public override Field Convert(GroupValue fieldDef, ITemplateRegistry templateRegistry, ConversionContext context) { var name = new QName(fieldDef.GetString("Name"), fieldDef.GetString("Ns")); bool optional = fieldDef.GetBool("Optional"); GroupValue exponentDef = fieldDef.GetGroup("Exponent"); GroupValue exponentOperatorDef = exponentDef.GetGroup("Operator").GetGroup(0); Operator exponentOperator = GetOperator(exponentOperatorDef.Group); ScalarValue exponentDefaultValue = ScalarValue.Undefined; if (exponentDef.IsDefined("InitialValue")) exponentDefaultValue = new IntegerValue(exponentDef.GetInt("InitialValue")); GroupValue mantissaDef = fieldDef.GetGroup("Mantissa"); GroupValue mantissaOperatorDef = mantissaDef.GetGroup("Operator").GetGroup(0); Operator mantissaOperator = GetOperator(mantissaOperatorDef.Group); ScalarValue mantissaDefaultValue = ScalarValue.Undefined; if (mantissaDef.IsDefined("InitialValue")) mantissaDefaultValue = new LongValue(mantissaDef.GetInt("InitialValue")); ComposedScalar composedDecimal = Util.ComposedDecimal(name, exponentOperator, exponentDefaultValue, mantissaOperator, mantissaDefaultValue, optional); IFieldValue retAuxId; if (fieldDef.TryGetValue("AuxId", out retAuxId) && retAuxId!=null) { composedDecimal.Id = retAuxId.ToString(); } return composedDecimal; }
public ComposedScalar(QName name, FASTType type, Scalar[] fields, bool optional, ComposedValueConverter valueConverter) : base(name, optional) { this.fields = fields; this.valueConverter = valueConverter; this.type = type; }
static FastConstants() { ANY_TYPE = new QName("any"); ERROR = FastAlertSeverity.ERROR; WARN = FastAlertSeverity.WARN; FATAL = FastAlertSeverity.FATAL; DYNAMIC = new ErrorType("Dynamic"); STATIC = new ErrorType("Static"); REPORTABLE = new ErrorType("Reportable"); S1_INVALID_XML = new ErrorCode(STATIC, 1, "ERR S1", "Invalid XML", ERROR); S2_OPERATOR_TYPE_INCOMP = new ErrorCode(STATIC, 2, "ERR S2", "Incompatible operator and type", ERROR); S3_INITIAL_VALUE_INCOMP = new ErrorCode(STATIC, 3, "ERR S3", "Incompatible initial value", ERROR); S4_NO_INITIAL_VALUE_FOR_CONST = new ErrorCode(STATIC, 4, "ERR S4", "Fields with constant operators must have a default value defined.", ERROR); S5_NO_INITVAL_MNDTRY_DFALT = new ErrorCode(STATIC, 5, "ERR S5", "No initial value for mandatory field with default operator", ERROR); D1_FIELD_APP_INCOMP = new ErrorCode(DYNAMIC, 1, "ERR D1", "Field cannot be converted to type of application field", ERROR); D2_INT_OUT_OF_RANGE = new ErrorCode(DYNAMIC, 2, "ERR D2", "The integer value is out of range for the specified integer type.", WARN); D3_CANT_ENCODE_VALUE = new ErrorCode(DYNAMIC, 3, "ERR D3", "The value cannot be encoded for the given operator.", ERROR); D4_INVALID_TYPE = new ErrorCode(DYNAMIC, 4, "ERR D4", "The previous value is not the same type as the type of the current field.", ERROR); D5_NO_DEFAULT_VALUE = new ErrorCode(DYNAMIC, 5, "ERR D5", "If no prior value is set and the field is not present, there must be a default value or the optional flag must be set.", ERROR); D6_MNDTRY_FIELD_NOT_PRESENT = new ErrorCode(DYNAMIC, 6, "ERR D6", "A mandatory field must have a value", ERROR); D7_SUBTRCTN_LEN_LONG = new ErrorCode(DYNAMIC, 7, "ERR D7", "The subtraction length is longer than the base value.", ERROR); D8_TEMPLATE_NOT_EXIST = new ErrorCode(DYNAMIC, 8, "ERR D8", "The referenced template does not exist.", ERROR); D9_TEMPLATE_NOT_REGISTERED = new ErrorCode(DYNAMIC, 9, "ERR D9", "The template has not been registered.", ERROR); R1_LARGE_DECIMAL = new ErrorCode(REPORTABLE, 1, "ERR R1", "Decimal exponent does not fit into range -63...63", WARN); R4_NUMERIC_VALUE_TOO_LARGE = new ErrorCode(REPORTABLE, 4, "ERR R4", "The value is too large.", WARN); R5_DECIMAL_CANT_CONVERT_TO_INT = new ErrorCode(REPORTABLE, 5, "ERR R5", "The decimal value cannot convert to an integer because of trailing decimal part.", WARN); R7_PMAP_OVERLONG = new ErrorCode(REPORTABLE, 7, "ERR R7", "The presence map is overlong.", WARN); R8_PMAP_TOO_MANY_BITS = new ErrorCode(REPORTABLE, 8, "ERR R8", "The presence map has too many bits.", WARN); R9_STRING_OVERLONG = new ErrorCode(REPORTABLE, 9, "ERR R9", "The string is overlong.", ERROR); GENERAL_ERROR = new ErrorCode(DYNAMIC, 100, "GENERAL", "An error has occurred.", ERROR); IMPOSSIBLE_EXCEPTION = new ErrorCode(DYNAMIC, 101, "IMPOSSIBLE", "This should never happen.", ERROR); IO_ERROR = new ErrorCode(DYNAMIC, 102, "IOERROR", "An IO error occurred.", FATAL); PARSE_ERROR = new ErrorCode(DYNAMIC, 103, "PARSEERR", "An exception occurred while parsing.", ERROR); LENGTH_FIELD = new QName("length", TEMPLATE_DEFINITION_1_1); }
public Group(QName name, Field[] fields, bool optional) : base(name, optional) { var expandedFields = new List<Field>(); var references = new List<StaticTemplateReference>(); for (int i = 0; i < fields.Length; i++) { if (fields[i] is StaticTemplateReference) { var currentTemplate = (StaticTemplateReference)fields[i]; Field[] referenceFields = currentTemplate.Template.Fields; for (int j = 1; j < referenceFields.Length; j++) expandedFields.Add(referenceFields[j]); references.Add(currentTemplate); } else { expandedFields.Add(fields[i]); } } this.fields = expandedFields.ToArray(); fieldDefinitions = fields; fieldIndexMap = ConstructFieldIndexMap(this.fields); fieldNameMap = ConstructFieldNameMap(this.fields); fieldIdMap = ConstructFieldIdMap(this.fields); introspectiveFieldMap = ConstructInstrospectiveFields(this.fields); usesPresenceMap_Renamed_Field = DeterminePresenceMapUsage(this.fields); staticTemplateReferences = references.ToArray(); }
protected Field(string name, string key, bool optional, string id) { this.name = new QName(name); this.key = new QName(key); this.optional = optional; this.id = id; }
public override Field Convert(GroupValue fieldDef, TemplateRegistry templateRegistry, ConversionContext context) { string name = fieldDef.GetString("Name"); string ns = fieldDef.GetString("Ns"); var qname = new QName(name, ns); var fields = GroupConverter.ParseFieldInstructions(fieldDef, templateRegistry, context); bool optional = fieldDef.GetBool("Optional"); Scalar length = null; if (fieldDef.IsDefined("Length")) { var lengthDef = fieldDef.GetGroup("Length"); QName lengthName; string id = null; if (lengthDef.IsDefined("Name")) { var nameDef = lengthDef.GetGroup("Name"); lengthName = new QName(nameDef.GetString("Name"), nameDef.GetString("Ns")); if (nameDef.IsDefined("AuxId")) id = nameDef.GetString("AuxId"); } else lengthName = Global.CreateImplicitName(qname); var operator_Renamed = Operator.NONE; if (lengthDef.IsDefined("Operator")) operator_Renamed = GetOperator(lengthDef.GetGroup("Operator").GetGroup(0).GetGroup()); var initialValue = ScalarValue.UNDEFINED; if (lengthDef.IsDefined("InitialValue")) initialValue = (ScalarValue) lengthDef.GetValue("InitialValue"); length = new Scalar(lengthName, Type.U32, operator_Renamed, initialValue, optional) {Id = id}; } return new Sequence(qname, length, fields, optional); }
public override int GetId(QName name) { MessageTemplate template = nameMap[name]; if (template == null || !templateMap.ContainsKey(template)) return - 1; return templateMap[template]; }
private static Field createComposedDecimal(System.Xml.XmlElement fieldNode, QName name, bool optional, System.Xml.XmlNode mantissaNode, System.Xml.XmlNode exponentNode, ParsingContext context) { string mantissaOperator = "none"; string exponentOperator = "none"; ScalarValue mantissaDefaultValue = ScalarValue.UNDEFINED; ScalarValue exponentDefaultValue = ScalarValue.UNDEFINED; QName mantissaKey = null; QName exponentKey = null; string mantissaDictionary = context.Dictionary; string exponentDictionary = context.Dictionary; string mantissaNamespace = context.Namespace; string exponentNamespace = context.Namespace; if ((mantissaNode != null) && mantissaNode.HasChildNodes) { System.Xml.XmlElement operatorElement = GetElement((System.Xml.XmlElement) mantissaNode, 1); mantissaOperator = operatorElement.Name; if (operatorElement.HasAttribute("value")) mantissaDefaultValue = FASTType.I64.GetValue(operatorElement.GetAttribute("value")); if (operatorElement.HasAttribute("ns")) mantissaNamespace = operatorElement.GetAttribute("ns"); if (operatorElement.HasAttribute("key")) mantissaKey = new QName(operatorElement.GetAttribute("key"), mantissaNamespace); if (operatorElement.HasAttribute("dictionary")) mantissaDictionary = operatorElement.GetAttribute("dictionary"); } if ((exponentNode != null) && exponentNode.HasChildNodes) { System.Xml.XmlElement operatorElement = GetElement((System.Xml.XmlElement) exponentNode, 1); exponentOperator = operatorElement.Name; if (operatorElement.HasAttribute("value")) exponentDefaultValue = FASTType.I32.GetValue(operatorElement.GetAttribute("value")); if (operatorElement.HasAttribute("ns")) exponentNamespace = operatorElement.GetAttribute("ns"); if (operatorElement.HasAttribute("key")) exponentKey = new QName(operatorElement.GetAttribute("key"), exponentNamespace); if (operatorElement.HasAttribute("dictionary")) exponentDictionary = operatorElement.GetAttribute("dictionary"); } ComposedScalar scalar = Util.ComposedDecimal(name, Operator.Operator.GetOperator(exponentOperator), exponentDefaultValue, Operator.Operator.GetOperator(mantissaOperator), mantissaDefaultValue, optional); Scalar exponent = scalar.Fields[0]; exponent.Dictionary = exponentDictionary; if (exponentKey != null) exponent.Key = exponentKey; Scalar mantissa = scalar.Fields[1]; mantissa.Dictionary = mantissaDictionary; if (mantissaKey != null) mantissa.Key = mantissaKey; if (fieldNode.HasAttribute("id")) scalar.Id = fieldNode.GetAttribute("id"); return scalar; }
public ComposedScalar(QName name, FastType fastType, Scalar[] fields, bool optional, IComposedValueConverter valueConverter) : base(name, optional) { _fields = fields; _valueConverter = valueConverter; _fastType = fastType; }
public override Field Convert(GroupValue fieldDef, TemplateRegistry templateRegistry, ConversionContext context) { var name = new QName(fieldDef.GetString("Name"), fieldDef.GetString("Ns")); if (!templateRegistry.IsDefined(name)) { throw new System.SystemException("Referenced template " + name + " not defined."); } return new StaticTemplateReference(templateRegistry.get_Renamed(name)); }
public override Field Convert(GroupValue fieldDef, ITemplateRegistry templateRegistry, ConversionContext context) { var name = new QName(fieldDef.GetString("Name"), fieldDef.GetString("Ns")); MessageTemplate template; if (templateRegistry.TryGetTemplate(name, out template)) return new StaticTemplateReference(template); throw new ArgumentOutOfRangeException("fieldDef", name, "Referenced template name not defined."); }
public Group(QName name, string childNamespace, Field[] fields, bool optional) : base(name, optional) { _childNamespace = childNamespace; Init(fields, out _fieldDefinitions, out _fields, out _fieldIndexMap, out _fieldNameMap, out _introspectiveFieldMap, out _usesPresenceMapRenamedField, out _staticTemplateReferences); }
public Group(Group other) : base(other) { _childNamespace = other._childNamespace; _typeReference = other._typeReference; Init(other._fieldDefinitions.CloneArray(), out _fieldDefinitions, out _fields, out _fieldIndexMap, out _fieldNameMap, out _introspectiveFieldMap, out _usesPresenceMapRenamedField, out _staticTemplateReferences); }
public override void Add(int templateId, QName templateName) { MessageTemplate template; if (!_defNameMap.TryGetValue(templateName, out template)) throw new ArgumentOutOfRangeException("templateName", templateName, "The template is not defined."); _regTemplateMap[template] = templateId; _regIdMap[templateId] = template; NotifyTemplateRegistered(template, templateId); }
public ParsingContext(XmlElement node, ParsingContext parent) { _parent = parent; if (node.HasAttribute("templateNs")) TemplateNamespace = node.GetAttribute("templateNs"); if (node.HasAttribute("ns")) Namespace = node.GetAttribute("ns"); if (node.HasAttribute("dictionary")) Dictionary = node.GetAttribute("dictionary"); if (node.HasAttribute("name")) _name = new QName(node.GetAttribute("name"), Namespace); }
public Sequence(QName name, Scalar length, Field[] fields, bool optional) : base(name, optional) { _group = new Group(name, fields, optional); if (length == null) { _length = CreateLength(name, optional); _implicitLength = true; } else _length = length; }
public Scalar(QName name, FASTType type, OperatorCodec operatorCodec, ScalarValue defaultValue, bool optional) : base(name, optional) { InitBlock(); operator_Renamed = operatorCodec.Operator; this.operatorCodec = operatorCodec; dictionary = "global"; this.defaultValue = defaultValue ?? ScalarValue.UNDEFINED; this.type = type; typeCodec = type.GetCodec(operator_Renamed, optional); initialValue = ((defaultValue == null) || defaultValue.Undefined)?this.type.DefaultValue:defaultValue; operator_Renamed.Validate(this); }
private Scalar(QName name, FastType fastType, Operator op, OperatorCodec operatorCodec, ScalarValue defaultValue, bool optional) : base(name, optional) { _operator = op; _operatorCodec = operatorCodec; _dictionary = DictionaryFields.Global; _defaultValue = defaultValue ?? ScalarValue.Undefined; _fastType = fastType; _typeCodec = fastType.GetCodec(op, optional); _initialValue = (defaultValue == null || defaultValue.IsUndefined) ? _fastType.DefaultValue : defaultValue; op.Validate(this); }
public override Field Convert(GroupValue fieldDef, ITemplateRegistry templateRegistry, ConversionContext context) { string name = fieldDef.GetString("Name"); string ns = fieldDef.GetString("Ns"); var qname = new QName(name, ns); Field[] fields = GroupConverter.ParseFieldInstructions(fieldDef, templateRegistry, context); bool optional = fieldDef.GetBool("Optional"); Scalar length = null; IFieldValue retLength; if (fieldDef.TryGetValue("Length", out retLength) && retLength!=null) { GroupValue lengthDef = (GroupValue)retLength; QName lengthName; string id = null; IFieldValue retName; if (lengthDef.TryGetValue("Name", out retName) && retName != null) { GroupValue nameDef = (GroupValue)retName; lengthName = new QName(nameDef.GetString("Name"), nameDef.GetString("Ns")); IFieldValue retAuxId; if (nameDef.TryGetValue("AuxId", out retAuxId) && retAuxId != null) id = retAuxId.ToString(); } else lengthName = Global.CreateImplicitName(qname); Operator op = Operator.None; IFieldValue retOperator; if (lengthDef.TryGetValue("Operator", out retOperator) && retOperator != null) op = GetOperator(((GroupValue)retOperator).GetGroup(0).Group); ScalarValue initialValue = ScalarValue.Undefined; IFieldValue retInitialValue; if (lengthDef.TryGetValue("InitialValue", out retInitialValue) && retInitialValue != null) initialValue = (ScalarValue) retInitialValue; length = new Scalar(lengthName, FastType.U32, op, initialValue, optional) {Id = id}; } var sequence = new Sequence(qname, length, fields, optional); IFieldValue retTypeRef; if (fieldDef.TryGetValue("TypeRef", out retTypeRef) && retTypeRef != null) { GroupValue typeRef = (GroupValue)retTypeRef; string typeRefName = typeRef.GetString("Name"); string typeRefNs = ""; // context.getNamespace(); IFieldValue rettypeRefNs; if (typeRef.TryGetValue("Ns", out rettypeRefNs) && rettypeRefNs!=null) typeRefNs = rettypeRefNs.ToString(); sequence.TypeReference = new QName(typeRefName, typeRefNs); } return sequence; }
private Scalar ParseSequenceLengthField(QName name, System.Xml.XmlElement sequence, bool optional, ParsingContext parent) { System.Xml.XmlNodeList lengthElements = sequence.GetElementsByTagName("length"); if (lengthElements.Count == 0) { var implicitLength = new Scalar(Global.CreateImplicitName(name), FASTType.U32, Operator.Operator.NONE, ScalarValue.UNDEFINED, optional) {Dictionary = parent.Dictionary}; return implicitLength; } var length = (System.Xml.XmlElement) lengthElements.Item(0); var context = new ParsingContext(length, parent); return (Scalar) sequenceLengthParser.Parse(length, optional, context); }
public static bool Average(IEnumerator<QName> left, out QName result) { decimal sum = 0; decimal count = 0; if (left.MoveNext()) { count++; sum += left.Current.GetValueOrDefault<decimal>(); while (left.MoveNext()) { count++; sum += left.Current.GetValueOrDefault<decimal>(); } } result = (sum / count).CreateLiteral(); // always returns true - means that execution avareage will always succeed if arguments match list criteria. return true; }
public override Field Convert(GroupValue fieldDef, TemplateRegistry templateRegistry, ConversionContext context) { var name = new QName(fieldDef.GetString("Name"), fieldDef.GetString("Ns")); bool optional = fieldDef.GetBool("Optional"); var exponentDef = fieldDef.GetGroup("Exponent"); var exponentOperatorDef = exponentDef.GetGroup("Operator").GetGroup(0); var exponentOperator = GetOperator(exponentOperatorDef.GetGroup()); var exponentDefaultValue = ScalarValue.UNDEFINED; if (exponentDef.IsDefined("InitialValue")) exponentDefaultValue = new IntegerValue(exponentDef.GetInt("InitialValue")); var mantissaDef = fieldDef.GetGroup("Mantissa"); var mantissaOperatorDef = mantissaDef.GetGroup("Operator").GetGroup(0); var mantissaOperator = GetOperator(mantissaOperatorDef.GetGroup()); var mantissaDefaultValue = ScalarValue.UNDEFINED; if (mantissaDef.IsDefined("InitialValue")) mantissaDefaultValue = new LongValue(mantissaDef.GetInt("InitialValue")); return Util.ComposedDecimal(name, exponentOperator, exponentDefaultValue, mantissaOperator, mantissaDefaultValue, optional); }
static Names() { Example = Logics.Names.Internal.Uri.CreateDomain("http://www.example.com/logics/example#"); Brain = Example.CreateName("brain"); DatabaseName = Example.CreateName("database"); SecondDatabaseName = Example.CreateName("secondDatabase"); Frans = Example.CreateName("Frans"); Maria = Example.CreateName("Maria"); Jos = Example.CreateName("Jos"); Rita = Example.CreateName("Rita"); Geert = Example.CreateName("Geert"); Caroline = Example.CreateName("Caroline"); Dirk = Example.CreateName("Dirk"); Greta = Example.CreateName("Greta"); Paul = Example.CreateName("Paul"); Dp = Example.CreateName("dp"); Sex = Example.CreateName("sex"); SpouseIn = Example.CreateName("spouseIn"); ChildIn = Example.CreateName("childIn"); Father = Example.CreateName("father"); Mother = Example.CreateName("mother"); Parent = Example.CreateName("parent"); Child = Example.CreateName("child"); Daughter = Example.CreateName("daughter"); Son = Example.CreateName("son"); Ancestor = Example.CreateName("ancestor"); Descendent = Example.CreateName("descendent"); Grandfather = Example.CreateName("grandfather"); Grandmother = Example.CreateName("grandmother"); Grandparent = Example.CreateName("grandparent"); Grandchild = Example.CreateName("grandchild"); Granddaughter = Example.CreateName("granddaughter"); Grandson = Example.CreateName("grandson"); FirstName = Example.CreateName("firstName"); LastName = Example.CreateName("lastName"); Age = Example.CreateName("age"); Female = Example.CreateName("female"); Male = Example.CreateName("male"); Person = Example.CreateName("Person"); }
private static string GetSimpleTypeInternal(this OpenXmlGeneratorServices services, QName qname) { if (_mapping.TryGetValue(qname, out var mapped)) { return(mapped); } if (services.TryGetEnum(qname, out var @enum, out var ns)) { return($"EnumValue<{ns}.{@enum.Name}>"); } throw new InvalidOperationException($"Could not find simple type mapping for {qname}"); }
private static Field CreateComposedDecimal(XmlElement fieldNode, QName name, bool optional, XmlNode mantissaNode, XmlNode exponentNode, ParsingContext context) { string mantissaOperator = "none"; string exponentOperator = "none"; ScalarValue mantissaDefaultValue = ScalarValue.Undefined; ScalarValue exponentDefaultValue = ScalarValue.Undefined; QName mantissaKey = null; QName exponentKey = null; string mantissaDictionary = context.Dictionary; string exponentDictionary = context.Dictionary; string mantissaNamespace = context.Namespace; string exponentNamespace = context.Namespace; if ((mantissaNode != null) && mantissaNode.HasChildNodes) { XmlElement operatorElement = GetElement((XmlElement)mantissaNode, 1); mantissaOperator = operatorElement.LocalName; if (operatorElement.HasAttribute("value")) { mantissaDefaultValue = FastType.I64.GetValue(operatorElement.GetAttribute("value")); } if (operatorElement.HasAttribute("ns")) { mantissaNamespace = operatorElement.GetAttribute("ns"); } if (operatorElement.HasAttribute("key")) { mantissaKey = new QName(operatorElement.GetAttribute("key"), mantissaNamespace); } if (operatorElement.HasAttribute("dictionary")) { mantissaDictionary = operatorElement.GetAttribute("dictionary"); } } if ((exponentNode != null) && exponentNode.HasChildNodes) { XmlElement operatorElement = GetElement((XmlElement)exponentNode, 1); exponentOperator = operatorElement.LocalName; if (operatorElement.HasAttribute("value")) { exponentDefaultValue = FastType.I32.GetValue(operatorElement.GetAttribute("value")); } if (operatorElement.HasAttribute("ns")) { exponentNamespace = operatorElement.GetAttribute("ns"); } if (operatorElement.HasAttribute("key")) { exponentKey = new QName(operatorElement.GetAttribute("key"), exponentNamespace); } if (operatorElement.HasAttribute("dictionary")) { exponentDictionary = operatorElement.GetAttribute("dictionary"); } } ComposedScalar scalar = Util.ComposedDecimal(name, Operator.GetOperator(exponentOperator), exponentDefaultValue, Operator.GetOperator(mantissaOperator), mantissaDefaultValue, optional); Scalar exponent = scalar.Fields[0]; exponent.Dictionary = exponentDictionary; if (exponentKey != null) { exponent.Key = exponentKey; } Scalar mantissa = scalar.Fields[1]; mantissa.Dictionary = mantissaDictionary; if (mantissaKey != null) { mantissa.Key = mantissaKey; } if (fieldNode.HasAttribute("id")) { scalar.Id = fieldNode.GetAttribute("id"); } return(scalar); }
/// <summary> /// Retrieves type definition of the attribute in an element. /// </summary> /// <param name="elem"> /// element name </param> /// <returns> schema definition of the type of the attribute </returns> public virtual TypeDefinition attribute_type_definition(QName elem) { return(_model.lookupAttributeDeclaration(elem.local(), elem.@namespace())); }
public QName NewColumnSchemaQName(QName table, SimpleName name) { return(this.NewColumnQName(table, name.Name, name.IsNameQuoted)); }
private bool AssertXPath(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc, bool debug) { if (IsException()) { return(false); } else { IEnumerator iter = assertion.EnumerateAxis(XdmAxis.Namespace); while (iter.MoveNext()) { XdmNode namespace1 = (XdmNode)iter.Current; if (namespace1.NodeName != null) { assertXpc.DeclareNamespace(namespace1.NodeName.LocalName, namespace1.StringValue); } } XPathExecutable exp = assertXpc.Compile(assertion.StringValue); XPathSelector s = exp.Load(); QName resultVar = new QName("result"); if (exp.GetRequiredCardinalityForVariable(resultVar) == '0') { if (result.value is XdmItem) // this path used in XSLT tests { s.ContextItem = ((XdmItem)result.value); } } else { s.SetVariable(resultVar, result.value); } bool b = s.EffectiveBooleanValue(); if (!b && debug) { driver.println("XPath assertion " + assertion.StringValue + " failed"); try { string ass = assertion.StringValue; int eq = ass.IndexOf("="); if (eq > 0) { ass = ass.Substring(0, eq); exp = assertXpc.Compile(ass); s = exp.Load(); if (exp.GetRequiredCardinalityForVariable(resultVar) == null) { if (result.value is XdmItem) // this path used in XSLT tests { s.ContextItem = ((XdmItem)result.value); } } else { s.SetVariable(resultVar, result.value); } XdmValue val = s.Evaluate(); driver.println("Actual result of " + ass + ": " + val.ToString()); } } catch (Exception err) {} driver.println("Actual results: " + result.value); } return(b); } }
public QName NewAutoName(string prefix, QName schema, QName parent, int type) { return(this.NewAutoName(prefix, null, schema, parent, type)); }
/// <summary> /// Adds a variable to current scope. /// /// used for static checking.... i.e. presence of variables /// </summary> /// <param name="var"> /// variable name to add. </param> public virtual void add_variable(QName @var) { set_variable(@var, (AnyType)null); }
public static string GetSimpleType(this OpenXmlGeneratorServices context, QName qname, bool isList) { var type = context.GetSimpleTypeInternal(qname); return(isList ? $"ListValue<{type}>" : type); }
private static MemberModel GetMember(MemberInfo info, FlagType baseFlags) { MemberModel member = new MemberModel(); member.Name = info.name.localName; member.Flags = baseFlags; member.Access = Visibility.Public; member.Namespace = "public"; if (info is SlotInfo) { SlotInfo slot = info as SlotInfo; member.Flags |= FlagType.Variable; if (slot.kind == TraitMember.Const) { member.Flags |= FlagType.Constant; } if (slot.value is Namespace) { member.Flags |= FlagType.Namespace; member.Value = '"' + (slot.value as Namespace).uri + '"'; } member.Type = ImportType(slot.type); } else if (info is MethodInfo) { switch (info.kind) { case TraitMember.Setter: member.Flags |= FlagType.Setter; break; case TraitMember.Getter: member.Flags |= FlagType.Getter; break; default: member.Flags |= FlagType.Function; break; } MethodInfo method = info as MethodInfo; QName type = method.returnType; member.Type = ImportType(type); member.Parameters = new List <MemberModel>(); int n = method.paramTypes.Length; int defaultValues = (method.optionalValues != null) ? n - method.optionalValues.Length : n; for (int i = 0; i < n; i++) { MemberModel param = new MemberModel(); param.Name = (!inSWF && method.paramNames != null) ? method.paramNames[i] : "param" + i; type = method.paramTypes[i]; param.Type = ImportType(type); if (param.Name[0] == '.' && param.Type == "Array") // ...rest { param.Type = ""; } else if (i >= defaultValues) { SetDefaultValue(param, method.optionalValues[i - defaultValues]); } member.Parameters.Add(param); } } else { return(null); } return(member); }
public Scalar(QName name, FastType fastType, Operator op, ScalarValue defaultValue, bool optional) : this(name, fastType, op, op.GetCodec(fastType), defaultValue, optional) { }
private static MemberList GetMembers(List <MemberInfo> abcMembers, FlagType baseFlags, QName instName) { MemberList list = new MemberList(); string package = instName.uri; string protect = instName.ToString(); foreach (MemberInfo info in abcMembers) { MemberModel member = GetMember(info, baseFlags); if (member == null) { continue; } string uri = info.name.uri ?? ""; if (uri.Length > 0) { if (uri == "private" || package == "private") { continue; } else if (uri == protect) { member.Access = Visibility.Protected; member.Namespace = "protected"; } else if (uri == package) { member.Access = Visibility.Internal; member.Namespace = "internal"; } else if (uri == "http://adobe.com/AS3/2006/builtin") { member.Access = Visibility.Public; member.Namespace = "AS3"; } else if (uri == "http://www.adobe.com/2006/flex/mx/internal") { continue; } else if (uri == "http://www.adobe.com/2006/actionscript/flash/proxy") { member.Access = Visibility.Public; member.Namespace = "flash_proxy"; } else if (uri == "http://www.adobe.com/2006/actionscript/flash/objectproxy") { member.Access = Visibility.Public; member.Namespace = "object_proxy"; } else // unknown namespace { member.Access = Visibility.Public; member.Namespace = "internal"; } } if (thisDocs != null) { GetMemberDoc(member); } list.Add(member); } return(list); }
public override bool MoveToAttribute(string name) { var qn = new QName(this, name); return(MoveToAttribute(qn.LocalName, qn.Namespace)); }
public override string?GetAttribute(string name) { var qn = new QName(this, name); return(GetAttribute(qn.LocalName, qn.Namespace)); }
/// <summary> /// Expands a qname and uses the default function namespace if unprefixed. /// </summary> /// <param name="name"> /// qname to expand. </param> /// <returns> true on success. </returns> public virtual bool expand_function_qname(QName name) { return(expand_qname(name, default_function_namespace())); }
// overwrites, or creates public virtual void set_variable(QName @var, AnyType val) { IDictionary scope = current_scope(); scope[@var] = val; }
/// <summary> /// Expands the qname's prefix into a namespace. /// </summary> /// <param name="name"> /// qname to expand. </param> /// <returns> true on success. </returns> public virtual bool expand_qname(QName name) { return(expand_qname(name, null)); }
public bool HasReportedError(QName errorCode) { return(errorsReported != null && errorsReported.Contains(errorCode)); }
/* * Set a XPath2 sequence into a variable. */ public virtual void set_variable(QName @var, ResultSequence val) { IDictionary scope = current_scope(); scope[@var] = val; }
private bool TestAssertion2(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc, XPathCompiler catalogXpc, bool debug) { string tag = assertion.NodeName.LocalName; if (tag.Equals("assert-eq")) { return(assertEq(assertion, result, assertXpc)); } else if (tag.Equals("assert-deep-eq")) { return(assertDeepEq(assertion, result, assertXpc)); } else if (tag.Equals("assert-permutation")) { return(assertPermutation(assertion, result, assertXpc)); } else if (tag.Equals("assert-xml")) { return(assertXml(assertion, result, assertXpc, catalogXpc, debug)); } else if (tag.Equals("serialization-matches")) { return(AssertSerializationMatches(assertion, result, catalogXpc)); } else if (tag.Equals("assert-serialization-error")) { return(AssertSerializationError(assertion, result, assertXpc)); } else if (tag.Equals("assert-empty")) { return(assertEmpty(result.value)); } else if (tag.Equals("assert-count")) { return(assertCount(assertion, result)); } else if (tag.Equals("assert")) { return(AssertXPath(assertion, result, assertXpc, debug)); } else if (tag.Equals("assert-string-value")) { return(AssertstringValue(assertion, result, debug)); } else if (tag.Equals("assert-serialization")) { return(AssertSerialization(assertion, result, catalogXpc, debug)); } else if (tag.Equals("assert-type")) { return(AssertType(assertion, result, assertXpc)); } else if (tag.Equals("assert-true")) { return(AssertTrue(result)); } else if (tag.Equals("assert-false")) { return(AssertFalse(result)); } else if (tag.Equals("assert-warning")) { return(AssertWarning()); } else if (tag.Equals("assert-message")) { XdmNode subAssertion = (XdmNode)catalogXpc.EvaluateSingle("*", assertion); foreach (XdmNode message in xslMessages) { if (TestAssertion2(subAssertion, new SingleResultDoc(message, ""), assertXpc, catalogXpc, debug)) { return(true); } } return(false); } else if (tag.Equals("assert-result-document")) { XdmNode subAssertion = (XdmNode)catalogXpc.EvaluateSingle("*", assertion); XmlUrlResolver res = new XmlUrlResolver(); Uri uri = new Uri(driver.getResultsDir() + "/results/output.xml"); uri = res.ResolveUri(uri, assertion.GetAttributeValue(new QName("uri"))); SingleResultDoc doc = GetSecondaryResult(uri); if (doc == null) { System.Console.WriteLine("**** No output document found for " + uri); return(false); } bool ok = TestAssertion2(subAssertion, doc, assertXpc, catalogXpc, debug); if (!ok) { System.Console.WriteLine("**** Assertion failed for result-document " + uri); } return(ok); } else if (tag.Equals("error")) { bool b = false; try { b = IsException() && compareExpectedError(assertion); } catch (Exception) { if (GetException() is StaticError) { string expectedError = assertion.GetAttributeValue(new QName("code")); QName expectedErrorQ; if (expectedError.Equals("*")) { expectedErrorQ = null; } else if (expectedError.StartsWith("Q{")) { expectedErrorQ = QName.FromEQName(expectedError); } else { expectedErrorQ = new QName("err", JNamespaceConstant.ERR, expectedError); } JFastStringBuffer fsb = new JFastStringBuffer(100); fsb.append("Expected "); fsb.append(expectedErrorQ.LocalName); fsb.append("; got "); fsb.append("err:XXX"); fsb.setLength(fsb.length() - 1); wrongError = fsb.ToString(); return(true); } if (GetException() is DynamicError) { string expectedError = assertion.GetAttributeValue(new QName("code")); QName expectedErrorQ; if (expectedError.Equals("*")) { expectedErrorQ = null; } else if (expectedError.StartsWith("Q{")) { expectedErrorQ = QName.FromEQName(expectedError); } else { expectedErrorQ = new QName("err", JNamespaceConstant.ERR, expectedError); } JFastStringBuffer fsb = new JFastStringBuffer(100); fsb.append("Expected "); fsb.append(expectedErrorQ.LocalName); fsb.append("; got "); fsb.append("err:XXX"); fsb.setLength(fsb.length() - 1); wrongError = fsb.ToString(); return(true); } } return(b); } else if (tag.Equals("all-of")) { foreach (XdmItem child in catalogXpc.Evaluate("*", assertion)) { if (!TestAssertion((XdmNode)child, result, assertXpc, catalogXpc, debug)) { return(false); } } return(true); } else if (tag.Equals("any-of")) { bool partialSuccess = false; foreach (XdmItem child in catalogXpc.Evaluate("*", assertion)) { if (TestAssertion((XdmNode)child, result, assertXpc, catalogXpc, debug)) { if (wrongError != null) { partialSuccess = true; continue; } return(true); } } return(partialSuccess); } else if (tag.Equals("not")) { XdmNode subAssertion = (XdmNode)catalogXpc.EvaluateSingle("*", assertion); return(!TestAssertion(subAssertion, result, assertXpc, catalogXpc, debug)); } throw new Exception("Unknown assertion element " + tag); }
public void go(String[] args) { processor.SetProperty("http://saxon.sf.net/feature/trace-external-functions", "true"); testSuiteDir = args[0]; if (testSuiteDir.EndsWith("/")) { testSuiteDir = testSuiteDir.Substring(0, testSuiteDir.Length - 1); } saxonResultsDir = args[1]; if (saxonResultsDir.EndsWith("/")) { saxonResultsDir = saxonResultsDir.Substring(0, testSuiteDir.Length - 1); } Hashtable exceptions = new Hashtable(); if (args.Length > 1) { testPattern = (args[2]); // TODO: allow a regex } for (int i = 0; i < args.Length; i++) { if (args[i].Equals("-w")) { //showWarnings = true; } } fileComparer = new FileComparer(processor, testSuiteDir); XPathCompiler xpc = processor.NewXPathCompiler(); xpc.DeclareNamespace("t", testURI); xpc.DeclareVariable(new QName("", "param")); findSourcePath = xpc.Compile("//t:test-suite/t:sources/t:source[@ID=$param]"); findCollection = xpc.Compile("//t:test-suite/t:sources/t:collection[@ID=$param]"); xpc = processor.NewXPathCompiler(); xpc.DeclareNamespace("t", testURI); xpc.DeclareVariable(new QName("", "testcase")); xpc.DeclareVariable(new QName("", "moduleuri")); findModule = xpc.Compile("for $m in $testcase/t:module[@namespace=$moduleuri] " + "return concat('file:///" + testSuiteDir + "/', root($testcase)/t:test-suite/t:sources/t:module[@ID=string($m)]/@FileName, '.xq')"); //xpc = processor.NewXPathCompiler(); //xpc.DeclareNamespace("saxon", "http://saxon.sf.net/"); //xpc.DeclareVariable(new QName("", "actual")); //xpc.DeclareVariable(new QName("", "gold")); //xpc.DeclareVariable(new QName("", "debug")); //compareDocuments = xpc.Compile("saxon:deep-equal($actual, $gold, (), if ($debug) then 'JNCPS?!' else 'JNCPS')"); QName testCaseNT = new QName(testURI, "test-case"); QName nameNT = new QName(testURI, "name"); QName queryNT = new QName(testURI, "query"); QName inputNT = new QName(testURI, "input"); QName inputFileNT = new QName(testURI, "input-file"); QName inputUriNT = new QName(testURI, "input-URI"); QName defaultCollectionNT = new QName(testURI, "defaultCollection"); QName outputFileNT = new QName(testURI, "output-file"); QName expectedErrorNT = new QName(testURI, "expected-error"); QName schemaNT = new QName(testURI, "schema"); QName contextItemNT = new QName(testURI, "contextItem"); QName inputQueryNT = new QName(testURI, "input-query"); QName sourceDocumentNT = new QName(testURI, "source-document"); QName errorNT = new QName(testURI, "error"); QName validationNT = new QName(testURI, "validation"); QName discretionaryItemsNT = new QName(testURI, "discretionary-items"); QName discretionaryFeatureNT = new QName(testURI, "discretionary-feature"); QName discretionaryChoiceNT = new QName(testURI, "discretionary-choice"); QName initialContextNodeNT = new QName(testURI, "initial-context-node"); QName fileAtt = new QName("", "file"); QName filePathAtt = new QName("", "FilePath"); QName fileNameAtt = new QName("", "FileName"); QName errorIdAtt = new QName("", "error-id"); QName compareAtt = new QName("", "compare"); QName nameAtt = new QName("", "name"); QName behaviorAtt = new QName("", "behavior"); QName qnameAtt = new QName("", "qname"); QName modeAtt = new QName("", "mode"); QName validatesAtt = new QName("", "validates"); QName variableAtt = new QName("", "variable"); QName roleAtt = new QName("", "role"); DocumentBuilder builder = processor.NewDocumentBuilder(); XdmNode exceptionsDoc = builder.Build(new Uri(saxonResultsDir + "/exceptions.xml")); // The exceptions.xml file contains details of tests that aren't to be run, for example // because they have known bugs or require special configuration IEnumerator exceptionTestCases = exceptionsDoc.EnumerateAxis(XdmAxis.Descendant, new QName("", "exception")); while (exceptionTestCases.MoveNext()) { XdmNode n = (XdmNode)exceptionTestCases.Current; String nameAttVal = n.StringValue; char[] seps = { ' ', '\n', '\t' }; String[] parts = nameAttVal.Split(seps); foreach (string p in parts) { if (!exceptions.ContainsKey(p)) { exceptions.Add(p, "Exception"); } } } // Hash table containing all source documents. The key is the document name in the // catalog, the value is the corresponding document node Hashtable sourceDocs = new Hashtable(50); // Load the catalog XdmNode catalog = builder.Build(new Uri(testSuiteDir + "/XQTScatalog.xml")); // Add all Static Typing test cases to the exceptions list xpc = processor.NewXPathCompiler(); xpc.DeclareNamespace("t", testURI); XPathSelector st = xpc.Compile("//t:test-group[@name='StaticTyping']//t:test-case").Load(); st.ContextItem = catalog; IEnumerator ste = st.GetEnumerator(); while (ste.MoveNext()) { XdmNode testCase = (XdmNode)ste.Current; exceptions.Add(testCase.GetAttributeValue(nameAtt), "StaticTypingException"); } // Create the results file and log file results = new StreamWriter(saxonResultsDir + "/results" + processor.ProductVersion + "n.xml"); log = new StreamWriter(saxonResultsDir + "/log" + processor.ProductVersion + "n.xml"); log.WriteLine("Testing Saxon " + processor.ProductVersion); results.WriteLine("<test-suite-result xmlns='http://www.w3.org/2005/02/query-test-XQTSResult'>"); // Pre-load all the schemas SchemaManager mgr = processor.SchemaManager; IEnumerator se = catalog.EnumerateAxis(XdmAxis.Descendant, schemaNT); while (se.MoveNext()) { XdmNode schemaNode = (XdmNode)se.Current; log.WriteLine("Loading schema " + schemaNode.GetAttributeValue(fileNameAtt)); Uri location = new Uri(testSuiteDir + "/" + schemaNode.GetAttributeValue(fileNameAtt)); mgr.Compile(location); } total = 0; IEnumerator testCases = catalog.EnumerateAxis(XdmAxis.Descendant, testCaseNT); while (testCases.MoveNext()) { total++; } // Process the test cases in turn testCases = catalog.EnumerateAxis(XdmAxis.Descendant, testCaseNT); while (testCases.MoveNext()) { XdmNode testCase = (XdmNode)testCases.Current; String testName = testCase.GetAttributeValue(nameAtt); if (testPattern != null && !testName.StartsWith(testPattern)) { continue; } if (exceptions.ContainsKey(testName)) { continue; } log.WriteLine("Test " + testName); // Compile the query String errorCode = null; String filePath = testCase.GetAttributeValue(filePathAtt); XdmNode query = getChildElement(testCase, queryNT); String queryName = query.GetAttributeValue(nameAtt); String queryPath = testSuiteDir + "/Queries/XQuery/" + filePath + queryName + ".xq"; XQueryCompiler compiler = processor.NewXQueryCompiler(); compiler.BaseUri = new Uri(queryPath).ToString(); compiler.QueryResolver = new XqtsModuleResolver(testCase, findModule); compiler.SchemaAware = true; // Set all queries to schema-aware, because we don't really know whether they will have to handle typed input or not. IList <StaticError> errors = new List <StaticError>(); compiler.ErrorList = errors; XQueryEvaluator xqe = null; FileStream stream = null; try { stream = new FileStream(queryPath, FileMode.Open, FileAccess.Read, FileShare.Read); xqe = compiler.Compile(stream).Load(); } catch (Exception e) { if (errors.Count > 0 && ((StaticError)errors[0]).ErrorCode != null) { errorCode = ((StaticError)errors[0]).ErrorCode.LocalName; } else if (e is StaticError && ((StaticError)e).ErrorCode != null) { log.WriteLine(e.Message); errorCode = ((StaticError)e).ErrorCode.LocalName; } else { log.WriteLine(e.Message); errorCode = "ErrorXXX"; } } finally { if (stream != null) { stream.Close(); } } // if the query compiled successfully, try to run it String outputPath = null; if (errorCode == null && xqe != null) { // Supply any input documents IEnumerator en = testCase.EnumerateAxis(XdmAxis.Child, inputFileNT); while (en.MoveNext()) { XdmNode file = (XdmNode)en.Current; String var = file.GetAttributeValue(variableAtt); if (var != null) { String sourceName = file.StringValue; XdmNode sourceDoc; if (sourceDocs.ContainsKey(sourceName)) { sourceDoc = (XdmNode)sourceDocs[sourceName]; } else { sourceDoc = buildSource(catalog, builder, sourceName); sourceDocs.Add(sourceName, sourceDoc); } xqe.SetExternalVariable(new QName("", var), sourceDoc); } } // Supply any input URIs IEnumerator eu = testCase.EnumerateAxis(XdmAxis.Child, inputUriNT); while (eu.MoveNext()) { XdmNode file = (XdmNode)eu.Current; String var = file.GetAttributeValue(variableAtt); if (var != null) { String sourceName = file.StringValue; if (sourceName.StartsWith("collection")) { // Supply a collection URI. // This seems to be the only way to distinguish a document URI // from a collection URI. String uri = "collection:" + sourceName; XPathSelector xpe = findCollection.Load(); xpe.SetVariable(new QName("", "param"), new XdmAtomicValue(sourceName)); xpe.ContextItem = catalog; XdmNode collectionNode = (XdmNode)xpe.EvaluateSingle(); if (collectionNode == null) { log.WriteLine("*** Collection " + sourceName + " not found"); } processor.RegisterCollection(new Uri(uri), getCollection(collectionNode)); xqe.SetExternalVariable(new QName("", var), new XdmAtomicValue(uri)); } else { // Supply a document URI. // We exploit the fact that the short name of the document is // always the same as the file name in these tests. With one exception! if (sourceName == "Char010D") { sourceName = "0x010D"; } String uri = "file:///" + testSuiteDir + "/TestSources/" + sourceName + ".xml"; xqe.SetExternalVariable(new QName("", var), new XdmAtomicValue(uri)); } } } // Supply the default collection if required XdmNode defaultCollection = getChildElement(testCase, defaultCollectionNT); if (defaultCollection != null) { String sourceName = defaultCollection.StringValue; XPathSelector xpe = findCollection.Load(); xpe.SetVariable(new QName("", "param"), new XdmAtomicValue(sourceName)); xpe.ContextItem = catalog; XdmNode collectionNode = (XdmNode)xpe.EvaluateSingle(); if (collectionNode == null) { log.WriteLine("*** Collection " + sourceName + " not found"); } processor.RegisterCollection(null, getCollection(collectionNode)); } // Supply any external variables defined as the result of a separate query IEnumerator ev = testCase.EnumerateAxis(XdmAxis.Child, inputQueryNT); while (ev.MoveNext()) { XdmNode inputQuery = (XdmNode)ev.Current; String fileName = inputQuery.GetAttributeValue(nameAtt); String subQueryPath = testSuiteDir + "/Queries/XQuery/" + filePath + fileName + ".xq"; XQueryCompiler subCompiler = processor.NewXQueryCompiler(); compiler.BaseUri = new Uri(subQueryPath).ToString(); FileStream subStream = new FileStream(subQueryPath, FileMode.Open, FileAccess.Read, FileShare.Read); XdmValue value = subCompiler.Compile(subStream).Load().Evaluate(); String var = inputQuery.GetAttributeValue(variableAtt); xqe.SetExternalVariable(new QName("", var), value); } // Supply the context item if required IEnumerator ci = testCase.EnumerateAxis(XdmAxis.Child, contextItemNT); while (ci.MoveNext()) { XdmNode file = (XdmNode)ci.Current; String sourceName = file.StringValue; if (!sourceDocs.ContainsKey(sourceName)) { XdmNode doc = buildSource(catalog, builder, sourceName); sourceDocs.Add(sourceName, doc); } XdmNode sourceDoc = (XdmNode)sourceDocs[sourceName]; xqe.ContextItem = sourceDoc; } // Create a serializer for the output outputPath = saxonResultsDir + "/results.net/" + filePath + queryName + ".out"; Serializer sr = processor.NewSerializer(); try { sr.SetOutputFile(outputPath); sr.SetOutputProperty(new QName("", "method"), "xml"); sr.SetOutputProperty(new QName("", "omit-xml-declaration"), "yes"); sr.SetOutputProperty(new QName("", "indent"), "no"); } catch (DynamicError) { // probably means that no output directory exists, which is probably because // an error is expected outputPath = saxonResultsDir + "/results.net/" + filePath + queryName + ".out"; sr.SetOutputFile(outputPath); } // Finally, run the query try { xqe.Run(sr); } catch (DynamicError e) { log.WriteLine(e.Message); QName code = e.ErrorCode; if (code != null && code.LocalName != null) { errorCode = code.LocalName; } else { errorCode = "ErrYYYYY"; } } catch (Exception e2) { log.WriteLine("Unexpected exception: " + e2.Message); log.WriteLine(e2.StackTrace); errorCode = "CRASH!!!"; } } // Compare actual results with expected results if (errorCode != null) { // query returned an error at compile time or run-time, check this was expected string expectedError = ""; bool matched = false; IEnumerator en = testCase.EnumerateAxis(XdmAxis.Child, expectedErrorNT); while (en.MoveNext()) { XdmNode error = (XdmNode)en.Current; String expectedErrorCode = error.StringValue; expectedError += (expectedErrorCode + " "); if (expectedErrorCode.Equals(errorCode)) { matched = true; feedback.Feedback(passed++, failed, total); log.WriteLine("Error " + errorCode + " as expected"); results.WriteLine("<test-case name='" + testName + "' result='pass'/>"); break; } } if (!matched) { if (expectedError.Equals("")) { feedback.Feedback(passed, failed++, total); log.WriteLine("Error " + errorCode + ", expected success"); results.WriteLine("<test-case name='" + testName + "' result='fail' comment='error " + errorCode + ", expected success'/>"); results.WriteLine("<--" + filePath + queryName + "-->"); } else { feedback.Feedback(passed++, failed, total); log.WriteLine("Error " + errorCode + ", expected " + expectedError); results.WriteLine("<test-case name='" + testName + "' result='pass' comment='error " + errorCode + ", expected " + expectedError + "'/>"); results.WriteLine("<--" + filePath + queryName + "-->"); } } } else { // query returned no error bool matched = false; String diag = ""; IEnumerator en = testCase.EnumerateAxis(XdmAxis.Child, outputFileNT); while (en.MoveNext()) { XdmNode outputFile = (XdmNode)en.Current; String fileName = testSuiteDir + "/ExpectedTestResults/" + filePath + outputFile.StringValue; String comparator = outputFile.GetAttributeValue(compareAtt); if (comparator.Equals("Inspect")) { matched = true; feedback.Feedback(passed++, failed, total); results.WriteLine("<test-case name='" + testName + "' result='inspect'/>"); results.WriteLine("<--" + filePath + queryName + "-->"); break; } else { String comparison = fileComparer.compare(outputPath, fileName, comparator); matched = (comparison == "OK" || comparison.StartsWith("#")); if (matched) { feedback.Feedback(passed++, failed, total); results.WriteLine("<test-case name='" + testName + "' result='pass'/>"); diag = diag + ("<!-- " + comparison + " -->\n"); break; } } } if (!matched) { string expectedError = ""; IEnumerator ee = testCase.EnumerateAxis(XdmAxis.Child, expectedErrorNT); while (ee.MoveNext()) { XdmNode error = (XdmNode)ee.Current; String expectedErrorCode = error.StringValue; expectedError += (expectedErrorCode + " "); } if (expectedError.Equals("")) { feedback.Feedback(passed, failed++, total); log.WriteLine("Results differ from expected results"); results.WriteLine("<test-case name='" + testName + "' result='fail'/>"); results.WriteLine("<--" + filePath + queryName + "-->"); } else { feedback.Feedback(passed, failed++, total); log.WriteLine("Error " + expectedError + "expected but not reported"); results.WriteLine("<test-case name='" + testName + "' result='fail' comment='expected error " + expectedError + "not reported'/>"); results.WriteLine("<--" + filePath + queryName + "-->"); } } } } results.WriteLine("</test-suite-result>"); results.Close(); log.Close(); }
internal static object ToObject(this Value value) { //Check for null/empty if (value == null) { return(null); } //Is it a sequence? Seq seq = value as Seq; if (seq != null) { return(new IterEnum(seq.iter())); } // Is it a node? ANode node = value as ANode; if (node != null) { return(Node.Node.Get(node)); } // Get the Java object object obj = value.toJava(); // Clean up non-.NET values if (obj is java.lang.Number) { int i; double d; if (int.TryParse(obj.ToString(), out i)) { obj = i; } else if (double.TryParse(obj.ToString(), out d)) { obj = d; } else if (obj is BigInteger) { BigInteger bigInteger = (BigInteger)obj; obj = Convert.ToDecimal(bigInteger.toString()); } else if (obj is BigDecimal) { BigDecimal bigDecimal = (BigDecimal)obj; obj = Convert.ToDecimal(bigDecimal.toString()); } } else if (obj is XMLGregorianCalendar) { XMLGregorianCalendar date = (XMLGregorianCalendar)obj; obj = XmlConvert.ToDateTime(date.toXMLFormat(), XmlDateTimeSerializationMode.RoundtripKind); } else if (obj is Duration) { Duration duration = (Duration)obj; obj = XmlConvert.ToTimeSpan(duration.toString()); } else if (obj is QName) { QName qname = (QName)obj; obj = new XmlQualifiedName(qname.getLocalPart(), qname.getNamespaceURI()); } return(obj); }
/// <summary> /// does variable exist in current scope ? /// </summary> /// <param name="var"> /// variable name. </param> /// <returns> true if it does. </returns> public virtual bool variable_exists(QName @var) { IDictionary scope = current_scope(); return(scope.Contains(@var)); }
public override bool HasAttribute(QName attributeName) { return group.HasAttribute(attributeName); }
public Sequence(QName name, Field[] fields, bool optional) : this(name, CreateLength(name, optional), fields, optional) { implicitLength = true; }
private void ProcessAttribute (XPathNavigator nav) { // skip attributes from non-default namespace if (nav.NamespaceURI != string.Empty) { return; } string value = nav.Value; switch (nav.LocalName) { case "cdata-section-elements": if (value.Length > 0) { cdSectsList.AddRange (XslNameUtil.FromListString (value, nav)); } break; case "method": if (value.Length == 0) { break; } switch (value) { case "xml": method = OutputMethod.XML; break; case "html": omitXmlDeclaration = true; method = OutputMethod.HTML; break; case "text": omitXmlDeclaration = true; method = OutputMethod.Text; break; default: method = OutputMethod.Custom; customMethod = XslNameUtil.FromString (value, nav); if (customMethod.Namespace == String.Empty) { IXmlLineInfo li = nav as IXmlLineInfo; throw new XsltCompileException (new ArgumentException ( "Invalid output method value: '" + value + "'. It" + " must be either 'xml' or 'html' or 'text' or QName."), nav.BaseURI, li != null ? li.LineNumber : 0, li != null ? li.LinePosition : 0); } break; } break; case "version": if (value.Length > 0) { this.version = value; } break; case "encoding": if (value.Length > 0) { try { this.encoding = System.Text.Encoding.GetEncoding (value); } catch (ArgumentException) { // MS.NET just leaves the default encoding when encoding is unknown } catch (NotSupportedException) { // Workaround for a bug in System.Text, it throws invalid exception } } break; case "standalone": switch (value) { case "yes": this.standalone = StandaloneType.YES; break; case "no": this.standalone = StandaloneType.NO; break; default: if (stylesheetVersion != "1.0") break; IXmlLineInfo li = nav as IXmlLineInfo; throw new XsltCompileException (new XsltException ( "'" + value + "' is an invalid value for 'standalone'" + " attribute.", (Exception) null), nav.BaseURI, li != null ? li.LineNumber : 0, li != null ? li.LinePosition : 0); } break; case "doctype-public": this.doctypePublic = value; break; case "doctype-system": this.doctypeSystem = value; break; case "media-type": if (value.Length > 0) { this.mediaType = value; } break; case "omit-xml-declaration": switch (value) { case "yes": this.omitXmlDeclaration = true; break; case "no": this.omitXmlDeclaration = false; break; default: if (stylesheetVersion != "1.0") break; IXmlLineInfo li = nav as IXmlLineInfo; throw new XsltCompileException (new XsltException ( "'" + value + "' is an invalid value for 'omit-xml-declaration'" + " attribute.", (Exception) null), nav.BaseURI, li != null ? li.LineNumber : 0, li != null ? li.LinePosition : 0); } break; case "indent": indent = value; if (stylesheetVersion != "1.0") break; switch (value) { case "yes": case "no": break; default: switch (method) { case OutputMethod.Custom: break; default: throw new XsltCompileException (String.Format ("Unexpected 'indent' attribute value in 'output' element: '{0}'", value), null, nav); } break; } break; default: if (stylesheetVersion != "1.0") break; IXmlLineInfo xli = nav as IXmlLineInfo; throw new XsltCompileException (new XsltException ( "'" + nav.LocalName + "' is an invalid attribute for 'output'" + " element.", (Exception) null), nav.BaseURI, xli != null ? xli.LineNumber : 0, xli != null ? xli.LinePosition : 0); } }
/// <summary> /// Constructor for SchemaElemTest. /// </summary> /// <param name="arg"> /// QName argument. </param> public SchemaElemTest(QName arg) { _arg = arg; }
public QNameManager(Database database) { this._catalogName = new QName(this, "PUBLIC", 1, false); }
public Scalar(QName name, FastType fastType, OperatorCodec operatorCodec, ScalarValue defaultValue, bool optional) : this(name, fastType, operatorCodec.Operator, operatorCodec, defaultValue, optional) { }
/// <summary> /// Expands a qname and uses the default type/element namespace if /// unprefixed. /// </summary> /// <param name="name"> /// qname to expand. </param> /// <returns> true on success. </returns> public virtual bool expand_elem_type_qname(QName name) { return(expand_qname(name, default_namespace())); }
public override string GetAttribute(QName qname) { return group.GetAttribute(qname); }
private XdmNode getChildElement(XdmNode parent, QName child) { IEnumerator e = parent.EnumerateAxis(XdmAxis.Child, child); return(e.MoveNext() ? (XdmNode)e.Current : null); }
private static Scalar CreateLength(QName name, bool optional) { return new Scalar(Global.CreateImplicitName(name), FASTType.U32, Operator.Operator.NONE, ScalarValue.UNDEFINED, optional); }
public void go(String[] args) { int passed = 0; int failed = 0; int total = 0; testSuiteDir = args[0]; if (testSuiteDir.EndsWith("/")) { testSuiteDir = testSuiteDir.Substring(0, testSuiteDir.Length - 1); } Hashtable exceptions = new Hashtable(); if (args.Length > 1) { testPattern = (args[1]); } for (int i = 0; i < args.Length; i++) { if (args[i].Equals("-w")) { //showWarnings = true; } } try { schemaAwareProcessor = new Processor(true); } catch (Exception) { Console.WriteLine("Cannot load Saxon-SA: continuing without it"); } processor.SetProperty("http://saxon.sf.net/feature/preferJaxpParser", "true"); if (schemaAwareProcessor != null) { schemaAwareProcessor.SetProperty("http://saxon.sf.net/feature/preferJaxpParser", "true"); } fileComparer = new FileComparer(processor, testSuiteDir); String testURI = "http://www.w3.org/2005/05/xslt20-test-catalog"; QName testCaseNT = new QName(testURI, "testcase"); QName nameNT = new QName(testURI, "name"); QName inputNT = new QName(testURI, "input"); QName outputNT = new QName(testURI, "output"); QName stylesheetNT = new QName(testURI, "stylesheet"); QName schemaNT = new QName(testURI, "schema"); QName initialModeNT = new QName(testURI, "initial-mode"); QName entryNamedTemplateNT = new QName(testURI, "entry-named-template"); QName sourceDocumentNT = new QName(testURI, "source-document"); QName stylesheetParametersNT = new QName(testURI, "stylesheet-parameters"); QName paramNT = new QName(testURI, "param"); QName resultDocumentNT = new QName(testURI, "result-document"); QName errorNT = new QName(testURI, "error"); QName validationNT = new QName(testURI, "validation"); QName discretionaryItemsNT = new QName(testURI, "discretionary-items"); QName discretionaryFeatureNT = new QName(testURI, "discretionary-feature"); QName discretionaryChoiceNT = new QName(testURI, "discretionary-choice"); QName discretionaryVersionNT = new QName(testURI, "discretionary-version"); QName initialContextNodeNT = new QName(testURI, "initial-context-node"); QName fileAtt = new QName("", "file"); QName errorIdAtt = new QName("", "error-id"); QName typeAtt = new QName("", "type"); QName nameAtt = new QName("", "name"); QName behaviorAtt = new QName("", "behavior"); QName specAtt = new QName("", "spec"); QName qnameAtt = new QName("", "qname"); QName modeAtt = new QName("", "mode"); QName validatesAtt = new QName("", "validates"); QName roleAtt = new QName("", "role"); DocumentBuilder builder = processor.NewDocumentBuilder(); XdmNode exceptionsDoc = builder.Build(new Uri(testSuiteDir + '/' + getResultDirectoryName() + "/exceptions.xml")); IEnumerator exceptionTestCases = exceptionsDoc.EnumerateAxis(XdmAxis.Descendant, testCaseNT); while (exceptionTestCases.MoveNext()) { XdmNode n = (XdmNode)exceptionTestCases.Current; String nameAttVal = n.GetAttributeValue(nameAtt); char[] seps = { ' ', '\n', '\t' }; String[] parts = nameAttVal.Split(seps); foreach (string p in parts) { if (!exceptions.ContainsKey(p)) { exceptions.Add(p, "Kilroy"); } } } XdmNode catalog = builder.Build(new Uri(testSuiteDir + "/catalog.xml")); results = new StreamWriter(testSuiteDir + "/SaxonResults.net/results" + processor.ProductVersion + ".xml"); log = new StreamWriter(testSuiteDir + "/SaxonResults.net/log" + processor.ProductVersion + "n.xml"); log.WriteLine("Testing Saxon " + processor.ProductVersion); results.WriteLine("<test-suite-result>"); results.WriteLine(" <implementation name='Saxon-SA' version='" + processor.ProductVersion + "' anonymous-result-column='false'>"); results.WriteLine(" <organization name='http://www.saxonica.com/' anonymous='false'/>"); results.WriteLine(" <submitter name='Michael Kay' email='*****@*****.**'/>"); outputDiscretionaryItems(); results.WriteLine(" </implementation>"); total = 0; IEnumerator testCases = catalog.EnumerateAxis(XdmAxis.Descendant, testCaseNT); while (testCases.MoveNext()) { total++; } testCases = catalog.EnumerateAxis(XdmAxis.Descendant, testCaseNT); while (testCases.MoveNext()) { bool useAssociated = false; XdmNode testCase = (XdmNode)testCases.Current; String testName = getChildElement(testCase, nameNT).StringValue; if (testPattern != null && !testName.StartsWith(testPattern)) { continue; } if (exceptions.ContainsKey(testName)) { continue; } if (isExcluded(testName)) { continue; } log.WriteLine("Test " + testName); XdmNode testInput = getChildElement(testCase, inputNT); XdmNode stylesheet = getChildElement(testInput, stylesheetNT); String absXSLName = null; if (stylesheet == null) { useAssociated = true; } else { absXSLName = testSuiteDir + "/TestInputs/" + stylesheet.GetAttributeValue(fileAtt); } XdmNode sourceDocument = getChildElement(testInput, sourceDocumentNT); String absXMLName = null; if (sourceDocument != null) { absXMLName = testSuiteDir + "/TestInputs/" + sourceDocument.GetAttributeValue(fileAtt); } bool schemaAware = false; bool recoverRecoverable = true; bool backwardsCompatibility = true; bool supportsDOE = true; bool recoverSESU0007 = false; bool useXSLT30 = false; XdmNode discretionaryItems = getChildElement(testCase, discretionaryItemsNT); if (discretionaryItems != null) { IEnumerator features = discretionaryItems.EnumerateAxis(XdmAxis.Child, discretionaryFeatureNT); while (features.MoveNext()) { XdmNode feature = (XdmNode)features.Current; String featureName = feature.GetAttributeValue(nameAtt); if ("schema_aware".Equals(featureName) || "Saxon-PE".Equals(featureName)) // TODO: test Saxon-PE properly { schemaAware = "on".Equals(feature.GetAttributeValue(behaviorAtt)); } else if ("XML_1.1".Equals(featureName)) { xml11 = "on".Equals(feature.GetAttributeValue(behaviorAtt)); } else if ("backwards_compatibility".Equals(featureName)) { backwardsCompatibility = "on".Equals(feature.GetAttributeValue(behaviorAtt)); } else if ("disabling_output_escaping".Equals(featureName)) { supportsDOE = "on".Equals(feature.GetAttributeValue(behaviorAtt)); } } IEnumerator choices = discretionaryItems.EnumerateAxis( XdmAxis.Child, discretionaryChoiceNT); while (choices.MoveNext()) { XdmNode choice = (XdmNode)choices.Current; String featureName = choice.GetAttributeValue(nameAtt); if ("error".Equals(choice.GetAttributeValue(behaviorAtt))) { recoverRecoverable = false; } else if ("SESU0007".Equals(featureName)) { recoverSESU0007 = "recovery".Equals(choice.GetAttributeValue(behaviorAtt)); } } IEnumerator versions = discretionaryItems.EnumerateAxis( XdmAxis.Child, discretionaryVersionNT); while (versions.MoveNext()) { XdmNode dv = (XdmNode)versions.Current; useXSLT30 = ("XSLT30" == dv.GetAttributeValue(specAtt)); } } if (!backwardsCompatibility) { // Saxon cannot run with BC switched off results.WriteLine(" <testcase name='" + testName + "' result='not run' comment='requires backwards-compatibility=off'/>"); continue; } if (!supportsDOE) { // Saxon cannot run with DOE switched off results.WriteLine(" <testcase name='" + testName + "' result='not run' comment='requires disable-output-escaping=off'/>"); continue; } if (recoverSESU0007) { // Saxon cannot recover from error SESU0007 results.WriteLine(" <testcase name='" + testName + "' result='not run' comment='requires recovery from error SESU0007'/>"); continue; } XdmNode initialMode = getChildElement(testInput, initialModeNT); QName initialModeName = null; if (initialMode != null) { String ini = initialMode.GetAttributeValue(qnameAtt); initialModeName = makeQName(ini, initialMode); } XdmNode initialTemplate = getChildElement(testInput, entryNamedTemplateNT); QName initialTemplateName = null; if (initialTemplate != null) { String ini = initialTemplate.GetAttributeValue(qnameAtt); initialTemplateName = makeQName(ini, initialTemplate); } XdmNode initialContextNode = getChildElement(testInput, initialContextNodeNT); String initialContextPath = null; if (initialContextNode != null) { initialContextPath = initialContextNode.StringValue; } XdmNode validation = getChildElement(testInput, validationNT); String validationMode = null; if (validation != null) { validationMode = validation.GetAttributeValue(modeAtt); } Hashtable paramTable = null; XdmNode paramList = getChildElement(testInput, stylesheetParametersNT); if (paramList != null) { paramTable = new Hashtable(5); IEnumerator paramIter = paramList.EnumerateAxis(XdmAxis.Child, paramNT); while (paramIter.MoveNext()) { XdmNode param = (XdmNode)paramIter.Current; QName name = makeQName(param.GetAttributeValue(qnameAtt), param); String value = param.StringValue; paramTable.Add(name, value); } } IEnumerator schemas = testInput.EnumerateAxis(XdmAxis.Child, schemaNT); while (schemas.MoveNext()) { XdmNode schema = (XdmNode)schemas.Current; if (schema == null) { break; } schemaAware = true; String role = schema.GetAttributeValue(roleAtt); if (("source-validator".Equals(role) || "source-reference".Equals(role)) /* && schema.GetAttributeValue(validatesAtt) != null */) { validationMode = "strict"; // TODO: control which source documents are validated... } } XdmNode testOutput = getChildElement(testCase, outputNT); XdmNode resultDocument = getChildElement(testOutput, resultDocumentNT); // TODO: handle alternative result documents String refFileName = null; String outFileName; String comparator = "xml"; if (resultDocument != null) { String relativePath = resultDocument.GetAttributeValue(fileAtt); int slash = relativePath.IndexOf('/'); if (slash > 0) { String relativeDir = relativePath.Substring(0, slash); String fullDir = testSuiteDir + '/' + getResultDirectoryName() + "/" + relativeDir; if (!Directory.Exists(fullDir)) { Directory.CreateDirectory(fullDir); } } refFileName = testSuiteDir + "/ExpectedTestResults/" + relativePath; outFileName = testSuiteDir + '/' + getResultDirectoryName() + "/" + relativePath; comparator = resultDocument.GetAttributeValue(typeAtt); } else { outFileName = testSuiteDir + '/' + getResultDirectoryName() + "/temp.out"; } XdmNode error = getChildElement(testOutput, errorNT); String expectedError = null; if (error != null) { expectedError = error.GetAttributeValue(errorIdAtt); } bool success; Exception xsltOutcome = runXSLT(testName, absXMLName, absXSLName, initialModeName, initialTemplateName, outFileName, paramTable, initialContextPath, useAssociated, schemaAware, validationMode, recoverRecoverable, useXSLT30); if (xsltOutcome == null) { success = true; if (expectedError != null && resultDocument == null) { log.WriteLine("Test failed. Expected error " + expectedError + ", got success"); feedback.Feedback(passed, failed++, total); success = false; results.WriteLine(" <testcase name='" + testName + "' result='differ' comment='Expected error " + expectedError + ", got success'/>"); } else { feedback.Feedback(passed++, failed, total); } } else { String errorCode = null; if (xsltOutcome is StaticError) { errorCode = ((StaticError)xsltOutcome).ErrorCode.LocalName; } else if (xsltOutcome is DynamicError) { errorCode = ((DynamicError)xsltOutcome).ErrorCode.LocalName; } if (expectedError != null && errorCode != null && errorCode.Equals(expectedError)) { feedback.Feedback(passed++, failed, total); log.WriteLine("Test succeeded (" + expectedError + ')'); results.WriteLine(" <testcase name='" + testName + "' result='full' comment='Error " + expectedError + " as expected'/>"); } else if (expectedError != null) { feedback.Feedback(passed++, failed, total); log.WriteLine("Test succeeded (??) (expected " + expectedError + ", got " + errorCode + ')'); results.WriteLine(" <testcase name='" + testName + "' result='different-error' comment='Expected " + expectedError + " got " + errorCode + "'/>"); } else { feedback.Feedback(passed, failed++, total); log.WriteLine("Test failed. Expected success, got " + errorCode); results.WriteLine(" <testcase name='" + testName + "' result='differ' comment='Expected success, got " + errorCode + "'/>"); results.WriteLine(" <!--" + xsltOutcome.Message + "-->"); } success = false; continue; } if (success) { String outcome = fileComparer.compare(outFileName, refFileName, comparator); if (outcome == "OK") { results.WriteLine(" <testcase name='" + testName + "' result='full'/>"); } else if (outcome.StartsWith("#")) { results.WriteLine(" <testcase name='" + testName + "' result='full' + comments='" + outcome.Substring(1) + "/>"); } else { results.WriteLine(" <testcase name='" + testName + "' result='differ' comments='" + outcome + "'/>"); } } } results.WriteLine("</test-suite-result>"); results.Close(); log.Close(); //} }
/// <summary> /// Run the transformation /// </summary> /// <param name="testName"></param> /// <param name="xml"></param> /// <param name="xsl"></param> /// <param name="initialMode"></param> /// <param name="initialTemplate"></param> /// <param name="outfile"></param> /// <param name="paramTable"></param> /// <param name="initialContextPath"></param> /// <param name="useAssociated"></param> /// <param name="schemaAware"></param> /// <param name="validationMode"></param> /// <param name="recoverRecoverable"></param> /// <returns>Either null, indicating success, or an Exception object with information about the failure</returns> protected Exception runXSLT(String testName, String xml, String xsl, QName initialMode, QName initialTemplate, String outfile, Hashtable paramTable, String initialContextPath, bool useAssociated, bool schemaAware, String validationMode, bool recoverRecoverable, bool useXSLT30) { Serializer sr = new Serializer(); sr.SetOutputFile(outfile); Processor f; if (noCacheTests.ContainsKey(testName)) { //create a custom Processor to avoid schema caching f = new Processor(true); } else if (schemaAware) { f = schemaAwareProcessor; if (f == null) { return(new DynamicError("Saxon-SA not available")); } } else if (xml11) { f = processor; // Use an Xml 1.1 processor } else { f = processor; } XdmNode source = null; IList errors = new ArrayList(); XsltCompiler compiler = f.NewXsltCompiler(); compiler.SchemaAware = schemaAware; compiler.ErrorList = errors; if (useXSLT30) { compiler.XsltLanguageVersion = "3.0"; } XsltExecutable sheet = null; XsltTransformer inst; if (useAssociated) { try { source = buildSource(f.NewDocumentBuilder(), xml, validationMode); } catch (Exception e) { log.WriteLine("Failed to build source document: " + e.Message); return(e); } try { sheet = compiler.CompileAssociatedStylesheet(source); } catch (Exception e) { log.WriteLine("Failed to compile stylesheet: " + e.Message); if (errors.Count > 0) { return((Exception)errors[0]); //QName code = ((StaticError)errors[0]).ErrorCode; //(code == null ? "Failed to compile stylesheet: " + e.Message : code.LocalName); } else { return(e); } } } else { Stream stream = new FileStream(xsl, FileMode.Open, FileAccess.Read); compiler.BaseUri = new Uri(xsl); try { sheet = compiler.Compile(stream); } catch (StaticError e) { if (errors.Count > 0) { return((StaticError)errors[0]); } else { log.WriteLine(e.Message); return(e); } } catch (Exception e2) { log.WriteLine("Unexpected CRASH: " + e2.Message); log.WriteLine(e2.StackTrace); return(e2); } finally { stream.Close(); } } if (initialContextPath != null) { if (source == null && xml != null) { try { source = buildSource(f.NewDocumentBuilder(), xml, validationMode); } catch (Exception e) { log.WriteLine("Failed to build source document: " + e.Message); return(e); } } XPathCompiler xc = f.NewXPathCompiler(); XPathExecutable exp = xc.Compile(initialContextPath); XPathSelector xpe = exp.Load(); xpe.ContextItem = source; XdmNode node = (XdmNode)xpe.EvaluateSingle(); source = node; } inst = sheet.Load(); if (source != null) { inst.InitialContextNode = source; } if (source == null && xml != null) { Stream stream = new FileStream(xml, FileMode.Open, FileAccess.Read); inst.SetInputStream(stream, new Uri(xml)); } if (initialMode != null) { inst.InitialMode = initialMode; } if (initialTemplate != null) { try { inst.InitialTemplate = initialTemplate; } catch (DynamicError e) { return(e); } } if (paramTable != null) { foreach (DictionaryEntry de in paramTable) { inst.SetParameter((QName)de.Key, new XdmAtomicValue(de.Value.ToString())); } } inst.BaseOutputUri = new Uri(outfile); inst.RecoveryPolicy = recoverRecoverable ? RecoveryPolicy.RecoverSilently : RecoveryPolicy.DoNotRecover; if ("strict" == validationMode) { inst.SchemaValidationMode = SchemaValidationMode.Strict; } else { inst.SchemaValidationMode = SchemaValidationMode.None; } //inst.setURIResolver(factory.getURIResolver()); //inst.setErrorListener(errorListener); //((Controller)inst).setRecoveryPolicy(recoverRecoverable ? Configuration.RECOVER_SILENTLY : Configuration.DO_NOT_RECOVER); // To avoid test results being dependent on the date and time (and timezone), set a fixed // date and time for the run //((Controller)inst).setCurrentDateTime(new DateTimeValue("2005-01-01T12:49:30.5+01:00")); try { inst.Run(sr); } catch (DynamicError e) { log.WriteLine(e.Message); return(e); } catch (Exception e2) { log.WriteLine("Unexpected CRASH: " + e2.Message); log.WriteLine(e2.StackTrace); return(e2); } return(null); // indicating success }
public NativeType(IType type, QName name) { _name = name; Type = type; }
/** * Run the tests * @param args command line arguments * @throws SAXException * @throws ParserConfigurationException * @throws XPathException * @throws IOException * @throws URISyntaxException */ public void go(String[] args) { if (args.Length == 0 || args[0] == "-?") { Console.WriteLine("SchemaTestSuiteDriver testDir [-w] [-onwards] -c:contributor? -s:setName? -g:groupName?"); } Processor processor = new Processor(true); Console.WriteLine("Testing Saxon " + processor.ProductVersion); testSuiteDir = args[0]; if (testSuiteDir.EndsWith("/")) { testSuiteDir = testSuiteDir.Substring(0, testSuiteDir.Length - 1); } String testSetPattern = null; // TODO use a regex String testGroupPattern = null; String contributor = null; Hashtable exceptions = new Hashtable(); for (int i = 1; i < args.Length; i++) { if (args[i] == ("-w")) { //showWarnings = true; } else if (args[i] == ("-onwards")) { onwards = true; } else if (args[i].StartsWith("-c:")) { contributor = args[i].Substring(3); } else if (args[i].StartsWith("-s:")) { testSetPattern = args[i].Substring(3); } else if (args[i].StartsWith("-g:")) { testGroupPattern = args[i].Substring(3); } else if (args[i] == "-?") { Console.WriteLine("Usage: SchemaTestSuiteDriver testDir [-w] [-s:testSetPattern] [-g:testGroupPattern]"); } } int total = 39700; int passed = 0; int failed = 0; try { xlinkHref = new QName("xlink", "http://www.w3.org/1999/xlink", "href"); QName testCaseNT = new QName("", "", "testcase"); QName commentNT = new QName("", "", "comment"); QName testSetRefNT = new QName(testNS, "testSetRef"); QName testGroupNT = new QName(testNS, "testGroup"); QName testSetNT = new QName(testNS, "testSet"); QName schemaTestNT = new QName(testNS, "schemaTest"); QName instanceTestNT = new QName(testNS, "instanceTest"); QName schemaDocumentNT = new QName(testNS, "schemaDocument"); QName instanceDocumentNT = new QName(testNS, "instanceDocument"); QName expectedNT = new QName(testNS, "expected"); QName currentNT = new QName(testNS, "current"); QName validityAtt = new QName("", "", "validity"); QName nameAtt = new QName("", "", "name"); QName contributorAtt = new QName("", "", "contributor"); QName setAtt = new QName("", "", "set"); QName groupAtt = new QName("", "", "group"); QName statusAtt = new QName("", "", "status"); QName bugzillaAtt = new QName("", "", "bugzilla"); QName targetNamespaceAtt = new QName("", "", "targetNamespace"); QName schemaVersion = new QName("saxon", "http://saxon.sf.net/", "schemaVersion"); DocumentBuilder builder = processor.NewDocumentBuilder(); builder.BaseUri = new Uri(testSuiteDir + "/"); XdmNode catalog = builder.Build( new FileStream(testSuiteDir + "/suite.xml", FileMode.Open, FileAccess.Read, FileShare.Read)); results = new StreamWriter(testSuiteDir + "/SaxonResults" + processor.ProductVersion + "n.xml"); results.Write("<testSuiteResults xmlns='" + testNS + "' xmlns:saxon='http://saxon.sf.net/' " + "suite='TS_2006' " + "processor='Saxon-SA (Java) 8.8++' submitDate='2007-01-05' publicationPermission='public'>\n"); XdmNode exceptionsDoc = builder.Build( new FileStream(testSuiteDir + "/exceptions.xml", FileMode.Open, FileAccess.Read, FileShare.Read)); IEnumerator exceptionTestCases = exceptionsDoc.EnumerateAxis(XdmAxis.Descendant, new QName("", "testcase")); while (exceptionTestCases.MoveNext()) { XdmNode testCase = (XdmNode)exceptionTestCases.Current; String set = testCase.GetAttributeValue(setAtt); String group = testCase.GetAttributeValue(groupAtt); String comment = getChildElement(testCase, commentNT).StringValue; exceptions[set + "#" + group] = comment; } IEnumerator testSets = catalog.EnumerateAxis(XdmAxis.Descendant, testSetRefNT); while (testSets.MoveNext()) { XdmNode testSetRef = (XdmNode)testSets.Current; XdmNode testSetDoc = getLinkedDocument(testSetRef, processor, false); XdmNode testSetElement = getChildElement(testSetDoc, testSetNT); if (testSetElement == null) { feedback.Message("test set doc has no TestSet child: " + testSetDoc.BaseUri, true); continue; } String testSetName = testSetElement.GetAttributeValue(nameAtt); if (testSetPattern != null && !testSetName.StartsWith(testSetPattern)) { continue; } if (contributor != null && contributor != testSetElement.GetAttributeValue(contributorAtt)) { continue; } bool needs11 = (testSetElement.GetAttributeValue(schemaVersion) == "1.1"); IEnumerator testGroups = testSetElement.EnumerateAxis(XdmAxis.Child, testGroupNT); while (testGroups.MoveNext()) { XdmNode testGroup = (XdmNode)testGroups.Current; String testGroupName = testGroup.GetAttributeValue(nameAtt); String exception = (String)exceptions[testSetName + "#" + testGroupName]; if (testGroupPattern != null && !testGroupName.StartsWith(testGroupPattern)) { continue; } Console.WriteLine("TEST SET " + testSetName + " GROUP " + testGroupName, false); if (onwards) { testGroupPattern = null; testSetPattern = null; } Processor testConfig = new Processor(true); if (needs11) { testConfig.SetProperty("http://saxon.sf.net/feature/xsd-version", "1.1"); } SchemaManager schemaManager = testConfig.SchemaManager; //testConfig.setHostLanguage(Configuration.XML_SCHEMA); testConfig.SetProperty("http://saxon.sf.net/feature/validation-warnings", "true"); IEnumerator schemaTests = testGroup.EnumerateAxis(XdmAxis.Child, schemaTestNT); bool schemaQueried = false; String bugzillaRef = null; while (schemaTests.MoveNext()) { XdmNode schemaTest = (XdmNode)schemaTests.Current; if (schemaTest == null) { break; } bugzillaRef = null; String testName = schemaTest.GetAttributeValue(nameAtt); if (exception != null) { results.Write("<testResult set='" + testSetName + "' group='" + testGroupName + "' test='" + testName + "' validity='notKnown' saxon:outcome='notRun' saxon:comment='" + exception + "'/>\n"); continue; } bool queried = false; XdmNode statusElement = getChildElement(schemaTest, currentNT); if (statusElement != null) { String status = statusElement.GetAttributeValue(statusAtt); queried = ("queried" == status); bugzillaRef = statusElement.GetAttributeValue(bugzillaAtt); } if (queried) { schemaQueried = true; } Console.WriteLine("TEST SCHEMA " + testName + (queried ? " (queried)" : "")); bool success = true; IEnumerator schemata = schemaTest.EnumerateAxis(XdmAxis.Child, schemaDocumentNT); while (schemata.MoveNext()) { XdmNode schemaDocumentRef = (XdmNode)schemata.Current; if (schemaDocumentRef == null) { break; } Console.WriteLine("Loading schema at " + schemaDocumentRef.GetAttributeValue(xlinkHref)); XdmNode schemaDoc = getLinkedDocument(schemaDocumentRef, testConfig, false); IEnumerator schemaDocKids = schemaDoc.EnumerateAxis(XdmAxis.Child); XdmNode schemaElement = null; while (schemaDocKids.MoveNext()) { schemaElement = (XdmNode)schemaDocKids.Current; if (schemaElement.NodeKind == XmlNodeType.Element) { break; } } String targetNamespace = schemaElement.GetAttributeValue(targetNamespaceAtt); //if (targetNamespace != null && schemaManager. isSchemaAvailable(targetNamespace)) { // do nothing // TODO: this is the only way I can get MS additional test addB132 to work. // It's not ideal: addSchemaSource() ought to be a no-op if the schema components // are already loaded, but in fact recompiling the imported schema document on its // own is losing the substitution group membership that was defined in the // importing document. //} else { IList errorList = new ArrayList(); schemaManager.ErrorList = errorList; try { schemaManager.Compile(schemaDoc); } catch (Exception e) { if (errorList.Count == 0) { feedback.Message("In " + testName + ", exception thrown but no errors in ErrorList\n", true); success = false; } } for (int i = 0; i < errorList.Count; i++) { if (errorList[i] is StaticError) { StaticError err = (StaticError)errorList[i]; if (!err.IsWarning) { success = false; break; } } else { feedback.Message("In " + testName + " wrong kind of error!" + errorList[i].GetType() + "\n", true); } } } XdmNode expected = getChildElement(schemaTest, expectedNT); bool expectedSuccess = expected == null || expected.GetAttributeValue(validityAtt) == "valid"; if (success == expectedSuccess) { passed++; } else { failed++; } feedback.Feedback(passed, failed, total); results.Write("<testResult set='" + testSetName + "' group='" + testGroupName + "' test='" + testName + "' validity='" + (success ? "valid" : "invalid") + (queried ? "' saxon:queried='true' saxon:bugzilla='" + bugzillaRef : "") + "' saxon:outcome='" + (success == expectedSuccess ? "same" : "different") + "'/>\n"); } IEnumerator instanceTests = testGroup.EnumerateAxis(XdmAxis.Child, instanceTestNT); while (instanceTests.MoveNext()) { XdmNode instanceTest = (XdmNode)instanceTests.Current; String testName = instanceTest.GetAttributeValue(nameAtt); if (exception != null) { results.Write("<testResult set='" + testSetName + "' group='" + testGroupName + "' test='" + testName + "' validity='notKnown' saxon:outcome='notRun' saxon:comment='" + exception + "'/>\n"); continue; } bool queried = false; XdmNode statusElement = getChildElement(instanceTest, currentNT); if (statusElement != null) { String status = statusElement.GetAttributeValue(statusAtt); queried = ("queried" == status); String instanceBug = statusElement.GetAttributeValue(bugzillaAtt); if (instanceBug != null) { bugzillaRef = instanceBug; } } queried |= schemaQueried; Console.WriteLine("TEST INSTANCE " + testName + (queried ? " (queried)" : "")); XdmNode instanceDocument = getChildElement(instanceTest, instanceDocumentNT); bool success = true; try { XdmNode instanceDoc = getLinkedDocument(instanceDocument, testConfig, true); } catch (Exception err) { success = false; } XdmNode expected = getChildElement(instanceTest, expectedNT); bool expectedSuccess = expected == null || expected.GetAttributeValue(validityAtt) == "valid"; if (success == expectedSuccess) { passed++; } else { failed++; } feedback.Feedback(passed, failed, total); results.Write("<testResult set='" + testSetName + "' group='" + testGroupName + "' test='" + testName + "' validity='" + (success ? "valid" : "invalid") + (queried ? "' saxon:queried='true' saxon:bugzilla='" + bugzillaRef : "") + "' saxon:outcome='" + (success == expectedSuccess ? "same" : "different") + "'/>\n"); } } } results.Write("</testSuiteResults>"); results.Close(); } catch (Exception e) { feedback.Message("Test failed: " + e.Message, true); } }
/// <summary> /// Obtains schema definition of the type of an element. /// </summary> /// <param name="elem"> /// name of element who's type is desired. </param> /// <returns> schema definition of type </returns> public virtual TypeDefinition element_type_definition(QName elem) { return(_model.lookupElementDeclaration(elem.local(), elem.@namespace())); }