private void AddQuadToDataset(Triple quad, string graphName, RDFDataset rdfDataset)
        {
            Literal literal = quad.Object as Literal;
            if (literal != null)
            {
                string datatype = null;
                if (literal.Datatype != null)
                {
                    datatype = literal.Datatype.ToString();
                }

                rdfDataset.AddQuad(
                    GetValue(quad.Subject),
                    GetValue(quad.Predicate),
                    GetValue(literal),
                    datatype,
                    literal.LanguageTag,
                    graphName);
            }
            else
            {
                rdfDataset.AddQuad(
                    GetValue(quad.Subject),
                    GetValue(quad.Predicate),
                    GetValue(quad.Object),
                    graphName);
            }
        }
        /// <summary>
        /// Parses the specified input.
        /// </summary>
        /// <param name="input">The input.</param>
        public RDFDataset Parse(JToken input)
        {
            RDFDataset rdfDataset = new RDFDataset();

            var parser = new Parsing.NQuadsParser();
            parser.QuadParsed += (s, a) => AddQuadToDataset(a.Quad.Triple, GetValue(a.Quad.Graph), rdfDataset);
            parser.TripleParsed += (s, a) => AddQuadToDataset(a.Triple, "@default", rdfDataset);

            if (input.Type != JTokenType.String)
            {
                throw new ArgumentException(string.Format("Input must be a string, but got {0}", input.Type), "input");
            }

            parser.Parse((string)input);

            return rdfDataset;
        }
Beispiel #3
0
        /// <exception cref="JsonLD.Core.JsonLdError"></exception>
        public virtual RDFDataset Parse(JToken input)
        {
            if (!(input.Type == JTokenType.String))
            {
                throw new JsonLdError(JsonLdError.Error.InvalidInput, "Invalid input; Triple RDF Parser requires a string input"
                                      );
            }
            RDFDataset result = new RDFDataset();

            TurtleRDFParser.State state = new TurtleRDFParser.State(this, (string)input);
            while (!string.Empty.Equals(state.line))
            {
                // check if line is a directive
                Matcher match = TurtleRDFParser.Regex.Directive.Matcher(state.line);
                if (match.Find())
                {
                    if (match.Group(1) != null || match.Group(4) != null)
                    {
                        string ns = match.Group(1) != null?match.Group(1) : match.Group(4);

                        string iri = match.Group(1) != null?match.Group(2) : match.Group(5);

                        if (!iri.Contains(":"))
                        {
                            iri = state.baseIri + iri;
                        }
                        iri = RDFDatasetUtils.Unescape(iri);
                        ValidateIRI(state, iri);
                        state.namespaces[ns] = iri;
                        result.SetNamespace(ns, iri);
                    }
                    else
                    {
                        string @base = match.Group(3) != null?match.Group(3) : match.Group(6);

                        @base = RDFDatasetUtils.Unescape(@base);
                        ValidateIRI(state, @base);
                        if ([email protected](":"))
                        {
                            state.baseIri = state.baseIri + @base;
                        }
                        else
                        {
                            state.baseIri = @base;
                        }
                    }
                    state.AdvanceLinePosition(match.Group(0).Length);
                    continue;
                }
                if (state.curSubject == null)
                {
                    // we need to match a subject
                    match = TurtleRDFParser.Regex.Subject.Matcher(state.line);
                    if (match.Find())
                    {
                        string iri;
                        if (match.Group(1) != null)
                        {
                            // matched IRI
                            iri = RDFDatasetUtils.Unescape(match.Group(1));
                            if (!iri.Contains(":"))
                            {
                                iri = state.baseIri + iri;
                            }
                        }
                        else
                        {
                            if (match.Group(2) != null)
                            {
                                // matched NS:NAME
                                string ns   = match.Group(2);
                                string name = UnescapeReserved(match.Group(3));
                                iri = state.ExpandIRI(ns, name);
                            }
                            else
                            {
                                if (match.Group(4) != null)
                                {
                                    // match ns: only
                                    iri = state.ExpandIRI(match.Group(4), string.Empty);
                                }
                                else
                                {
                                    if (match.Group(5) != null)
                                    {
                                        // matched BNODE
                                        iri = state.namer.GetName(match.Group(0).Trim());
                                    }
                                    else
                                    {
                                        // matched anon node
                                        iri = state.namer.GetName();
                                    }
                                }
                            }
                        }
                        // make sure IRI still matches an IRI after escaping
                        ValidateIRI(state, iri);
                        state.curSubject = iri;
                        state.AdvanceLinePosition(match.Group(0).Length);
                    }
                    else
                    {
                        // handle blank nodes
                        if (state.line.StartsWith("["))
                        {
                            string bnode = state.namer.GetName();
                            state.AdvanceLinePosition(1);
                            state.Push();
                            state.curSubject = bnode;
                        }
                        else
                        {
                            // handle collections
                            if (state.line.StartsWith("("))
                            {
                                string bnode = state.namer.GetName();
                                // so we know we want a predicate if the collection close
                                // isn't followed by a subject end
                                state.curSubject = bnode;
                                state.AdvanceLinePosition(1);
                                state.Push();
                                state.curSubject   = bnode;
                                state.curPredicate = JSONLDConsts.RdfFirst;
                            }
                            else
                            {
                                // make sure we have a subject already
                                throw new JsonLdError(JsonLdError.Error.ParseError, "Error while parsing Turtle; missing expected subject. {line: "
                                                      + state.lineNumber + "position: " + state.linePosition + "}");
                            }
                        }
                    }
                }
                if (state.curPredicate == null)
                {
                    // match predicate
                    match = TurtleRDFParser.Regex.Predicate.Matcher(state.line);
                    if (match.Find())
                    {
                        string iri = string.Empty;
                        if (match.Group(1) != null)
                        {
                            // matched IRI
                            iri = RDFDatasetUtils.Unescape(match.Group(1));
                            if (!iri.Contains(":"))
                            {
                                iri = state.baseIri + iri;
                            }
                        }
                        else
                        {
                            if (match.Group(2) != null)
                            {
                                // matched NS:NAME
                                string ns   = match.Group(2);
                                string name = UnescapeReserved(match.Group(3));
                                iri = state.ExpandIRI(ns, name);
                            }
                            else
                            {
                                if (match.Group(4) != null)
                                {
                                    // matched ns:
                                    iri = state.ExpandIRI(match.Group(4), string.Empty);
                                }
                                else
                                {
                                    // matched "a"
                                    iri = JSONLDConsts.RdfType;
                                }
                            }
                        }
                        ValidateIRI(state, iri);
                        state.curPredicate = iri;
                        state.AdvanceLinePosition(match.Group(0).Length);
                    }
                    else
                    {
                        throw new JsonLdError(JsonLdError.Error.ParseError, "Error while parsing Turtle; missing expected predicate. {line: "
                                              + state.lineNumber + "position: " + state.linePosition + "}");
                    }
                }
                // expecting bnode or object
                // match BNODE values
                if (state.line.StartsWith("["))
                {
                    string bnode = state.namer.GetName();
                    result.AddTriple(state.curSubject, state.curPredicate, bnode);
                    state.AdvanceLinePosition(1);
                    // check for anonymous objects
                    if (state.line.StartsWith("]"))
                    {
                        state.AdvanceLinePosition(1);
                    }
                    else
                    {
                        // next we expect a statement or object separator
                        // otherwise we're inside the blank node
                        state.Push();
                        state.curSubject = bnode;
                        // next we expect a predicate
                        continue;
                    }
                }
                else
                {
                    // match collections
                    if (state.line.StartsWith("("))
                    {
                        state.AdvanceLinePosition(1);
                        // check for empty collection
                        if (state.line.StartsWith(")"))
                        {
                            state.AdvanceLinePosition(1);
                            result.AddTriple(state.curSubject, state.curPredicate, JSONLDConsts.RdfNil);
                        }
                        else
                        {
                            // next we expect a statement or object separator
                            // otherwise we're inside the collection
                            string bnode = state.namer.GetName();
                            result.AddTriple(state.curSubject, state.curPredicate, bnode);
                            state.Push();
                            state.curSubject   = bnode;
                            state.curPredicate = JSONLDConsts.RdfFirst;
                            continue;
                        }
                    }
                    else
                    {
                        // match object
                        match = TurtleRDFParser.Regex.Object.Matcher(state.line);
                        if (match.Find())
                        {
                            string iri = null;
                            if (match.Group(1) != null)
                            {
                                // matched IRI
                                iri = RDFDatasetUtils.Unescape(match.Group(1));
                                if (!iri.Contains(":"))
                                {
                                    iri = state.baseIri + iri;
                                }
                            }
                            else
                            {
                                if (match.Group(2) != null)
                                {
                                    // matched NS:NAME
                                    string ns   = match.Group(2);
                                    string name = UnescapeReserved(match.Group(3));
                                    iri = state.ExpandIRI(ns, name);
                                }
                                else
                                {
                                    if (match.Group(4) != null)
                                    {
                                        // matched ns:
                                        iri = state.ExpandIRI(match.Group(4), string.Empty);
                                    }
                                    else
                                    {
                                        if (match.Group(5) != null)
                                        {
                                            // matched BNODE
                                            iri = state.namer.GetName(match.Group(0).Trim());
                                        }
                                    }
                                }
                            }
                            if (iri != null)
                            {
                                ValidateIRI(state, iri);
                                // we have a object
                                result.AddTriple(state.curSubject, state.curPredicate, iri);
                            }
                            else
                            {
                                // we have a literal
                                string value    = match.Group(6);
                                string lang     = null;
                                string datatype = null;
                                if (value != null)
                                {
                                    // we have a string literal
                                    value = UnquoteString(value);
                                    value = RDFDatasetUtils.Unescape(value);
                                    lang  = match.Group(7);
                                    if (lang == null)
                                    {
                                        if (match.Group(8) != null)
                                        {
                                            datatype = RDFDatasetUtils.Unescape(match.Group(8));
                                            if (!datatype.Contains(":"))
                                            {
                                                datatype = state.baseIri + datatype;
                                            }
                                            ValidateIRI(state, datatype);
                                        }
                                        else
                                        {
                                            if (match.Group(9) != null)
                                            {
                                                datatype = state.ExpandIRI(match.Group(9), UnescapeReserved(match.Group(10)));
                                            }
                                            else
                                            {
                                                if (match.Group(11) != null)
                                                {
                                                    datatype = state.ExpandIRI(match.Group(11), string.Empty);
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        datatype = JSONLDConsts.RdfLangstring;
                                    }
                                }
                                else
                                {
                                    if (match.Group(12) != null)
                                    {
                                        // integer literal
                                        value    = match.Group(12);
                                        datatype = JSONLDConsts.XsdDouble;
                                    }
                                    else
                                    {
                                        if (match.Group(13) != null)
                                        {
                                            // decimal literal
                                            value    = match.Group(13);
                                            datatype = JSONLDConsts.XsdDecimal;
                                        }
                                        else
                                        {
                                            if (match.Group(14) != null)
                                            {
                                                // double literal
                                                value    = match.Group(14);
                                                datatype = JSONLDConsts.XsdInteger;
                                            }
                                            else
                                            {
                                                if (match.Group(15) != null)
                                                {
                                                    // boolean literal
                                                    value    = match.Group(15);
                                                    datatype = JSONLDConsts.XsdBoolean;
                                                }
                                            }
                                        }
                                    }
                                }
                                result.AddTriple(state.curSubject, state.curPredicate, value, datatype, lang);
                            }
                            state.AdvanceLinePosition(match.Group(0).Length);
                        }
                        else
                        {
                            throw new JsonLdError(JsonLdError.Error.ParseError, "Error while parsing Turtle; missing expected object or blank node. {line: "
                                                  + state.lineNumber + "position: " + state.linePosition + "}");
                        }
                    }
                }
                // close collection
                bool collectionClosed = false;
                while (state.line.StartsWith(")"))
                {
                    if (!JSONLDConsts.RdfFirst.Equals(state.curPredicate))
                    {
                        throw new JsonLdError(JsonLdError.Error.ParseError, "Error while parsing Turtle; unexpected ). {line: "
                                              + state.lineNumber + "position: " + state.linePosition + "}");
                    }
                    result.AddTriple(state.curSubject, JSONLDConsts.RdfRest, JSONLDConsts.RdfNil);
                    state.Pop();
                    state.AdvanceLinePosition(1);
                    collectionClosed = true;
                }
                bool expectDotOrPred = false;
                // match end of bnode
                if (state.line.StartsWith("]"))
                {
                    string bnode = state.curSubject;
                    state.Pop();
                    state.AdvanceLinePosition(1);
                    if (state.curSubject == null)
                    {
                        // this is a bnode as a subject and we
                        // expect either a . or a predicate
                        state.curSubject = bnode;
                        expectDotOrPred  = true;
                    }
                }
                // match list separator
                if (!expectDotOrPred && state.line.StartsWith(","))
                {
                    state.AdvanceLinePosition(1);
                    // now we expect another object/bnode
                    continue;
                }
                // match predicate end
                if (!expectDotOrPred)
                {
                    while (state.line.StartsWith(";"))
                    {
                        state.curPredicate = null;
                        state.AdvanceLinePosition(1);
                        // now we expect another predicate, or a dot
                        expectDotOrPred = true;
                    }
                }
                if (state.line.StartsWith("."))
                {
                    if (state.expectingBnodeClose)
                    {
                        throw new JsonLdError(JsonLdError.Error.ParseError, "Error while parsing Turtle; missing expected )\"]\". {line: "
                                              + state.lineNumber + "position: " + state.linePosition + "}");
                    }
                    state.curSubject   = null;
                    state.curPredicate = null;
                    state.AdvanceLinePosition(1);
                    // this can now be the end of the document.
                    continue;
                }
                else
                {
                    if (expectDotOrPred)
                    {
                        // we're expecting another predicate since we didn't find a dot
                        continue;
                    }
                }
                // if we're in a collection
                if (JSONLDConsts.RdfFirst.Equals(state.curPredicate))
                {
                    string bnode = state.namer.GetName();
                    result.AddTriple(state.curSubject, JSONLDConsts.RdfRest, bnode);
                    state.curSubject = bnode;
                    continue;
                }
                if (collectionClosed)
                {
                    // we expect another object
                    // TODO: it's not clear yet if this is valid
                    continue;
                }
                // if we get here, we're missing a close statement
                throw new JsonLdError(JsonLdError.Error.ParseError, "Error while parsing Turtle; missing expected \"]\" \",\" \";\" or \".\". {line: "
                                      + state.lineNumber + "position: " + state.linePosition + "}");
            }
            return(result);
        }
Beispiel #4
0
 internal static string ToNQuad(RDFDataset.Quad triple, string graphName)
 {
     return ToNQuad(triple, graphName, null);
 }
Beispiel #5
0
 /// <summary>Parses RDF in the form of N-Quads.</summary>
 /// <remarks>Parses RDF in the form of N-Quads.</remarks>
 /// <param name="input">the N-Quads input to parse.</param>
 /// <returns>an RDF dataset.</returns>
 /// <exception cref="JsonLD.Core.JsonLdError"></exception>
 public static RDFDataset ParseNQuads(string input)
 {
     // build RDF dataset
     RDFDataset dataset = new RDFDataset();
     // split N-Quad input into lines
     string[] lines = RDFDatasetUtils.Regex.Eoln.Split(input);
     int lineNumber = 0;
     foreach (string line in lines)
     {
         lineNumber++;
         // skip empty lines
         if (RDFDatasetUtils.Regex.EmptyOrComment.Matcher(line).Matches())
         {
             continue;
         }
         // parse quad
         Matcher match = RDFDatasetUtils.Regex.Quad.Matcher(line);
         if (!match.Matches())
         {
             throw new JsonLdError(JsonLdError.Error.SyntaxError, "Error while parsing N-Quads; invalid quad. line:"
                  + lineNumber);
         }
         // get subject
         RDFDataset.Node subject;
         if (match.Group(1) != null)
         {
             var subjectIri = Unescape(match.Group(1));
             AssertAbsoluteIri(subjectIri);
             subject = new RDFDataset.IRI(subjectIri);
         }
         else
         {
             subject = new RDFDataset.BlankNode(Unescape(match.Group(2)));
         }
         // get predicate
         var predicateIri = Unescape(match.Group(3));
         AssertAbsoluteIri(predicateIri);
         RDFDataset.Node predicate = new RDFDataset.IRI(predicateIri);
         // get object
         RDFDataset.Node @object;
         if (match.Group(4) != null)
         {
             var objectIri = Unescape(match.Group(4));
             AssertAbsoluteIri(objectIri);
             @object = new RDFDataset.IRI(objectIri);
         }
         else
         {
             if (match.Group(5) != null)
             {
                 @object = new RDFDataset.BlankNode(Unescape(match.Group(5)));
             }
             else
             {
                 string language = Unescape(match.Group(8));
                 string datatype = match.Group(7) != null ? Unescape(match.Group(7)) : match.Group
                     (8) != null ? JSONLDConsts.RdfLangstring : JSONLDConsts.XsdString;
                 AssertAbsoluteIri(datatype);
                 string unescaped = Unescape(match.Group(6));
                 @object = new RDFDataset.Literal(unescaped, datatype, language);
             }
         }
         // get graph name ('@default' is used for the default graph)
         string name = "@default";
         if (match.Group(9) != null)
         {
             name = Unescape(match.Group(9));
             AssertAbsoluteIri(name);
         }
         else
         {
             if (match.Group(10) != null)
             {
                 name = Unescape(match.Group(10));
             }
         }
         RDFDataset.Quad triple = new RDFDataset.Quad(subject, predicate, @object, name);
         // initialise graph in dataset
         if (!dataset.ContainsKey(name))
         {
             IList<RDFDataset.Quad> tmp = new List<RDFDataset.Quad>();
             tmp.Add(triple);
             dataset[name] = tmp;
         }
         else
         {
             // add triple if unique to its graph
             IList<RDFDataset.Quad> triples = (IList<RDFDataset.Quad>)dataset[name];
             if (!triples.Contains(triple))
             {
                 triples.Add(triple);
             }
         }
     }
     return dataset;
 }
Beispiel #6
0
        public static string ToNQuads(RDFDataset dataset)
        {
            IList<string> quads = new List<string>();
            foreach (string graphName in dataset.GraphNames())
            {
                var eachGraphName = graphName;
                IList<RDFDataset.Quad> triples = dataset.GetQuads(eachGraphName);
                if ("@default".Equals(eachGraphName))
                {
                    eachGraphName = null;
                }
                foreach (RDFDataset.Quad triple in triples)
                {
                    quads.Add(ToNQuad(triple, eachGraphName));
                }
            }

            ((List<string>)quads).Sort(StringComparer.Ordinal);

            string rval = string.Empty;
            foreach (string quad in quads)
            {
                rval += quad;
            }
            return rval;
        }
Beispiel #7
0
 internal static string ToNQuad(RDFDataset.Quad triple, string graphName, string bnode
     )
 {
     RDFDataset.Node s = triple.GetSubject();
     RDFDataset.Node p = triple.GetPredicate();
     RDFDataset.Node o = triple.GetObject();
     string quad = string.Empty;
     // subject is an IRI or bnode
     if (s.IsIRI())
     {
         quad += "<" + Escape(s.GetValue()) + ">";
     }
     else
     {
         // normalization mode
         if (bnode != null)
         {
             quad += bnode.Equals(s.GetValue()) ? "_:a" : "_:z";
         }
         else
         {
             // normal mode
             quad += s.GetValue();
         }
     }
     if (p.IsIRI())
     {
         quad += " <" + Escape(p.GetValue()) + "> ";
     }
     else
     {
         // otherwise it must be a bnode (TODO: can we only allow this if the
         // flag is set in options?)
         quad += " " + Escape(p.GetValue()) + " ";
     }
     // object is IRI, bnode or literal
     if (o.IsIRI())
     {
         quad += "<" + Escape(o.GetValue()) + ">";
     }
     else
     {
         if (o.IsBlankNode())
         {
             // normalization mode
             if (bnode != null)
             {
                 quad += bnode.Equals(o.GetValue()) ? "_:a" : "_:z";
             }
             else
             {
                 // normal mode
                 quad += o.GetValue();
             }
         }
         else
         {
             string escaped = Escape(o.GetValue());
             quad += "\"" + escaped + "\"";
             if (JSONLDConsts.RdfLangstring.Equals(o.GetDatatype()))
             {
                 quad += "@" + o.GetLanguage();
             }
             else
             {
                 if (!JSONLDConsts.XsdString.Equals(o.GetDatatype()))
                 {
                     quad += "^^<" + Escape(o.GetDatatype()) + ">";
                 }
             }
         }
     }
     // graph
     if (graphName != null)
     {
         if (graphName.IndexOf("_:") != 0)
         {
             quad += " <" + Escape(graphName) + ">";
         }
         else
         {
             if (bnode != null)
             {
                 quad += " _:g";
             }
             else
             {
                 quad += " " + graphName;
             }
         }
     }
     quad += " .\n";
     return quad;
 }
Beispiel #8
0
		/// <summary>Performs RDF normalization on the given JSON-LD input.</summary>
		/// <remarks>Performs RDF normalization on the given JSON-LD input.</remarks>
		/// <param name="input">the expanded JSON-LD object to normalize.</param>
		/// <param name="options">the normalization options.</param>
		/// <param name="callback">(err, normalized) called once the operation completes.</param>
		/// <exception cref="JSONLDProcessingError">JSONLDProcessingError</exception>
		/// <exception cref="JsonLD.Core.JsonLdError"></exception>
		public virtual object Normalize(RDFDataset dataset)
		{
			// create quads and map bnodes to their associated quads
			IList<RDFDataset.Quad> quads = new List<RDFDataset.Quad>();
			IDictionary<string,IDictionary<string,object>> bnodes = new Dictionary<string,IDictionary<string,object>>();
			foreach (string graphName in dataset.Keys)
			{
                var eachGraphName = graphName;
                IList<RDFDataset.Quad> triples = (IList<RDFDataset.Quad>)dataset[eachGraphName];
				if ("@default".Equals(eachGraphName))
				{
					eachGraphName = null;
				}
                foreach (RDFDataset.Quad quad in triples)
				{
					if (eachGraphName != null)
					{
						if (eachGraphName.IndexOf("_:") == 0)
						{
                            IDictionary<string, object> tmp = new Dictionary<string, object>();
							tmp["type"] = "blank node";
							tmp["value"] = eachGraphName;
							quad["name"] = tmp;
						}
						else
						{
                            IDictionary<string, object> tmp = new Dictionary<string, object>();
							tmp["type"] = "IRI";
							tmp["value"] = eachGraphName;
							quad["name"] = tmp;
						}
					}
					quads.Add(quad);
					string[] attrs = new string[] { "subject", "object", "name" };
					foreach (string attr in attrs)
					{
						if (quad.ContainsKey(attr) && (string)((IDictionary<string,object>)quad[attr])["type"] == "blank node")
						{
                            string id = (string)((IDictionary<string,object>)quad[attr])["value"];
							if (!bnodes.ContainsKey(id))
							{
								bnodes[id] = new Dictionary<string,object> { {"quads", new List<RDFDataset.Quad>()} };
							}
							((IList<RDFDataset.Quad>)bnodes[id]["quads"]).Add(quad);
						}
					}
				}
			}
			// mapping complete, start canonical naming
			NormalizeUtils normalizeUtils = new NormalizeUtils(quads, bnodes, new UniqueNamer
				("_:c14n"), opts);
			return normalizeUtils.HashBlankNodes(bnodes.Keys);
		}
Beispiel #9
0
        // this shouldn't be a
        // valid iri/bnode i
        // hope!
        // TODO: fill with default namespaces
        public virtual object Call(RDFDataset dataset)
        {
            foreach (KeyValuePair <string, string> e in dataset.GetNamespaces().GetEnumerableSelf
                         ())
            {
                availableNamespaces[e.Value] = e.Key;
            }
            usedNamespaces = new HashSet <string>();
            JObject refs = new JObject();
            JObject ttl  = new JObject();

            foreach (string graphName in dataset.Keys)
            {
                string localGraphName           = graphName;
                IList <RDFDataset.Quad> triples = (IList <RDFDataset.Quad>)dataset.GetQuads(localGraphName);
                if ("@default".Equals(localGraphName))
                {
                    localGraphName = null;
                }
                // http://www.w3.org/TR/turtle/#unlabeled-bnodes
                // TODO: implement nesting for unlabled nodes
                // map of what the output should look like
                // subj (or [ if bnode) > pred > obj
                // > obj (set ref if IRI)
                // > pred > obj (set ref if bnode)
                // subj > etc etc etc
                // subjid -> [ ref, ref, ref ]
                string  prevSubject   = string.Empty;
                string  prevPredicate = string.Empty;
                JObject thisSubject   = null;
                JArray  thisPredicate = null;
                foreach (RDFDataset.Quad triple in triples)
                {
                    string subject   = triple.GetSubject().GetValue();
                    string predicate = triple.GetPredicate().GetValue();
                    if (prevSubject.Equals(subject))
                    {
                        if (prevPredicate.Equals(predicate))
                        {
                        }
                        else
                        {
                            // nothing to do
                            // new predicate
                            if (thisSubject.ContainsKey(predicate))
                            {
                                thisPredicate = (JArray)thisSubject[predicate];
                            }
                            else
                            {
                                thisPredicate          = new JArray();
                                thisSubject[predicate] = thisPredicate;
                            }
                            prevPredicate = predicate;
                        }
                    }
                    else
                    {
                        // new subject
                        if (ttl.ContainsKey(subject))
                        {
                            thisSubject = (JObject)ttl[subject];
                        }
                        else
                        {
                            thisSubject  = new JObject();
                            ttl[subject] = thisSubject;
                        }
                        if (thisSubject.ContainsKey(predicate))
                        {
                            thisPredicate = (JArray)thisSubject[predicate];
                        }
                        else
                        {
                            thisPredicate          = new JArray();
                            thisSubject[predicate] = thisPredicate;
                        }
                        prevSubject   = subject;
                        prevPredicate = predicate;
                    }
                    if (triple.GetObject().IsLiteral())
                    {
                        thisPredicate.Add(triple.GetObject());
                    }
                    else
                    {
                        string o = triple.GetObject().GetValue();
                        if (o.StartsWith("_:"))
                        {
                            // add ref to o
                            if (!refs.ContainsKey(o))
                            {
                                refs[o] = new JArray();
                            }
                            ((JArray)refs[o]).Add(thisPredicate);
                        }
                        thisPredicate.Add(o);
                    }
                }
            }
            JObject collections = new JObject();
            JArray  subjects    = new JArray(ttl.GetKeys());

            // find collections
            foreach (string subj in subjects)
            {
                JObject preds = (JObject)ttl[subj];
                if (preds != null && preds.ContainsKey(JSONLDConsts.RdfFirst))
                {
                    JArray col = new JArray();
                    collections[subj] = col;
                    while (true)
                    {
                        JArray first = (JArray)JsonLD.Collections.Remove(preds, JSONLDConsts.RdfFirst);
                        JToken o     = first[0];
                        col.Add(o);
                        // refs
                        if (refs.ContainsKey((string)o))
                        {
                            ((JArray)refs[(string)o]).Remove(first);
                            ((JArray)refs[(string)o]).Add(col);
                        }
                        string next = (string)JsonLD.Collections.Remove(preds, JSONLDConsts.RdfRest)[0
                                      ];
                        if (JSONLDConsts.RdfNil.Equals(next))
                        {
                            // end of this list
                            break;
                        }
                        // if collections already contains a value for "next", add
                        // it to this col and break out
                        if (collections.ContainsKey(next))
                        {
                            JsonLD.Collections.AddAll(col, (JArray)JsonLD.Collections.Remove(collections, next));
                            break;
                        }
                        preds = (JObject)JsonLD.Collections.Remove(ttl, next);
                        JsonLD.Collections.Remove(refs, next);
                    }
                }
            }
            // process refs (nesting referenced bnodes if only one reference to them
            // in the whole graph)
            foreach (string id in refs.GetKeys())
            {
                // skip items if there is more than one reference to them in the
                // graph
                if (((JArray)refs[id]).Count > 1)
                {
                    continue;
                }
                // otherwise embed them into the referenced location
                JToken @object = JsonLD.Collections.Remove(ttl, id);
                if (collections.ContainsKey(id))
                {
                    @object = new JObject();
                    JArray tmp = new JArray();
                    tmp.Add(JsonLD.Collections.Remove(collections, id));
                    ((JObject)@object)[ColsKey] = tmp;
                }
                JArray predicate = (JArray)refs[id][0];
                // replace the one bnode ref with the object
                predicate[predicate.LastIndexOf(id)] = (JToken)@object;
            }
            // replace the rest of the collections
            foreach (string id_1 in collections.GetKeys())
            {
                JObject subj_1 = (JObject)ttl[id_1];
                if (!subj_1.ContainsKey(ColsKey))
                {
                    subj_1[ColsKey] = new JArray();
                }
                ((JArray)subj_1[ColsKey]).Add(collections[id_1]);
            }
            // build turtle output
            string output   = GenerateTurtle(ttl, 0, 0, false);
            string prefixes = string.Empty;

            foreach (string prefix in usedNamespaces)
            {
                string name = availableNamespaces[prefix];
                prefixes += "@prefix " + name + ": <" + prefix + "> .\n";
            }
            return((string.Empty.Equals(prefixes) ? string.Empty : prefixes + "\n") + output);
        }
Beispiel #10
0
		/// <summary>Converts RDF statements into JSON-LD.</summary>
		/// <remarks>Converts RDF statements into JSON-LD.</remarks>
		/// <param name="statements">the RDF statements.</param>
		/// <param name="options">the RDF conversion options.</param>
		/// <param name="callback">(err, output) called once the operation completes.</param>
		/// <exception cref="JSONLDProcessingError">JSONLDProcessingError</exception>
		/// <exception cref="JsonLD.Core.JsonLdError"></exception>
		public virtual JArray FromRDF(RDFDataset dataset)
		{
			// 1)
			JObject defaultGraph = new JObject();
			// 2)
			JObject graphMap = new JObject();
			graphMap["@default"] = defaultGraph;
			// 3/3.1)
			foreach (string name in dataset.GraphNames())
			{
				IList<RDFDataset.Quad> graph = dataset.GetQuads(name);
				// 3.2+3.4)
				JObject nodeMap;
				if (!graphMap.ContainsKey(name))
				{
					nodeMap = new JObject();
					graphMap[name] = nodeMap;
				}
				else
				{
					nodeMap = (JObject)graphMap[name];
				}
				// 3.3)
				if (!"@default".Equals(name) && !Obj.Contains(defaultGraph, name))
				{
					defaultGraph[name] = new JsonLdApi.NodeMapNode(this, name);
				}
				// 3.5)
				foreach (RDFDataset.Quad triple in graph)
				{
					string subject = triple.GetSubject().GetValue();
					string predicate = triple.GetPredicate().GetValue();
					RDFDataset.Node @object = triple.GetObject();
					// 3.5.1+3.5.2)
					JsonLdApi.NodeMapNode node;
					if (!nodeMap.ContainsKey(subject))
					{
						node = new JsonLdApi.NodeMapNode(this, subject);
						nodeMap[subject] = node;
					}
					else
					{
						node = (NodeMapNode)nodeMap[subject];
					}
					// 3.5.3)
					if ((@object.IsIRI() || @object.IsBlankNode()) && !nodeMap.ContainsKey(@object.GetValue
						()))
					{
						nodeMap[@object.GetValue()] = new JsonLdApi.NodeMapNode(this, @object.GetValue());
					}
					// 3.5.4)
					if (JSONLDConsts.RdfType.Equals(predicate) && (@object.IsIRI() || @object.IsBlankNode
						()) && !opts.GetUseRdfType())
					{
						JsonLdUtils.MergeValue(node, "@type", @object.GetValue());
						continue;
					}
					// 3.5.5)
					JObject value = @object.ToObject(opts.GetUseNativeTypes());
					// 3.5.6+7)
					JsonLdUtils.MergeValue(node, predicate, value);
					// 3.5.8)
					if (@object.IsBlankNode() || @object.IsIRI())
					{
						// 3.5.8.1-3)
						((NodeMapNode)nodeMap[@object.GetValue()]).usages.Add(new JsonLdApi.UsagesNode(this, node, predicate
							, value));
					}
				}
			}
			// 4)
			foreach (string name_1 in graphMap.GetKeys())
			{
				JObject graph = (JObject)graphMap[name_1];
				// 4.1)
				if (!graph.ContainsKey(JSONLDConsts.RdfNil))
				{
					continue;
				}
				// 4.2)
				JsonLdApi.NodeMapNode nil = (NodeMapNode)graph[JSONLDConsts.RdfNil];
				// 4.3)
				foreach (JsonLdApi.UsagesNode usage in nil.usages)
				{
					// 4.3.1)
					JsonLdApi.NodeMapNode node = usage.node;
					string property = usage.property;
					JObject head = usage.value;
					// 4.3.2)
					JArray list = new JArray();
					JArray listNodes = new JArray();
					// 4.3.3)
					while (JSONLDConsts.RdfRest.Equals(property) && node.IsWellFormedListNode())
					{
						// 4.3.3.1)
						list.Add(((JArray)node[JSONLDConsts.RdfFirst])[0]);
						// 4.3.3.2)
						listNodes.Add((string)node["@id"]);
						// 4.3.3.3)
						JsonLdApi.UsagesNode nodeUsage = node.usages[0];
						// 4.3.3.4)
						node = nodeUsage.node;
						property = nodeUsage.property;
						head = nodeUsage.value;
						// 4.3.3.5)
						if (!JsonLdUtils.IsBlankNode(node))
						{
							break;
						}
					}
					// 4.3.4)
					if (JSONLDConsts.RdfFirst.Equals(property))
					{
						// 4.3.4.1)
						if (JSONLDConsts.RdfNil.Equals(node["@id"]))
						{
							continue;
						}
						// 4.3.4.3)
						string headId = (string)head["@id"];
						// 4.3.4.4-5)
						head = (JObject)((JArray)graph[headId][JSONLDConsts.RdfRest
							])[0];
						// 4.3.4.6)
						list.RemoveAt(list.Count - 1);
						listNodes.RemoveAt(listNodes.Count - 1);
					}
					// 4.3.5)
					JsonLD.Collections.Remove(head, "@id");
					// 4.3.6)
					JsonLD.Collections.Reverse(list);
					// 4.3.7)
					head["@list"] = list;
					// 4.3.8)
					foreach (string nodeId in listNodes)
					{
						JsonLD.Collections.Remove(graph, nodeId);
					}
				}
			}
			// 5)
			JArray result = new JArray();
			// 6)
            JArray ids = new JArray(defaultGraph.GetKeys());
			ids.SortInPlace();
			foreach (string subject_1 in ids)
			{
				JsonLdApi.NodeMapNode node = (NodeMapNode)defaultGraph[subject_1];
				// 6.1)
				if (graphMap.ContainsKey(subject_1))
				{
					// 6.1.1)
                    node["@graph"] = new JArray();
					// 6.1.2)
                    JArray keys = new JArray(graphMap[subject_1].GetKeys());
					keys.SortInPlace();
					foreach (string s in keys)
					{
						JsonLdApi.NodeMapNode n = (NodeMapNode)graphMap[subject_1][s];
						if (n.Count == 1 && n.ContainsKey("@id"))
						{
							continue;
						}
						((JArray)node["@graph"]).Add(n.Serialize());
					}
				}
				// 6.2)
				if (node.Count == 1 && node.ContainsKey("@id"))
				{
					continue;
				}
				result.Add(node.Serialize());
			}
			return result;
		}
Beispiel #11
0
		/// <summary>Adds RDF triples for each graph in the given node map to an RDF dataset.
		/// 	</summary>
		/// <remarks>Adds RDF triples for each graph in the given node map to an RDF dataset.
		/// 	</remarks>
		/// <returns>the RDF dataset.</returns>
		/// <exception cref="JsonLdError">JsonLdError</exception>
		/// <exception cref="JsonLD.Core.JsonLdError"></exception>
		public virtual RDFDataset ToRDF()
		{
			// TODO: make the default generateNodeMap call (i.e. without a
			// graphName) create and return the nodeMap
			JObject nodeMap = new JObject();
			nodeMap["@default"] = new JObject();
			GenerateNodeMap(this.value, nodeMap);
			RDFDataset dataset = new RDFDataset(this);
			foreach (string graphName in nodeMap.GetKeys())
			{
				// 4.1)
				if (JsonLdUtils.IsRelativeIri(graphName))
				{
					continue;
				}
				JObject graph = (JObject)nodeMap[graphName
					];
				dataset.GraphToRDF(graphName, graph);
			}
			return dataset;
		}
        private static IEnumerable <object[]> SortingTestCases()
        {
            var jsonFetcher   = new JsonFetcher();
            var rootDirectory = Path.Combine(ManifestRoot, "Sorting");

            foreach (string manifest in SortingManifests)
            {
                JToken manifestJson = jsonFetcher.GetJson(manifest, rootDirectory);

                foreach (JObject testcase in manifestJson["sequence"])
                {
                    Func <JToken> run = null;
                    ExtendedFunctionalityTestCase newCase = new ExtendedFunctionalityTestCase();

                    newCase.input  = jsonFetcher.GetJson(manifestJson["input"], rootDirectory);
                    newCase.output = jsonFetcher.GetJson(testcase["expect"], rootDirectory);

                    var options = new JsonLdOptions();

                    var sortType = (string)testcase["sort-type"];

                    if (sortType == "jld:GraphsAndNodes")
                    {
                        options.SetSortGraphsFromRdf(true);
                        options.SetSortGraphNodesFromRdf(true);
                    }
                    else if (sortType == "jld:Graphs")
                    {
                        options.SetSortGraphsFromRdf(true);
                        options.SetSortGraphNodesFromRdf(false);
                    }
                    else if (sortType == "jld:Nodes")
                    {
                        options.SetSortGraphsFromRdf(false);
                        options.SetSortGraphNodesFromRdf(true);
                    }
                    else if (sortType == "jld:None")
                    {
                        options.SetSortGraphsFromRdf(false);
                        options.SetSortGraphNodesFromRdf(false);
                    }

                    JsonLdApi jsonLdApi = new JsonLdApi(options);

                    var testType = (string)testcase["test-type"];

                    if (testType == "jld:FromRDF")
                    {
                        JToken     quads = newCase.input["quads"];
                        RDFDataset rdf   = new RDFDataset();

                        foreach (JToken quad in quads)
                        {
                            string subject   = (string)quad["subject"];
                            string predicate = (string)quad["predicate"];
                            string value     = (string)quad["value"];
                            string graph     = (string)quad["graph"];

                            rdf.AddQuad(subject, predicate, value, graph);
                        }

                        options.format = "application/nquads";

                        run = () => jsonLdApi.FromRDF(rdf);
                    }
                    else
                    {
                        run = () => { throw new Exception("Couldn't find a test type, apparently."); };
                    }

                    newCase.run = run;

                    yield return(new object[] { manifest + (string)testcase["@id"], newCase });
                }
            }
        }
 public virtual object Call(RDFDataset dataset)
 {
     return RDFDatasetUtils.ToNQuads(dataset);
 }
Beispiel #14
0
 public virtual object Call(RDFDataset dataset)
 {
     return(RDFDatasetUtils.ToNQuads(dataset));
 }
Beispiel #15
0
 public virtual JToken Call(RDFDataset dataset)
 {
     return(RDFDatasetUtils.ToNQuads(dataset));
 }
Beispiel #16
0
 public object Call(RDFDataset dataset) =>
 RDFDatasetUtils.ToNQuads(dataset);     // serialize the RDF dataset as NQuads