Exemple #1
0
 /// <summary>
 /// Formats a Graph Header by creating an <strong>&lt;rdf:RDF&gt;</strong> element and adding namespace definitions
 /// </summary>
 /// <param name="namespaces">Namespaces</param>
 /// <returns></returns>
 public string FormatGraphHeader(INamespaceMapper namespaces)
 {
     this._mapper = new QNameOutputMapper(namespaces);
     StringBuilder output = new StringBuilder();
     output.Append(this.GetGraphHeaderBase());
     foreach (String prefix in namespaces.Prefixes)
     {
         if (!prefix.Equals("rdf"))
         {
             if (prefix.Equals(String.Empty))
             {
                 output.Append(" xmlns=\"" + WriterHelper.EncodeForXml(namespaces.GetNamespaceUri(prefix).ToString()) + "\"");
             }
             else
             {
                 output.Append(" xmlns:" + prefix + "=\"" + WriterHelper.EncodeForXml(namespaces.GetNamespaceUri(prefix).ToString()) + "\"");
             }
         }
     }
     output.Append(">");
     return output.ToString();
 }
Exemple #2
0
        /// <summary>
        /// Resolves a QName into a Uri using the Namespace Mapper and Base Uri provided
        /// </summary>
        /// <param name="qname">QName to resolve</param>
        /// <param name="nsmap">Namespace Map to resolve against</param>
        /// <param name="baseUri">Base Uri to resolve against</param>
        /// <returns></returns>
        public static String ResolveQName(String qname, INamespaceMapper nsmap, Uri baseUri)
        {
            String output;

            if (qname.StartsWith(":"))
            {
                //QName in Default Namespace
                if (nsmap.HasNamespace(String.Empty))
                {
                    //Default Namespace Defined
                    output = nsmap.GetNamespaceUri(String.Empty).ToString() + qname.Substring(1);
                }
                else
                {
                    //No Default Namespace so use Base Uri
                    //These type of QNames are scoped to the local Uri regardless of the type of the Base Uri
                    //i.e. these always result in Hash URIs
                    if (baseUri != null)
                    {
                        output = baseUri.ToString();
                        if (output.EndsWith("#"))
                        {
                            output += qname.Substring(1);
                        }
                        else
                        {
                            output += "#" + qname.Substring(1);
                        }
                    }
                    else
                    {
                        throw new RdfParseException("Cannot resolve a QName in the Default Namespace when there is no in-scope Base URI and no Default Namespace defined");
                    }
                }
            }
            else
            {
                //QName in some other Namespace
                String[] parts = qname.Split(':');
                if (parts.Length == 1)
                {
                    output = nsmap.GetNamespaceUri(String.Empty).ToString() + parts[0];
                }
                else
                {
                    output = nsmap.GetNamespaceUri(parts[0]).ToString() + parts[1];
                }
            }

            return output;
        }
        /// <summary>
        /// Initializes a new instance.
        /// </summary>
        /// <param name="dest">The destination stream.</param>
        /// <param name="nsMapper">The namespace prefix list to use.</param>
        /// <exception cref="ArgumentNullException">Any of the arguments is <see langword="null"/>.</exception>
        /// <remarks>
        /// <para>Initializes a new instance with the given destination stream and the given namespace prefix list.
        ///   All prefixes listed in <paramref name="nsMapper"/> will be declared in the resulting Turtle output, as the writer cannot know in advance which prefixes will actually be used.</para>
        /// </remarks>
        public SequentialTurtleWriter(StreamWriter dest, INamespaceMapper nsMapper)
        {
            if (dest == null) {
                throw new ArgumentNullException("dest");
            }
            if (nsMapper == null) {
                throw new ArgumentNullException("nsMapper");
            }

            this.dest = dest;
            this.nsMapper = nsMapper;

            foreach (var prefix in nsMapper.Prefixes) {
                dest.WriteLine("@prefix {0}: <{1}> .", prefix, nsMapper.GetNamespaceUri(prefix));
            }
        }
 /// <summary>
 /// Creates a new Turtle Formatter
 /// </summary>
 /// <param name="formatName">Format Name</param>
 /// <param name="nsmap">Namespace Map</param>
 protected TurtleFormatter(String formatName, INamespaceMapper nsmap)
     : base(formatName, new QNameOutputMapper(nsmap))
 {
 }
 internal TriplePatternPredicatePart(TriplePatternBuilder triplePatternBuilder, PatternItem subjectPatternItem, INamespaceMapper prefixes)
 {
     _subjectPatternItem   = subjectPatternItem;
     _prefixes             = prefixes;
     _triplePatternBuilder = triplePatternBuilder;
 }
Exemple #6
0
 /// <summary>
 /// Creates a new SPARQL Formatter using the given Namespace Map
 /// </summary>
 /// <param name="nsmap">Namespace Map</param>
 public SparqlFormatter(INamespaceMapper nsmap)
     : base("SPARQL", new QNameOutputMapper(nsmap))
 {
 }
        internal static string StringForNode(IResource node, INamespaceMapper pm)
        {
            SpinWrappedDataset model = null; // TODO change this for a queryModel
            StringBuilder      sb    = new StringBuilder();

            if (node.canAs(SP.ClassExpression))
            {
                ((IPrintable)SPINFactory.asExpression(node)).print(new BaseSparqlFactory(model, sb));
            }
            else if (node.canAs(SP.ClassVariable))
            {
                ((IPrintable)SPINFactory.asVariable(node)).print(new BaseSparqlFactory(model, sb));
            }
            else if (RDFUtil.sameTerm(node.getResource(RDF.PropertyType), SP.PropertyNot))
            {
                sb.Append("!(");
                sb.Append(StringForNode(node.getObject(SP.PropertyArg1), pm));
                sb.Append(")");
            }
            else if (RDFUtil.sameTerm(node.getResource(RDF.PropertyType), SP.PropertyOr))
            {
                sb.Append(StringForNode(node.getObject(SP.PropertyArg1), pm));
                sb.Append(" || ");
                sb.Append(StringForNode(node.getObject(SP.PropertyArg2), pm));
            }
            else if (RDFUtil.sameTerm(node.getResource(RDF.PropertyType), SP.PropertyAnd))
            {
                sb.Append(StringForNode(node.getObject(SP.PropertyArg1), pm));
                sb.Append(" && ");
                sb.Append(StringForNode(node.getObject(SP.PropertyArg2), pm));
            }
            else if (RDFUtil.sameTerm(node.getResource(RDF.PropertyType), SP.PropertyEq))
            {
                sb.Append(StringForNode(node.getObject(SP.PropertyArg1), pm));
                sb.Append("=");
                sb.Append(StringForNode(node.getObject(SP.PropertyArg2), pm));
            }
            else if (RDFUtil.sameTerm(node.getResource(RDF.PropertyType), SP.PropertyNeq))
            {
                sb.Append(StringForNode(node.getObject(SP.PropertyArg1), pm));
                sb.Append("!=");
                sb.Append(StringForNode(node.getObject(SP.PropertyArg2), pm));
            }
            else if (RDFUtil.sameTerm(node.getResource(RDF.PropertyType), SP.PropertyLt))
            {
                sb.Append(StringForNode(node.getObject(SP.PropertyArg1), pm));
                sb.Append("<");
                sb.Append(StringForNode(node.getObject(SP.PropertyArg2), pm));
            }
            else if (RDFUtil.sameTerm(node.getResource(RDF.PropertyType), SP.PropertyLeq))
            {
                sb.Append(StringForNode(node.getObject(SP.PropertyArg1), pm));
                sb.Append("<=");
                sb.Append(StringForNode(node.getObject(SP.PropertyArg2), pm));
            }
            else if (RDFUtil.sameTerm(node.getResource(RDF.PropertyType), SP.PropertyGt))
            {
                sb.Append(StringForNode(node.getObject(SP.PropertyArg1), pm));
                sb.Append(">");
                sb.Append(StringForNode(node.getObject(SP.PropertyArg2), pm));
            }
            else if (RDFUtil.sameTerm(node.getResource(RDF.PropertyType), SP.PropertyGeq))
            {
                sb.Append(StringForNode(node.getObject(SP.PropertyArg1), pm));
                sb.Append(">=");
                sb.Append(StringForNode(node.getObject(SP.PropertyArg2), pm));
            }
            else if (RDFUtil.sameTerm(node.getResource(RDF.PropertyType), SP.PropertyBound))
            {
                sb.Append("bound(");
                sb.Append(StringForNode(node.getObject(SP.PropertyArg1), pm));
                sb.Append(")");
            }
            else if (node.isUri())
            {
                sb.Append("<");
                sb.Append(node.Uri().ToString());
                sb.Append(">");
            }
            else if (node.isLiteral())
            {
                sb.Append(((ILiteralNode)node.getSource()).Value);
            }
            else
            {
                throw new Exception("Missing translation for expression " + node.getResource(RDF.PropertyType).Uri().ToString());
            }
            return(sb.ToString());
        }
Exemple #8
0
 /// <summary>
 /// Creates a new Thread Safe QName Output Mapper
 /// </summary>
 /// <param name="nsmapper">Namespace Mapper</param>
 public ThreadSafeQNameOutputMapper(INamespaceMapper nsmapper)
     : base(nsmapper)
 {
 }
 /// <summary>
 /// Gets an instance of the currently selected formatter using the given namespaces if possible
 /// </summary>
 /// <param name="namespaces">Namespaces</param>
 /// <returns></returns>
 public INodeFormatter GetFormatter(INamespaceMapper namespaces)
 {
     return(this.CurrentFormatter.CreateInstance(namespaces));
 }
 public ResultSetViewerForm(SparqlResultSet results, String title, INamespaceMapper nsmap)
     : this(results, title)
 {
     this._nsmap = nsmap;
     if (nsmap != null) this._formatter = new SparqlFormatter(nsmap);
 }
Exemple #11
0
 /// <summary>
 /// Creates a new SPARQL Formatter using the given Namespace Map
 /// </summary>
 /// <param name="nsmap">Namespace Map</param>
 public SparqlFormatter(INamespaceMapper nsmap)
     : base("SPARQL", new QNameOutputMapper(nsmap))
 {
     this._validEscapes = new char[] { '"', 'n', 't', 'u', 'U', 'r', '\\', '0', 'f', 'b', '\'' };
 }
Exemple #12
0
        public static void LoadGraphPrefixes(INamespaceMapper nm)
        {
            if (nm.HasNamespace(RoboKindPrefix))
            {
                return;
            }
            string s =
                @"
@prefix : <#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix daml: <http://www.daml.org/2001/03/daml+oil#> .
@prefix log: <http://www.w3.org/2000/10/swap/log.n3#> .
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix virtrdf: <http://www.openlinksw.com/schemas/virtrdf#> .
@prefix sswap: <http://sswapmeet.sswap.info/sswap/#> .
@prefix sioc: <http://rdfs.org/sioc/ns#> .
@prefix sioct: <http://rdfs.org/sioc/types#> .
@prefix atom: <http://atomowl.org/ontologies/atomrdf#> .
@prefix dc: <http://purl.org/dc/elements/1.1/> .
@prefix dct: <http://purl.org/dc/terms/> .
@prefix skos: <http://www.w3.org/2004/02/skos/core#> .
@prefix geo: <http://www.w3.org/2003/01/geo/wgs84_pos#> .
@prefix wikiont: <http://sw.deri.org/2005/04/wikipedia/wikiont.owl#> .
@prefix aowl: <http://atomowl.org/ontologies/atomrdf#> .
@prefix v: <http://www.openlinksw.com/schemas/drupal_v#> .
@prefix sd: <http://www.w3.org/ns/sparql-service-description#> .
@prefix dbpprop: <http://dbpedia.org/property/> .
@prefix dbpedia-owl:	<http://dbpedia.org/ontology/> .
@prefix dc: <http://purl.org/dc/elements/1.1/> .
@prefix grddl: <http://www.w3.org/2003/g/data-view#> .
@prefix xml: <http://www.w3.org/XML/1998/namespace> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix dnr: <http://www.dotnetrdf.org/configuration#> .
@prefix dotnetrdf: <http://www.dotnetrdf.org/configuration#> .
@prefix dc: <http://purl.org/dc/elements/1.1/>.
@prefix dcterms: <http://www.purl.org/dc/terms/>.
@prefix vann: <http://purl.org/vocab/vann/>.
@prefix vs: <http://www.w3.org/2003/06/sw-vocab-status/ns#>.
@prefix fmt: <http://www.w3.org/ns/formats/>.
@prefix siprolog: <http://" + CogbotServerWithPort + @"/siprolog#> .
@prefix robokind: <" +
                RoboKindURI + @"> .
";

            string ss =
                @"
fn http://www.w3.org/2005/xpath-functions
gmlxbt http://www.opengis.net/gml/3.3/xbt
sch http://www.ascc.net/xml/schematron
# gml http://www.opengis.net/gml/3.2
gml http://www.opengis.net/gml/_
gmd http://www.isotc211.org/2005/gmd
xlink http://www.w3.org/1999/xlink
xsl  http://www.w3.org/1999/XSL/Transform 
rdf  http://www.w3.org/1999/02/22-rdf-syntax-ns# 
p3q  http://www.w3.org/2004/01/rdxh/p3q-ns-example 
p3qr http://www.example.org/P3Q-rdf# 
p3dr http://www.example.org/TR/P3P/base# 
ont  http://www.daml.org/2001/03/daml+oil# 
s http://schema.org/
xsd http://www.w3.org/2001/XMLSchema#
eco http://www.ebusiness-unibw.org/ontologies/eclass/5.1.4/
gr http://purl.org/goodrelations/v1#
dc http://purl.org/dc/elements/1.1/
ao	http://purl.org/ao/core/
aoa	http://purl.org/ao/annotea/
aof	http://purl.org/ao/foaf/
aold	http://biotea.ws/ontologies/aold/
aos	http://purl.org/ao/selectors/
aot	http://purl.org/ao/types/
bibo	http://purl.org/ontology/bibo/
bif	bif:
bio2rdf_mesh	http://bio2rdf.org/ns/mesh#
bio2rdf_ns	http://bio2rdf.org/ns/bio2rdf#
chebi	http://purl.obolibrary.org/obo/CHEBI_
cnt	http://www.w3.org/2011/content#
dawgt	http://www.w3.org/2001/sw/DataAccess/tests/test-dawg#
dbpedia	http://dbpedia.org/resource/
dbpprop	http://dbpedia.org/property/
dc	http://purl.org/dc/elements/1.1/
dcterms	http://purl.org/dc/terms/
doco	http://purl.org/spar/doco/
fma	http://purl.org/obo/owl/FMA#FMA_
fn	http://www.w3.org/2005/xpath-functions/#
foaf	http://xmlns.com/foaf/0.1/
geo	http://www.w3.org/2003/01/geo/wgs84_pos#
go	http://purl.org/obo/owl/GO#GO_
gw_property	http://genewikiplus.org/wiki/Special:URIResolver/Property-3A
gw_wiki	http://genewikiplus.org/wiki/Special:URIResolver/
icd9	http://purl.bioontology.org/ontology/ICD9-9/
math	http://www.w3.org/2000/10/swap/math#
mddb	http://purl.bioontology.org/ontology/MDDB/
meddra	http://purl.bioontology.org/ontology/MDR/
medline	http://purl.bioontology.org/ontology/MEDLINEPLUS/
mesh	http://purl.org/commons/record/mesh/
mf	http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#
mged	http://mged.sourceforge.net/ontologies/MGEDOntology.owl#
ncbitaxon	http://purl.org/obo/owl/NCBITaxon#NCBITaxon_
ncithesaurus	http://ncicb.nci.nih.gov/xml/owl/EVS/Thesaurus.owl#
nddf	http://purl.bioontology.org/ontology/NDDF/
ndfrt	http://purl.bioontology.org/ontology/NDFRT/
obi	http://purl.obolibrary.org/obo/OBI_
obo	http://www.geneontology.org/formats/oboInOwl#
omim	http://purl.bioontology.org/ontology/OMIM/
owl	http://www.w3.org/2002/07/owl#
pav	http://purl.org/swan/pav/provenance/
po	http://purl.bioontology.org/ontology/PO/
product	http://www.buy.com/rss/module/productV2/
protseq	http://purl.org/science/protein/bysequence/
prov	http://www.w3.org/ns/prov#
pw	http://purl.org/obo/owl/PW#PW_
rdf	http://www.w3.org/1999/02/22-rdf-syntax-ns#
rdfa	http://www.w3.org/ns/rdfa#
rdfdf	http://www.openlinksw.com/virtrdf-data-formats#
rdfs	http://www.w3.org/2000/01/rdf-schema#
sc	http://purl.org/science/owl/sciencecommons/
scovo	http://purl.org/NET/scovo#
sioc	http://rdfs.org/sioc/ns#
skos	http://www.w3.org/2004/02/skos/core#
snomed	http://purl.bioontology.org/ontology/SNOMEDCT/
sql	sql:
swivt	http://semantic-mediawiki.org/swivt/1.0#
symptom	http://purl.org/obo/owl/SYMP#SYMP_
taxonomy	http://www.uniprot.org/taxonomy/
umls	http://berkeleybop.org/obo/UMLS:
uniprot	http://purl.uniprot.org/core/
vcard	http://www.w3.org/2001/vcard-rdf/3.0#
vcard2006	http://www.w3.org/2006/vcard/ns#
virtcxml	http://www.openlinksw.com/schemas/virtcxml#
virtrdf	http://www.openlinksw.com/schemas/virtrdf#
void	http://rdfs.org/ns/void#
xf	http://www.w3.org/2004/07/xpath-functions
xml	http://www.w3.org/XML/1998/namespace
xsd	http://www.w3.org/2001/XMLSchema#
xsl10	http://www.w3.org/XSL/Transform/1.0
xsl1999	http://www.w3.org/1999/XSL/Transform
xslwd	http://www.w3.org/TR/WD-xsl
xsp	http://www.owl-ontologies.com/2005/08/07/xsp.owl#
yago	http://dbpedia.org/class/yago/
";

            ss = s + ss;
            foreach (string s00 in ss.Split('\n', '\r'))
            {
                if (String.IsNullOrEmpty(s00))
                {
                    continue;
                }
                var s0 = s00.Replace('\t', ' ').Trim();
                if (s0.StartsWith("#"))
                {
                    continue;
                }
                if (s0.StartsWith("@prefix "))
                {
                    s0 = s0.Substring("@prefix ".Length).TrimStart();
                    s0 = s0.TrimEnd('.', ' ');
                }
                while (s0.Contains("  "))
                {
                    s0 = s0.Replace("  ", " ");
                }
                if (String.IsNullOrEmpty(s0))
                {
                    continue;
                }
                int    spc    = s0.IndexOf(' ');
                string prefix = s0.Substring(0, spc).Trim().TrimEnd(' ', ':');
                string uri    = s0.Substring(spc).Trim();
                if (uri.StartsWith("<") && uri.EndsWith(">"))
                {
                    uri = uri.Substring(1, uri.Length - 2).Trim();
                }
                if (uri == "#")
                {
                    continue;
                    //  uri = graph.BaseUri.AbsoluteUri;
                }
                if (String.IsNullOrEmpty(prefix))
                {
                    continue;
                    prefix = ":";//"Warn("adding null prefix " + uri);
                }
                if (nm.HasNamespace(prefix))
                {
                    var prev = nm.GetNamespaceUri(prefix).ToString();
                    if (prev != uri)
                    {
                        if (uri.Length < prev.Length)
                        {
                            continue;
                        }
                    }
                }
                nm.AddNamespace(prefix, new Uri(uri));
            }
        }
Exemple #13
0
 /// <summary>
 /// Creates a new Notation 3 Formatter using the given Namespace Map.
 /// </summary>
 /// <param name="nsmap">Namespace Map.</param>
 public Notation3Formatter(INamespaceMapper nsmap)
     : base("Notation 3", new QNameOutputMapper(nsmap))
 {
 }
Exemple #14
0
 internal ExpressionBuilder(INamespaceMapper prefixes)
 {
     _prefixes     = prefixes;
     SparqlVersion = SparqlQuerySyntax.Sparql_1_1;
 }
        /// <summary>
        /// Get column name by using qname compression and replacing special chars with underscores
        /// </summary>
        /// <param name="node">Node</param>
        /// <param name="namespaces">Namespaces</param>
        /// <returns></returns>
        private string GetColumnName(INode node, INamespaceMapper namespaces)
        {
            if (node.NodeType != NodeType.Uri)
            {
                return(null);
            }
            Uri u = ((IUriNode)node).Uri;

            String qname;

            if (!namespaces.ReduceToQName(u.AbsoluteUri, out qname))
            {
                // Issue temporary namespaces
                String tempNsPrefix = "ns" + this._nextTempID;
                String nsUri        = u.AbsoluteUri;
                if (nsUri.Contains("#"))
                {
                    //Create a Hash Namespace Uri
                    nsUri = nsUri.Substring(0, nsUri.LastIndexOf("#") + 1);
                }
                else if (nsUri.Contains("/"))
                {
                    //Create a Slash Namespace Uri
                    nsUri = nsUri.Substring(0, nsUri.LastIndexOf("/") + 1);
                }
                Uri tempNsUri;
                if (!Uri.TryCreate(nsUri, UriKind.Absolute, out tempNsUri))
                {
                    tempNsUri = u;
                }
                while (namespaces.HasNamespace(tempNsPrefix))
                {
                    this._nextTempID++;
                    tempNsPrefix = "ns" + this._nextTempID;
                }
                namespaces.AddNamespace(tempNsPrefix, tempNsUri);
                if (!namespaces.ReduceToQName(u.AbsoluteUri, out qname))
                {
                    qname = null;
                }
            }
            if (qname == null)
            {
                // Issue temporary column name
                return("entityPredicateColumn" + (++this._nextTempColumnID));
            }
            // Sanitize qname column name
            qname = qname.StartsWith("_") ? qname.Substring(1) : qname.Replace(':', '_');
            if (SparqlSpecsHelper.IsValidVarName(qname))
            {
                return(qname);
            }
            if (qname.Length == 0)
            {
                // Issue temporary column name
                return("entityPredicateColumn " + (++this._nextTempColumnID));
            }

            // Clean up illegal characters
            // First Character must be from PN_CHARS_U or a digit
            // Add a leading p for invalid first characters
            char[] cs    = qname.ToCharArray();
            char   first = cs[0];

            if (!Char.IsDigit(first) || !SparqlSpecsHelper.IsPNCharsU(first))
            {
                qname = "p" + qname;
                if (SparqlSpecsHelper.IsValidVarName(qname))
                {
                    return(qname);
                }
                cs = qname.ToCharArray();
            }
            for (int i = 1; i < cs.Length; i++)
            {
                if (i >= cs.Length - 1)
                {
                    continue;
                }
                // Subsequent Chars must be from PN_CHARS (except -) or a '.'
                // Replace invalid characters with _
                if (cs[i] == '.' || cs[i] == '-')
                {
                    cs[i] = '_';
                }
                else if (!SparqlSpecsHelper.IsPNChars(cs[i]))
                {
                    cs[i] = '_';
                }
            }
            // Trim trailing underscores
            return(new string(cs).TrimEnd('_'));
        }
 public GraphPattern BuildGraphPattern(INamespaceMapper prefixes)
 {
     return(_builder.BuildGraphPattern(prefixes));
 }
Exemple #17
0
 /// <summary>
 /// Constructs a new Namespace Map which is based on an existing map
 /// </summary>
 /// <param name="nsmapper"></param>
 protected internal NamespaceMapper(INamespaceMapper nsmapper)
     : this(true)
 {
     this.Import(nsmapper);
 }
Exemple #18
0
 /// <summary>
 /// Checks whether a give element is an rdf:li element.
 /// </summary>
 /// <param name="e">The element to test.</param>
 /// <param name="nsMapper">The namespace mappings to use when expanding element QName prefixes.</param>
 /// <returns>True if the element is an rdf:li element, false otherwise.</returns>
 public static bool IsLiElement(ElementEvent e, INamespaceMapper nsMapper)
 {
     return(nsMapper.HasNamespace(e.Namespace) &&
            IsRdfNamespace(nsMapper.GetNamespaceUri(e.Namespace)) &&
            e.LocalName.Equals("li"));
 }
 /// <summary>
 /// Creates a new Turtle Formatter for the given Namespace Map
 /// </summary>
 /// <param name="nsmap">Namespace Map</param>
 public TurtleFormatter(INamespaceMapper nsmap)
     : base("Turtle", new QNameOutputMapper(nsmap)) { }
Exemple #20
0
 /// <summary>
 /// Checks whether an attribute is an rdf:type attribute.
 /// </summary>
 /// <param name="attr">The attribute to check.</param>
 /// <param name="nsMapper">The namespace prefix mappings to use to expand QNames.</param>
 /// <returns>True if the attribute is and rdf:type attribute, false otherwise.</returns>
 public static bool IsTypeAttribute(AttributeEvent attr, INamespaceMapper nsMapper)
 {
     return(nsMapper.HasNamespace(attr.Namespace) &&
            IsRdfNamespace(nsMapper.GetNamespaceUri(attr.Namespace)) &&
            attr.LocalName.Equals("type"));
 }
Exemple #21
0
 /// <summary>
 /// Resolves a QName into a Uri using the Namespace Mapper and Base Uri provided
 /// </summary>
 /// <param name="qname">QName to resolve</param>
 /// <param name="nsmap">Namespace Map to resolve against</param>
 /// <param name="baseUri">Base Uri to resolve against</param>
 /// <returns></returns>
 public static String ResolveQName(String qname, INamespaceMapper nsmap, Uri baseUri)
 {
     return(Tools.ResolveQName(qname, nsmap, baseUri, false));
 }
        /// <summary>
        /// Starts RDF Handling instantiating a Triple Formatter if necessary.
        /// </summary>
        protected override void StartRdfInternal()
        {
            if (_closeOnEnd && _writer == null)
            {
                throw new RdfParseException("Cannot use this WriteThroughHandler as an RDF Handler for parsing as you set closeOnEnd to true and you have already used this Handler and so the provided TextWriter was closed");
            }

            if (_formatterType != null)
            {
                _formatter        = null;
                _formattingMapper = new QNameOutputMapper();

                // Instantiate a new Formatter
                ConstructorInfo[] cs = _formatterType.GetConstructors();
                Type qnameMapperType = typeof(QNameOutputMapper);
                Type nsMapperType    = typeof(INamespaceMapper);
                foreach (ConstructorInfo c in cs.OrderByDescending(c => c.GetParameters().Count()))
                {
                    ParameterInfo[] ps = c.GetParameters();
                    try
                    {
                        if (ps.Length == 1)
                        {
                            if (ps[0].ParameterType.Equals(qnameMapperType))
                            {
                                _formatter = Activator.CreateInstance(_formatterType, new Object[] { _formattingMapper }) as ITripleFormatter;
                            }
                            else if (ps[0].ParameterType.Equals(nsMapperType))
                            {
                                _formatter = Activator.CreateInstance(_formatterType, new Object[] { _formattingMapper }) as ITripleFormatter;
                            }
                        }
                        else if (ps.Length == 0)
                        {
                            _formatter = Activator.CreateInstance(_formatterType) as ITripleFormatter;
                        }

                        if (_formatter != null)
                        {
                            break;
                        }
                    }
                    catch
                    {
                        // Suppress errors since we'll throw later if necessary
                    }
                }

                // If we get out here and the formatter is null then we throw an error
                if (_formatter == null)
                {
                    throw new RdfParseException("Unable to instantiate a ITripleFormatter from the given Formatter Type " + _formatterType.FullName);
                }
            }

            if (_formatter is IGraphFormatter)
            {
                _writer.WriteLine(((IGraphFormatter)_formatter).FormatGraphHeader(_formattingMapper));
            }
            _written = 0;
        }
        /// <summary>
        /// Converts a <see cref="GraphDiffReport">diff</see> to an equivalent <see cref="ModifyCommand">SPARQL Update INSERT/DELETE command</see>
        /// </summary>
        /// <param name="diff">The <see cref="GraphDiffReport">diff</see> to convert</param>
        /// <param name="graphUri">Optional <see cref="Uri">URI</see> of the affected graph</param>
        /// <param name="prefixes">Optional <see cref="INamespaceMapper">mapper</see> used to resolve prefixes</param>
        /// <returns>A <see cref="ModifyCommand">SPARQL Update INSERT/DELETE command</see> that represents the <see cref="GraphDiffReport">diff</see></returns>
        public static ModifyCommand AsUpdate(this GraphDiffReport diff, Uri graphUri = null, INamespaceMapper prefixes = null)
        {
            var delete = new GraphPatternBuilder();
            var insert = new GraphPatternBuilder();

            var where = new GraphPatternBuilder();

            // Removed ground triples are added as is to both delete and where clauses
            foreach (var t in diff.RemovedTriples)
            {
                delete.AddTriplePattern(t);
                where.AddTriplePattern(t);
            }

            foreach (var g in diff.RemovedMSGs)
            {
                // Blank nodes in removed non-ground triples are converted to variables and added to both delete and where clauses
                foreach (var t in g.Triples)
                {
                    delete.AddVariablePattern(t);
                    where.AddVariablePattern(t);
                }

                // An ISBLANK filter is added for each blank node in removed non-ground triples
                foreach (var n in g.BlankNodes())
                {
                    where.AddBlankNodeFilter(n);
                }
            }

            // Added triples (ground or not) are added as is to the insert clause
            foreach (var t in diff.AllAddedTriples())
            {
                insert.AddTriplePattern(t);
            }

            return(new ModifyCommand(
                       delete.BuildGraphPattern(prefixes),
                       insert.BuildGraphPattern(prefixes),
                       where.BuildGraphPattern(prefixes),
                       graphUri));
        }
Exemple #24
0
        internal PatternItem CreateNodeMatchPattern(string qName, INamespaceMapper namespaceMapper)
        {
            var qNameResolved = Tools.ResolveQName(qName, namespaceMapper, null);

            return(CreateNodeMatchPattern(new Uri(qNameResolved)));
        }
 /// <summary>
 /// Creates a new Turtle Formatter for the given Namespace Map
 /// </summary>
 /// <param name="nsmap">Namespace Map</param>
 public TurtleFormatter(INamespaceMapper nsmap)
     : base("Turtle", new QNameOutputMapper(nsmap))
 {
 }
 /// <summary>
 /// Constructs a new Namespace Map which is based on an existing map.
 /// </summary>
 /// <param name="nsmapper"></param>
 protected internal NamespaceMapper(INamespaceMapper nsmapper)
     : this(true)
 {
     Import(nsmapper);
 }
Exemple #27
0
        /// <summary>
        /// Starts RDF Handling instantiating a Triple Formatter if necessary
        /// </summary>
        protected override void StartRdfInternal()
        {
            if (this._closeOnEnd && this._writer == null) throw new RdfParseException("Cannot use this WriteThroughHandler as an RDF Handler for parsing as you set closeOnEnd to true and you have already used this Handler and so the provided TextWriter was closed");

            if (this._formatterType != null)
            {
                this._formatter = null;
                this._formattingMapper = new QNameOutputMapper();

                //Instantiate a new Formatter
                ConstructorInfo[] cs = this._formatterType.GetConstructors();
                Type qnameMapperType = typeof(QNameOutputMapper);
                Type nsMapperType = typeof(INamespaceMapper);
                foreach (ConstructorInfo c in cs.OrderByDescending(c => c.GetParameters().Count()))
                {
                    ParameterInfo[] ps = c.GetParameters();
                    try
                    {
                        if (ps.Length == 1)
                        {
                            if (ps[0].ParameterType.Equals(qnameMapperType))
                            {
                                this._formatter = Activator.CreateInstance(this._formatterType, new Object[] { this._formattingMapper }) as ITripleFormatter;
                            }
                            else if (ps[0].ParameterType.Equals(nsMapperType))
                            {
                                this._formatter = Activator.CreateInstance(this._formatterType, new Object[] { this._formattingMapper }) as ITripleFormatter;
                            }
                        }
                        else if (ps.Length == 0)
                        {
                            this._formatter = Activator.CreateInstance(this._formatterType) as ITripleFormatter;
                        }

                        if (this._formatter != null) break;
                    }
                    catch
                    {
                        //Suppress errors since we'll throw later if necessary
                    }
                }

                //If we get out here and the formatter is null then we throw an error
                if (this._formatter == null) throw new RdfParseException("Unable to instantiate a ITripleFormatter from the given Formatter Type " + this._formatterType.FullName);
            }

            if (this._formatter is IGraphFormatter)
            {
                this._writer.WriteLine(((IGraphFormatter)this._formatter).FormatGraphHeader(this._formattingMapper));
            }
            this._written = 0;
        }
 /// <summary>
 /// Creates a new QName Output Mapper using the given Namespace Map.
 /// </summary>
 /// <param name="nsmapper">Namespace Map.</param>
 public QNameOutputMapper(INamespaceMapper nsmapper)
     : base(nsmapper)
 {
 }
 /// <summary>Creates a new instance of <see cref="TripleStoreAdapter"/></summary>
 /// <param name="store">The underlying triple store</param>
 public TripleStoreAdapter(ITripleStore store)
 {
     _store = store;
     _namespaces = new NamespaceMapper(true);
     _namespaces.AddNamespace("foaf", new Uri("http://xmlns.com/foaf/0.1/"));
 }
 /// <summary>
 /// Creates a new Thread Safe QName Output Mapper.
 /// </summary>
 /// <param name="nsmapper">Namespace Mapper.</param>
 public ThreadSafeQNameOutputMapper(INamespaceMapper nsmapper)
     : base(nsmapper)
 {
 }
Exemple #31
0
 /// <summary>
 /// Resolves a QName/Uri into a Uri using the Namespace Mapper and Base Uri provided
 /// </summary>
 /// <param name="t">QName/Uri to resolve</param>
 /// <param name="nsmap">Namespace Map to resolve against</param>
 /// <param name="baseUri">Base Uri to resolve against</param>
 /// <returns></returns>
 public static String ResolveUriOrQName(IToken t, INamespaceMapper nsmap, Uri baseUri)
 {
     if (t.TokenType == Token.QNAME)
     {
         return Tools.ResolveQName(t.Value, nsmap, baseUri);
     }
     else if (t.TokenType == Token.URI)
     {
         String uriBase = (baseUri == null) ? String.Empty : baseUri.ToString();
         return Tools.ResolveUri(t.Value, uriBase);
     }
     else
     {
         throw new RdfParseException("Unable to resolve a '" + t.GetType().ToString() + "' Token into a URI", t);
     }
 }
 public TriplePatternBuilder(INamespaceMapper prefixes)
 {
     _prefixes           = prefixes;
     _patternItemFactory = new PatternItemFactory();
 }
 /// <summary>
 /// Creates a new SPARQL Formatter using the given Namespace Map
 /// </summary>
 /// <param name="nsmap">Namespace Map</param>
 public SparqlFormatter(INamespaceMapper nsmap)
     : base("SPARQL", new QNameOutputMapper(nsmap)) 
 {
     this._validEscapes = new char[] { '"', 'n', 't', 'u', 'U', 'r', '\\', '0', 'f', 'b', '\'' };
 }
Exemple #34
0
 /// <summary>
 /// Creates a new Notation 3 Formatter using the given Namespace Map
 /// </summary>
 /// <param name="nsmap">Namespace Map</param>
 public Notation3Formatter(INamespaceMapper nsmap)
     : base("Notation 3", new QNameOutputMapper(nsmap))
 {
     this._validEscapes = new char[] { '"', 'n', 't', 'u', 'U', 'r', '\\', '0', '\'' };
 }
Exemple #35
0
 /// <summary>
 /// Creates a new QName Output Mapper using the given Namespace Map
 /// </summary>
 /// <param name="nsmapper">Namespace Map</param>
 public QNameOutputMapper(INamespaceMapper nsmapper)
     : base(nsmapper)
 {
 }
 /// <summary>
 /// Creates a new Notation 3 Formatter using the given Namespace Map
 /// </summary>
 /// <param name="nsmap">Namespace Map</param>
 public Notation3Formatter(INamespaceMapper nsmap)
     : base("Notation 3", new QNameOutputMapper(nsmap)) 
 {
     this._validEscapes = new char[] { '"', 'n', 't', 'u', 'U', 'r', '\\', '0', '\'' };
 }
 /// <summary>
 /// Imports another Namespace Map into this one
 /// </summary>
 /// <param name="nsmap">Namespace Map</param>
 public void Import(INamespaceMapper nsmap)
 {
     String tempPrefix = "ns0";
     int tempPrefixID = 0;
     foreach (String prefix in nsmap.Prefixes)
     {
         if (!this._uris.ContainsKey(prefix))
         {
             //Non-colliding Namespaces get copied across
             this.AddNamespace(prefix, nsmap.GetNamespaceUri(prefix));
         }
         else
         {
             //Colliding Namespaces get remapped to new prefixes
             //Assuming the prefixes aren't already used for the same Uri
             if (!this.GetNamespaceUri(prefix).ToString().Equals(nsmap.GetNamespaceUri(prefix).ToString(), StringComparison.Ordinal))
             {
                 while (this._uris.ContainsKey(tempPrefix))
                 {
                     tempPrefixID++;
                     tempPrefix = "ns" + tempPrefixID;
                 }
                 this.AddNamespace(tempPrefix, nsmap.GetNamespaceUri(prefix));
             }
         }
     }
 }
Exemple #38
0
        public static string NodesToString(IEnumerable <IEnumerable <INode> > nodesCollections, INamespaceMapper globalNsMapper)
        {
            SNamespaceMap mapLocal = new SNamespaceMap();

            string resultLines = String.Join(Environment.NewLine,
                                             nodesCollections.Select(result => String.Join(" ", result.Select <INode, string>(node =>
            {
                //optional empty
                if (node == null)
                {
                    return(" ");
                }
                IUriNode uriNode = node as IUriNode;
                if (uriNode != null)
                {
                    return(Uri2QName(mapLocal, uriNode.Uri.ToString(), globalNsMapper));
                }
                ILiteralNode literalNode = node as ILiteralNode;
                if (literalNode != null)
                {
                    if (literalNode.DataType != null)
                    {
                        if (literalNode.DataType.AbsoluteUri == XmlSchema.XMLSchemaLangString.AbsoluteUri)
                        {
                            return("\"" + literalNode.Value + "\"@" + literalNode.Language);
                        }
                        if (literalNode.DataType.AbsoluteUri == XmlSchema.XMLSchemaString.AbsoluteUri)
                        {
                            return("\"" + literalNode.Value + "\"");
                        }
                        return(String.Format("\"{0}\"^^{1}", literalNode.Value,
                                             Uri2QName(mapLocal, literalNode.DataType.AbsoluteUri, globalNsMapper)));
                    }
                    if (!(String.IsNullOrWhiteSpace(literalNode.Language)))
                    {
                        throw new NotImplementedException();
                    }
                    //  return literalNode.Value + "@" + literalNode.Language;
                    return(literalNode.Value);
                }
                throw new NotImplementedException();
            }
                                                                                                                              ))));

            return((mapLocal.Prefixes.Any()
                ? String.Join(Environment.NewLine,
                              mapLocal.Prefixes.Select(
                                  prefix => "@prefix " + prefix + " " + mapLocal.GetNamespaceUri(prefix))) +
                    Environment.NewLine + Environment.NewLine
                : String.Empty) + resultLines);
        }
 /// <summary>
 /// Creates a new Turtle Formatter
 /// </summary>
 /// <param name="formatName">Format Name</param>
 /// <param name="nsmap">Namespace Map</param>
 protected TurtleFormatter(String formatName, INamespaceMapper nsmap)
     : base(formatName, new QNameOutputMapper(nsmap)) { }
Exemple #40
0
 public NonCachingQNameOutputMapper(INamespaceMapper nsmapper)
     : base(nsmapper)
 {
 }