예제 #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);
        }
예제 #2
0
        /// <summary>Uses a specific serializer.</summary>
        /// <remarks>Uses a specific serializer.</remarks>
        /// <exception cref="JsonLD.Core.JsonLdError"></exception>
        public static JToken FromRDF(JToken input, JsonLdOptions options, IRDFParser parser
                                     )
        {
            RDFDataset dataset = parser.Parse(input);
            // convert from RDF
            JToken rval = new JsonLdApi(options).FromRDF(dataset);

            // re-process using the generated context if outputForm is set
            if (options.outputForm != null)
            {
                if ("expanded".Equals(options.outputForm))
                {
                    return(rval);
                }
                else
                {
                    if ("compacted".Equals(options.outputForm))
                    {
                        return(Compact(rval, dataset.GetContext(), options));
                    }
                    else
                    {
                        if ("flattened".Equals(options.outputForm))
                        {
                            return(Flatten(rval, dataset.GetContext(), options));
                        }
                        else
                        {
                            throw new JsonLdError(JsonLdError.Error.UnknownError);
                        }
                    }
                }
            }
            return(rval);
        }
예제 #3
0
        /// <summary>Uses a specific serializer.</summary>
        /// <remarks>Uses a specific serializer.</remarks>
        /// <exception cref="JsonLdError"></exception>
        public static async Task <JToken> FromRdfAsync(JToken input,
                                                       JsonLdOptions options,
                                                       IRdfParser parser
                                                       )
        {
            var dataset = parser.Parse(input);

            // convert from RDF
            JToken rval = new JsonLdApi(options).FromRdf(dataset);

            // re-process using the generated context if outputForm is set
            if (options.outputForm != null)
            {
                if ("expanded".Equals(options.outputForm))
                {
                    return(rval);
                }
                else
                {
                    if ("compacted".Equals(options.outputForm))
                    {
                        return(await CompactAsync(rval, dataset.GetContext(), options));
                    }

                    if ("flattened".Equals(options.outputForm))
                    {
                        return(await FlattenAsync(rval, dataset.GetContext(), options));
                    }
                    throw new JsonLdError(JsonLdError.Error.UnknownError);
                }
            }

            return(rval);
        }
예제 #4
0
        /// <summary>Outputs the RDF dataset found in the given JSON-LD object.</summary>
        /// <remarks>Outputs the RDF dataset found in the given JSON-LD object.</remarks>
        /// <param name="input">the JSON-LD input.</param>
        /// <param name="callback"></param>
        /// <param name="options"></param>
        /// <exception cref="JsonLdError"></exception>
        public static async Task <object> ToRdfAsync(JToken input,
                                                     IJsonLdTripleCallback callback,
                                                     JsonLdOptions options)
        {
            JToken expandedInput = await ExpandAsync(input, options);

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

            var dataset = api.ToRdf();

            // generate namespaces from context
            if (options.useNamespaces)
            {
                JArray _input;
                if (input is JArray array)
                {
                    _input = array;
                }
                else
                {
                    _input = new JArray();
                    _input.Add((JObject)input);
                }

                foreach (var e in _input)
                {
                    if (((JObject)e).ContainsKey("@context"))
                    {
                        dataset.ParseContext((JObject)e["@context"]);
                    }
                }
            }

            if (callback != null)
            {
                return(callback.Call(dataset));
            }
            if (options.format != null)
            {
                if ("application/nquads".Equals(options.format))
                {
                    return(new NQuadTripleCallback().Call(dataset));
                }
                else
                {
                    if ("text/turtle".Equals(options.format))
                    {
                        return(new TurtleTripleCallback().Call(dataset));
                    }
                    throw new JsonLdError(JsonLdError.Error.UnknownFormat, options.format);
                }
            }

            return(dataset);
        }
예제 #5
0
        /// <summary>Outputs the RDF dataset found in the given JSON-LD object.</summary>
        /// <remarks>Outputs the RDF dataset found in the given JSON-LD object.</remarks>
        /// <param name="input">the JSON-LD input.</param>
        /// <param name="callback">
        /// A callback that is called when the input has been converted to
        /// Quads (null to use options.format instead).
        /// </param>
        /// <?></?>
        /// <param name="callback">(err, dataset) called once the operation completes.</param>
        /// <exception cref="JsonLDNet.Core.JsonLdError"></exception>
        public static object ToRDF(JToken input, IJSONLDTripleCallback callback, JsonLdOptions
                                   options)
        {
            JToken     expandedInput = Expand(input, options);
            JsonLdApi  api           = new JsonLdApi(expandedInput, options);
            RDFDataset dataset       = api.ToRDF();

            // generate namespaces from context
            if (options.useNamespaces)
            {
                JArray _input;
                if (input is JArray)
                {
                    _input = (JArray)input;
                }
                else
                {
                    _input = new JArray();
                    _input.Add((JObject)input);
                }
                foreach (JToken e in _input)
                {
                    if (((JObject)e).ContainsKey("@context"))
                    {
                        dataset.ParseContext((JObject)e["@context"]);
                    }
                }
            }
            if (callback != null)
            {
                return(callback.Call(dataset));
            }
            if (options.format != null)
            {
                if ("application/nquads".Equals(options.format))
                {
                    return(new NQuadTripleCallback().Call(dataset));
                }
                else
                {
                    if ("text/turtle".Equals(options.format))
                    {
                        return(new TurtleTripleCallback().Call(dataset));
                    }
                    else
                    {
                        throw new JsonLdError(JsonLdError.Error.UnknownFormat, options.format);
                    }
                }
            }
            return(dataset);
        }
예제 #6
0
        /// <exception cref="JsonLD.Core.JsonLdError"></exception>
        public static JObject Compact(JToken input, JToken context, JsonLdOptions
                                      opts)
        {
            // 1)
            // TODO: look into java futures/promises
            // 2-6) NOTE: these are all the same steps as in expand
            JToken expanded = Expand(input, opts);

            // 7)
            if (context is JObject && ((IDictionary <string, JToken>)context).ContainsKey(
                    "@context"))
            {
                context = ((JObject)context)["@context"];
            }
            Context activeCtx = new Context(opts);

            activeCtx = activeCtx.Parse(context);
            // 8)
            JToken compacted = new JsonLdApi(opts).Compact(activeCtx, null, expanded, opts.GetCompactArrays
                                                               ());

            // final step of Compaction Algorithm
            // TODO: SPEC: the result result is a NON EMPTY array,
            if (compacted is JArray)
            {
                if (((JArray)compacted).IsEmpty())
                {
                    compacted = new JObject();
                }
                else
                {
                    JObject tmp = new JObject();
                    // TODO: SPEC: doesn't specify to use vocab = true here
                    tmp[activeCtx.CompactIri("@graph", true)] = compacted;
                    compacted = tmp;
                }
            }
            if (!compacted.IsNull() && !context.IsNull())
            {
                // TODO: figure out if we can make "@context" appear at the start of
                // the keySet
                if ((context is JObject && !((JObject)context).IsEmpty()) ||
                    (context is JArray && !((JArray)context).IsEmpty()))
                {
                    compacted["@context"] = context;
                }
            }
            // 9)
            return((JObject)compacted);
        }
예제 #7
0
        /// <exception cref="JsonLdError"></exception>
        public static async Task <JObject> CompactAsync(JToken input,
                                                        JToken context,
                                                        JsonLdOptions opts)
        {
            // 1)
            // TODO: look into java futures/promises
            // 2-6) NOTE: these are all the same steps as in expand
            JToken expanded = await ExpandAsync(input, opts);

            // 7)
            if (context is JObject jObj && jObj.ContainsKey("@context"))
            {
                context = jObj["@context"];
            }

            var activeCtx = await Context.ParseAsync(context, opts);

            // 8)
            var compacted = new JsonLdApi(opts).Compact(activeCtx,
                                                        null,
                                                        expanded,
                                                        opts.GetCompactArrays
                                                            ());

            // final step of Compaction Algorithm
            // TODO: SPEC: the result result is a NON EMPTY array,
            if (compacted is JArray jArray)
            {
                compacted = jArray.IsEmpty() ? new JObject() : new JObject {
                    [activeCtx.CompactIri("@graph", true)] = compacted
                }
            }
            ;

            if (!compacted.IsNull() && !context.IsNull())
            {
                if (context is JObject && !((JObject)context).IsEmpty() ||
                    context is JArray && !((JArray)context).IsEmpty())
                {
                    compacted["@context"] = context;
                }
            }

            // 9)
            return((JObject)compacted);
        }
예제 #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);
        }
예제 #9
0
        /// <exception cref="JsonLD.Core.JsonLdError"></exception>
        public static JArray Expand(JToken input, JsonLdOptions opts)
        {
            // 1)
            // TODO: look into java futures/promises

            // 2) verification of DOMString IRI
            bool isIriString = input.Type == JTokenType.String;

            if (isIriString)
            {
                bool hasColon = false;
                foreach (var c in ((string)input))
                {
                    if (c == ':')
                    {
                        hasColon = true;
                    }

                    if (!hasColon && (c == '{' || c == '['))
                    {
                        isIriString = false;
                        break;
                    }
                }
            }

            if (isIriString)
            {
                try
                {
                    RemoteDocument tmp = opts.documentLoader.LoadDocument((string)input);
                    input = tmp.document;
                }
                catch (Exception e)
                {
                    // TODO: figure out how to deal with remote context
                    throw new JsonLdError(JsonLdError.Error.LoadingDocumentFailed, e.Message);
                }
                // if set the base in options should override the base iri in the
                // active context
                // thus only set this as the base iri if it's not already set in
                // options
                if (opts.GetBase() == null)
                {
                    opts.SetBase((string)input);
                }
            }
            // 3)
            Context activeCtx = new Context(opts);

            // 4)
            if (opts.GetExpandContext() != null)
            {
                JObject exCtx = opts.GetExpandContext();
                if (exCtx is JObject && ((IDictionary <string, JToken>)exCtx).ContainsKey("@context"
                                                                                          ))
                {
                    exCtx = (JObject)((IDictionary <string, JToken>)exCtx)["@context"];
                }
                activeCtx = activeCtx.Parse(exCtx);
            }
            // 5)
            // TODO: add support for getting a context from HTTP when content-type
            // is set to a jsonld compatable format
            // 6)
            JToken expanded = new JsonLdApi(opts).Expand(activeCtx, input);

            // final step of Expansion Algorithm
            if (expanded is JObject && ((IDictionary <string, JToken>)expanded).ContainsKey("@graph") && (
                    (IDictionary <string, JToken>)expanded).Count == 1)
            {
                expanded = ((JObject)expanded)["@graph"];
            }
            else
            {
                if (expanded.IsNull())
                {
                    expanded = new JArray();
                }
            }
            // normalize to an array
            if (!(expanded is JArray))
            {
                JArray tmp = new JArray();
                tmp.Add(expanded);
                expanded = tmp;
            }
            return((JArray)expanded);
        }
예제 #10
0
        /// <exception cref="JsonLD.Core.JsonLdError"></exception>
        public static JToken Flatten(JToken input, JToken context, JsonLdOptions opts)
        {
            // 2-6) NOTE: these are all the same steps as in expand
            JArray expanded = Expand(input, opts);

            // 7)
            if (context is JObject && ((IDictionary <string, JToken>)context).ContainsKey(
                    "@context"))
            {
                context = context["@context"];
            }
            // 8) NOTE: blank node generation variables are members of JsonLdApi
            // 9) NOTE: the next block is the Flattening Algorithm described in
            // http://json-ld.org/spec/latest/json-ld-api/#flattening-algorithm
            // 1)
            JObject nodeMap = new JObject();

            nodeMap["@default"] = new JObject();
            // 2)
            new JsonLdApi(opts).GenerateNodeMap(expanded, nodeMap);
            // 3)
            JObject defaultGraph = (JObject)JsonLD.Collections.Remove
                                       (nodeMap, "@default");

            // 4)
            foreach (string graphName in nodeMap.GetKeys())
            {
                JObject graph = (JObject)nodeMap[graphName];
                // 4.1+4.2)
                JObject entry;
                if (!defaultGraph.ContainsKey(graphName))
                {
                    entry                   = new JObject();
                    entry["@id"]            = graphName;
                    defaultGraph[graphName] = entry;
                }
                else
                {
                    entry = (JObject)defaultGraph[graphName];
                }
                // 4.3)
                // TODO: SPEC doesn't specify that this should only be added if it
                // doesn't exists
                if (!entry.ContainsKey("@graph"))
                {
                    entry["@graph"] = new JArray();
                }
                JArray keys = new JArray(graph.GetKeys());
                keys.SortInPlace();
                foreach (string id in keys)
                {
                    JObject node = (JObject)graph[id];
                    if (!(node.ContainsKey("@id") && node.Count == 1))
                    {
                        ((JArray)entry["@graph"]).Add(node);
                    }
                }
            }
            // 5)
            JArray flattened = new JArray();
            // 6)
            JArray keys_1 = new JArray(defaultGraph.GetKeys());

            keys_1.SortInPlace();
            foreach (string id_1 in keys_1)
            {
                JObject node = (JObject)defaultGraph[id_1
                               ];
                if (!(node.ContainsKey("@id") && node.Count == 1))
                {
                    flattened.Add(node);
                }
            }
            // 8)
            if (!context.IsNull() && !flattened.IsEmpty())
            {
                Context activeCtx = new Context(opts);
                activeCtx = activeCtx.Parse(context);
                // TODO: only instantiate one jsonldapi
                JToken compacted = new JsonLdApi(opts).Compact(activeCtx, null, flattened, opts.GetCompactArrays
                                                                   ());
                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;
                return(rval);
            }
            return(flattened);
        }
예제 #11
0
 public RDFDataset(JsonLdApi jsonLdApi) : this()
 {
     // put("@context", context);
     this.api = jsonLdApi;
 }
        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 });
                }
            }
        }
예제 #13
0
 public RdfDataset(JsonLdApi jsonLdApi) : this()
 {
     // put("@context", context);
     api = jsonLdApi;
 }