Exemplo n.º 1
0
        /// <exception cref="JsonLD.Core.JsonLdError"></exception>
        public static JObject Frame(JToken input, JToken frame, JsonLdOptions
                                    options)
        {
            if (frame is JObject)
            {
                frame = JsonLdUtils.Clone((JObject)frame);
            }
            // TODO string/IO input
            JToken    expandedInput = Expand(input, options);
            JArray    expandedFrame = Expand(frame, options);
            JsonLdApi api           = new JsonLdApi(expandedInput, options);
            JArray    framed        = api.Frame(expandedInput, expandedFrame);
            Context   activeCtx     = api.context.Parse(frame["@context"
                                                        ]);
            JToken compacted = api.Compact(activeCtx, null, framed);

            if (!(compacted is JArray))
            {
                JArray tmp = new JArray();
                tmp.Add(compacted);
                compacted = tmp;
            }
            string  alias = activeCtx.CompactIri("@graph");
            JObject rval  = activeCtx.Serialize();

            rval[alias] = compacted;
            JsonLdUtils.RemovePreserve(activeCtx, rval, options);
            return(rval);
        }
Exemplo n.º 2
0
 /// <summary>Copies this UniqueNamer.</summary>
 /// <remarks>Copies this UniqueNamer.</remarks>
 /// <returns>a copy of this UniqueNamer.</returns>
 public virtual JsonLD.Core.UniqueNamer Clone()
 {
     JsonLD.Core.UniqueNamer copy = new JsonLD.Core.UniqueNamer(this.prefix);
     copy.counter  = this.counter;
     copy.existing = (JObject)JsonLdUtils.Clone(this.existing);
     return(copy);
 }
Exemplo n.º 3
0
        /// <summary>Copies this UniqueNamer.</summary>
        /// <remarks>Copies this UniqueNamer.</remarks>
        /// <returns>a copy of this UniqueNamer.</returns>
        public virtual UniqueNamer Clone()
        {
            var copy = new UniqueNamer(prefix);

            copy.counter  = counter;
            copy.existing = (JObject)JsonLdUtils.Clone(existing);
            return(copy);
        }
Exemplo n.º 4
0
 public Permutator(JArray list)
 {
     this.list = (JArray)JsonLdUtils.Clone(list);
     this.list.SortInPlace();
     this.done = false;
     this.left = new Dictionary <string, bool>();
     foreach (string i in this.list)
     {
         this.left[i] = true;
     }
 }
Exemplo n.º 5
0
            /// <summary>Gets the next permutation.</summary>
            /// <remarks>
            ///     Gets the next permutation. Call hasNext() to ensure there is another
            ///     one first.
            /// </remarks>
            /// <returns>the next permutation.</returns>
            public virtual JArray Next()
            {
                var rval = (JArray)JsonLdUtils.Clone(list);

                // Calculate the next permutation using Steinhaus-Johnson-Trotter
                // permutation algoritm
                // get largest mobile element k
                // (mobile: element is grater than the one it is looking at)
                string k      = null;
                var    pos    = 0;
                var    length = list.Count;

                for (var i = 0; i < length; ++i)
                {
                    var element = (string)list[i];
                    var left    = this.left[element];
                    if ((k == null || string.CompareOrdinal(element, k) > 0) &&
                        (left && i > 0 && string.CompareOrdinal(element, (string)list[i - 1]) > 0 ||
                         !left && i < length - 1 && string.CompareOrdinal(element, (string)list[i + 1]) > 0))
                    {
                        k   = element;
                        pos = i;
                    }
                }

                // no more permutations
                if (k == null)
                {
                    done = true;
                }
                else
                {
                    // swap k and the element it is looking at
                    var swap = left[k] ? pos - 1 : pos + 1;
                    list[pos]  = list[swap];
                    list[swap] = k;

                    // reverse the direction of all element larger than k
                    for (var i_1 = 0; i_1 < length; i_1++)
                    {
                        if (string.CompareOrdinal((string)list[i_1], k) > 0)
                        {
                            left[(string)list[i_1]] = !left[(string)list[i_1]];
                        }
                    }
                }

                return(rval);
            }
Exemplo n.º 6
0
 /// <summary>parses a @context object and sets any namespaces found within it</summary>
 /// <param name="context"></param>
 public virtual void ParseContext(JObject context)
 {
     foreach (string key in context.GetKeys())
     {
         JToken val = context[key];
         if ("@vocab".Equals(key))
         {
             if (val.IsNull() || JsonLdUtils.IsString(val))
             {
                 SetNamespace(string.Empty, (string)val);
             }
         }
         else
         {
             // TODO: the context is actually invalid, should we throw an
             // exception?
             if ("@context".Equals(key))
             {
                 // go deeper!
                 ParseContext((JObject)context["@context"]);
             }
             else
             {
                 if (!JsonLdUtils.IsKeyword(key))
                 {
                     // TODO: should we make sure val is a valid URI prefix (i.e. it
                     // ends with /# or ?)
                     // or is it ok that full URIs for terms are used?
                     if (val.Type == JTokenType.String)
                     {
                         SetNamespace(key, (string)context[key]);
                     }
                     else
                     {
                         if (JsonLdUtils.IsObject(val) && ((JObject)val).ContainsKey("@id"
                                                                                     ))
                         {
                             SetNamespace(key, (string)((JObject)val)["@id"]);
                         }
                     }
                 }
             }
         }
     }
 }
Exemplo n.º 7
0
 /// <summary>parses a @context object and sets any namespaces found within it</summary>
 /// <param name="context"></param>
 public virtual void ParseContext(JObject context)
 {
     foreach (var key in context.GetKeys())
     {
         var val = context[key];
         if ("@vocab".Equals(key))
         {
             if (val.IsNull() || JsonLdUtils.IsString(val))
             {
                 SetNamespace(string.Empty, (string)val);
             }
         }
         else
         {
             // TODO: the context is actually invalid, should we throw an
             // exception?
             if ("@context".Equals(key))
             {
                 // go deeper!
                 ParseContext((JObject)context["@context"]);
             }
             else
             {
                 if (!JsonLdUtils.IsKeyword(key))
                 {
                     if (val.Type == JTokenType.String)
                     {
                         SetNamespace(key, (string)context[key]);
                     }
                     else
                     {
                         if (JsonLdUtils.IsObject(val) && ((JObject)val).ContainsKey("@id"
                                                                                     ))
                         {
                             SetNamespace(key, (string)((JObject)val)["@id"]);
                         }
                     }
                 }
             }
         }
     }
 }
Exemplo n.º 8
0
        /// <exception cref="JsonLdError"></exception>
        public static async Task <JObject> FrameAsync(JToken input,
                                                      JToken frame,
                                                      JsonLdOptions options)
        {
            if (frame is JObject)
            {
                frame = JsonLdUtils.Clone((JObject)frame);
            }

            // TODO string/IO input
            JToken expandedInput = await ExpandAsync(input, options);

            var expandedFrame = await ExpandAsync(frame, options);

            var api = await JsonLdApi.CreateAsync(expandedInput, options);

            var framed    = api.Frame(expandedInput, expandedFrame);
            var activeCtx = await api.context.ParseAsync(frame["@context"
                                                         ]);

            var compacted = api.Compact(activeCtx, null, framed);

            if (!(compacted is JArray))
            {
                compacted = new JArray {
                    compacted
                };
            }

            var alias = activeCtx.CompactIri("@graph");
            var rval  = activeCtx.Serialize();

            rval[alias] = compacted;
            JsonLdUtils.RemovePreserve(activeCtx, rval, options);
            return(rval);
        }
Exemplo n.º 9
0
        internal static JArray GraphToRDF(JObject graph, UniqueNamer
                                          namer)
        {
            // use RDFDataset.graphToRDF
            JArray rval = new JArray();

            foreach (string id in graph.GetKeys())
            {
                JObject node       = (JObject)graph[id];
                JArray  properties = new JArray(node.GetKeys());
                properties.SortInPlace();
                foreach (string property in properties)
                {
                    var    eachProperty = property;
                    JToken items        = node[eachProperty];
                    if ("@type".Equals(eachProperty))
                    {
                        eachProperty = JSONLDConsts.RdfType;
                    }
                    else
                    {
                        if (JsonLdUtils.IsKeyword(eachProperty))
                        {
                            continue;
                        }
                    }
                    foreach (JToken item in (JArray)items)
                    {
                        // RDF subjects
                        JObject subject = new JObject();
                        if (id.IndexOf("_:") == 0)
                        {
                            subject["type"]  = "blank node";
                            subject["value"] = namer.GetName(id);
                        }
                        else
                        {
                            subject["type"]  = "IRI";
                            subject["value"] = id;
                        }
                        // RDF predicates
                        JObject predicate = new JObject();
                        predicate["type"]  = "IRI";
                        predicate["value"] = eachProperty;
                        // convert @list to triples
                        if (JsonLdUtils.IsList(item))
                        {
                            ListToRDF((JArray)((JObject)item)["@list"], namer, subject
                                      , predicate, rval);
                        }
                        else
                        {
                            // convert value or node object to triple
                            object @object = ObjectToRDF(item, namer);
                            IDictionary <string, object> tmp = new Dictionary <string, object>();
                            tmp["subject"]   = subject;
                            tmp["predicate"] = predicate;
                            tmp["object"]    = @object;
                            rval.Add(tmp);
                        }
                    }
                }
            }
            return(rval);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Converts a JSON-LD value object to an RDF literal or a JSON-LD string or
        /// node object to an RDF resource.
        /// </summary>
        /// <remarks>
        /// Converts a JSON-LD value object to an RDF literal or a JSON-LD string or
        /// node object to an RDF resource.
        /// </remarks>
        /// <param name="item">the JSON-LD value or node object.</param>
        /// <param name="namer">the UniqueNamer to use to assign blank node names.</param>
        /// <returns>the RDF literal or RDF resource.</returns>
        private static JObject ObjectToRDF(JToken item, UniqueNamer namer)
        {
            JObject @object = new JObject();

            // convert value object to RDF
            if (JsonLdUtils.IsValue(item))
            {
                @object["type"] = "literal";
                JToken value    = ((JObject)item)["@value"];
                JToken datatype = ((JObject)item)["@type"];
                // convert to XSD datatypes as appropriate
                if (value.Type == JTokenType.Boolean || value.Type == JTokenType.Float || value.Type == JTokenType.Integer)
                {
                    // convert to XSD datatype
                    if (value.Type == JTokenType.Boolean)
                    {
                        @object["value"]    = value.ToString();
                        @object["datatype"] = datatype.IsNull() ? JSONLDConsts.XsdBoolean : datatype;
                    }
                    else
                    {
                        if (value.Type == JTokenType.Float)
                        {
                            // canonical double representation
                            @object["value"]    = string.Format("{0:0.0###############E0}", (double)value);
                            @object["datatype"] = datatype.IsNull() ? JSONLDConsts.XsdDouble : datatype;
                        }
                        else
                        {
                            DecimalFormat df = new DecimalFormat("0");
                            @object["value"]    = df.Format((int)value);
                            @object["datatype"] = datatype.IsNull() ? JSONLDConsts.XsdInteger : datatype;
                        }
                    }
                }
                else
                {
                    if (((IDictionary <string, JToken>)item).ContainsKey("@language"))
                    {
                        @object["value"]    = value;
                        @object["datatype"] = datatype.IsNull() ? JSONLDConsts.RdfLangstring : datatype;
                        @object["language"] = ((IDictionary <string, JToken>)item)["@language"];
                    }
                    else
                    {
                        @object["value"]    = value;
                        @object["datatype"] = datatype.IsNull() ? JSONLDConsts.XsdString : datatype;
                    }
                }
            }
            else
            {
                // convert string/node object to RDF
                string id = JsonLdUtils.IsObject(item) ? (string)((JObject)item
                                                                  )["@id"] : (string)item;
                if (id.IndexOf("_:") == 0)
                {
                    @object["type"]  = "blank node";
                    @object["value"] = namer.GetName(id);
                }
                else
                {
                    @object["type"]  = "IRI";
                    @object["value"] = id;
                }
            }
            return(@object);
        }
Exemplo n.º 11
0
 /// <summary>
 /// Converts a JSON-LD value object to an RDF literal or a JSON-LD string or
 /// node object to an RDF resource.
 /// </summary>
 /// <remarks>
 /// Converts a JSON-LD value object to an RDF literal or a JSON-LD string or
 /// node object to an RDF resource.
 /// </remarks>
 /// <param name="item">the JSON-LD value or node object.</param>
 /// <param name="namer">the UniqueNamer to use to assign blank node names.</param>
 /// <returns>the RDF literal or RDF resource.</returns>
 private RDFDataset.Node ObjectToRDF(JToken item)
 {
     // convert value object to RDF
     if (JsonLdUtils.IsValue(item))
     {
         JToken value    = ((JObject)item)["@value"];
         JToken datatype = ((JObject)item)["@type"];
         // convert to XSD datatypes as appropriate
         if (value.Type == JTokenType.Boolean || value.Type == JTokenType.Float || value.Type == JTokenType.Integer)
         {
             // convert to XSD datatype
             if (value.Type == JTokenType.Boolean)
             {
                 var serializeObject = JsonConvert.SerializeObject(value, Formatting.None).Trim('"');
                 return(new RDFDataset.Literal(serializeObject, datatype.IsNull() ? JSONLDConsts.XsdBoolean
                      : (string)datatype, null));
             }
             else
             {
                 if (value.Type == JTokenType.Float || datatype.SafeCompare(JSONLDConsts.XsdDouble))
                 {
                     // Workaround for Newtonsoft.Json's refusal to cast a JTokenType.Integer to a double.
                     if (value.Type == JTokenType.Integer)
                     {
                         int number = (int)value;
                         value = new JValue((double)number);
                     }
                     // canonical double representation
                     return(new RDFDataset.Literal(string.Format(CultureInfo.InvariantCulture, "{0:0.0###############E0}", (double)value), datatype.IsNull() ? JSONLDConsts.XsdDouble
                          : (string)datatype, null));
                 }
                 else
                 {
                     return(new RDFDataset.Literal(string.Format("{0:0}", value), datatype.IsNull() ? JSONLDConsts.XsdInteger
                          : (string)datatype, null));
                 }
             }
         }
         else
         {
             if (((JObject)item).ContainsKey("@language"))
             {
                 return(new RDFDataset.Literal((string)value, datatype.IsNull() ? JSONLDConsts.RdfLangstring
                      : (string)datatype, (string)((JObject)item)["@language"]));
             }
             else
             {
                 var serializeObject = JsonConvert.SerializeObject(value, Formatting.None).Trim('"');
                 return(new RDFDataset.Literal(serializeObject, datatype.IsNull() ? JSONLDConsts.XsdString
                      : (string)datatype, null));
             }
         }
     }
     else
     {
         // convert string/node object to RDF
         string id;
         if (JsonLdUtils.IsObject(item))
         {
             id = (string)((JObject)item)["@id"];
             if (JsonLdUtils.IsRelativeIri(id))
             {
                 return(null);
             }
         }
         else
         {
             id = (string)item;
         }
         if (id.IndexOf("_:") == 0)
         {
             // NOTE: once again no need to rename existing blank nodes
             return(new RDFDataset.BlankNode(id));
         }
         else
         {
             return(new RDFDataset.IRI(id));
         }
     }
 }
Exemplo n.º 12
0
        /// <summary>Creates an array of RDF triples for the given graph.</summary>
        /// <remarks>Creates an array of RDF triples for the given graph.</remarks>
        /// <param name="graph">the graph to create RDF triples for.</param>
        internal virtual void GraphToRDF(string graphName, JObject graph
                                         )
        {
            // 4.2)
            IList <RDFDataset.Quad> triples = new List <RDFDataset.Quad>();
            // 4.3)
            IEnumerable <string> subjects = graph.GetKeys();

            // Collections.sort(subjects);
            foreach (string id in subjects)
            {
                if (JsonLdUtils.IsRelativeIri(id))
                {
                    continue;
                }
                JObject node       = (JObject)graph[id];
                JArray  properties = new JArray(node.GetKeys());
                properties.SortInPlace();
                foreach (string property in properties)
                {
                    var    localProperty = property;
                    JArray values;
                    // 4.3.2.1)
                    if ("@type".Equals(localProperty))
                    {
                        values        = (JArray)node["@type"];
                        localProperty = JSONLDConsts.RdfType;
                    }
                    else
                    {
                        // 4.3.2.2)
                        if (JsonLdUtils.IsKeyword(localProperty))
                        {
                            continue;
                        }
                        else
                        {
                            // 4.3.2.3)
                            if (localProperty.StartsWith("_:") && !api.opts.GetProduceGeneralizedRdf())
                            {
                                continue;
                            }
                            else
                            {
                                // 4.3.2.4)
                                if (JsonLdUtils.IsRelativeIri(localProperty))
                                {
                                    continue;
                                }
                                else
                                {
                                    values = (JArray)node[localProperty];
                                }
                            }
                        }
                    }
                    RDFDataset.Node subject;
                    if (id.IndexOf("_:") == 0)
                    {
                        // NOTE: don't rename, just set it as a blank node
                        subject = new RDFDataset.BlankNode(id);
                    }
                    else
                    {
                        subject = new RDFDataset.IRI(id);
                    }
                    // RDF predicates
                    RDFDataset.Node predicate;
                    if (localProperty.StartsWith("_:"))
                    {
                        predicate = new RDFDataset.BlankNode(localProperty);
                    }
                    else
                    {
                        predicate = new RDFDataset.IRI(localProperty);
                    }
                    foreach (JToken item in values)
                    {
                        // convert @list to triples
                        if (JsonLdUtils.IsList(item))
                        {
                            JArray          list       = (JArray)((JObject)item)["@list"];
                            RDFDataset.Node last       = null;
                            RDFDataset.Node firstBNode = nil;
                            if (!list.IsEmpty())
                            {
                                last       = ObjectToRDF(list[list.Count - 1]);
                                firstBNode = new RDFDataset.BlankNode(api.GenerateBlankNodeIdentifier());
                            }
                            triples.Add(new RDFDataset.Quad(subject, predicate, firstBNode, graphName));
                            for (int i = 0; i < list.Count - 1; i++)
                            {
                                RDFDataset.Node @object = ObjectToRDF(list[i]);
                                triples.Add(new RDFDataset.Quad(firstBNode, first, @object, graphName));
                                RDFDataset.Node restBNode = new RDFDataset.BlankNode(api.GenerateBlankNodeIdentifier
                                                                                         ());
                                triples.Add(new RDFDataset.Quad(firstBNode, rest, restBNode, graphName));
                                firstBNode = restBNode;
                            }
                            if (last != null)
                            {
                                triples.Add(new RDFDataset.Quad(firstBNode, first, last, graphName));
                                triples.Add(new RDFDataset.Quad(firstBNode, rest, nil, graphName));
                            }
                        }
                        else
                        {
                            // convert value or node object to triple
                            RDFDataset.Node @object = ObjectToRDF(item);
                            if (@object != null)
                            {
                                triples.Add(new RDFDataset.Quad(subject, predicate, @object, graphName));
                            }
                        }
                    }
                }
            }
            this[graphName] = triples;
        }
Exemplo n.º 13
0
 /// <summary>
 /// Converts a JSON-LD value object to an RDF literal or a JSON-LD string or
 /// node object to an RDF resource.
 /// </summary>
 /// <remarks>
 /// Converts a JSON-LD value object to an RDF literal or a JSON-LD string or
 /// node object to an RDF resource.
 /// </remarks>
 /// <param name="item">the JSON-LD value or node object.</param>
 /// <param name="namer">the UniqueNamer to use to assign blank node names.</param>
 /// <returns>the RDF literal or RDF resource.</returns>
 private RDFDataset.Node ObjectToRDF(JToken item)
 {
     // convert value object to RDF
     if (JsonLdUtils.IsValue(item))
     {
         JToken value    = ((JObject)item)["@value"];
         JToken datatype = ((JObject)item)["@type"];
         // convert to XSD datatypes as appropriate
         if (value.Type == JTokenType.Boolean || value.Type == JTokenType.Float || value.Type == JTokenType.Integer)
         {
             // convert to XSD datatype
             if (value.Type == JTokenType.Boolean)
             {
                 return(new RDFDataset.Literal(value.ToString(), datatype.IsNull() ? JSONLDConsts.XsdBoolean
                                                  : (string)datatype, null));
             }
             else
             {
                 if (value.Type == JTokenType.Float || datatype.SafeCompare(JSONLDConsts.XsdDouble))
                 {
                     // canonical double representation
                     return(new RDFDataset.Literal(string.Format("{0:0.0###############E0}", value), datatype.IsNull() ? JSONLDConsts.XsdDouble
                                                          : (string)datatype, null));
                 }
                 else
                 {
                     return(new RDFDataset.Literal(string.Format("{0:0}", value), datatype.IsNull() ? JSONLDConsts.XsdInteger
                                                          : (string)datatype, null));
                 }
             }
         }
         else
         {
             if (((JObject)item).ContainsKey("@language"))
             {
                 return(new RDFDataset.Literal((string)value, datatype.IsNull() ? JSONLDConsts.RdfLangstring
                                                  : (string)datatype, (string)((JObject)item)["@language"]));
             }
             else
             {
                 return(new RDFDataset.Literal((string)value, datatype.IsNull() ? JSONLDConsts.XsdString
                                                  : (string)datatype, null));
             }
         }
     }
     else
     {
         // convert string/node object to RDF
         string id;
         if (JsonLdUtils.IsObject(item))
         {
             id = (string)((JObject)item)["@id"];
             if (JsonLdUtils.IsRelativeIri(id))
             {
                 return(null);
             }
         }
         else
         {
             id = (string)item;
         }
         if (id.IndexOf("_:") == 0)
         {
             // NOTE: once again no need to rename existing blank nodes
             return(new RDFDataset.BlankNode(id));
         }
         else
         {
             return(new RDFDataset.IRI(id));
         }
     }
 }
Exemplo n.º 14
0
        private static IDictionary <string, string> modifyFirstDegreeComponent(IDictionary <string, string> component, string id)
        {
            if (!component["type"].Equals("blank node"))
            {
                return(component);
            }

            IDictionary <string, string> componentClone = (IDictionary <string, string>)JsonLdUtils.Clone(JToken.FromObject(component));

            if (componentClone["value"].Equals(id))
            {
                componentClone["value"] = "_:a";
            }
            else
            {
                componentClone["value"] = "_:z";
            }
            return(componentClone);
        }