private static JArray Expand(RemoteDocument doc, Uri documentLocation,
                                     JsonLdProcessorOptions options = null)
        {
            var activeContext = new JsonLdContext {
                Base = documentLocation
            };

            if (options?.Base != null)
            {
                activeContext.Base = options.Base;
            }
            var processor = new JsonLdProcessor(options);

            if (options?.ExpandContext != null)
            {
                var expandObject = options.ExpandContext as JObject;
                if (expandObject != null)
                {
                    var contextProperty = expandObject.Property("@context");
                    if (contextProperty != null)
                    {
                        activeContext = processor.ProcessContext(activeContext, contextProperty.Value);
                    }
                    else
                    {
                        activeContext = processor.ProcessContext(activeContext, expandObject);
                    }
                }
                else
                {
                    activeContext = processor.ProcessContext(activeContext, options.ExpandContext);
                }
            }
            if (doc.ContextUrl != null)
            {
                var contextDoc = LoadJson(doc.ContextUrl, options);
                if (contextDoc.Document is string)
                {
                    contextDoc.Document = JToken.Parse(contextDoc.Document as string);
                }
                activeContext = processor.ProcessContext(activeContext, contextDoc.Document as JToken);
            }
            if (doc.Document is string)
            {
                doc.Document = JToken.Parse(doc.Document as string);
            }
            return(processor.Expand(activeContext, null, doc.Document as JToken));
        }
Exemple #2
0
        /// <summary>
        /// Flattens the given input and compacts it using the passed context according to the steps in the JSON-LD Flattening algorithm.
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static async Task <JToken> FlattenAsync(JToken input, JToken context, JsonLdProcessorOptions options = null)
        {
            var processor = new JsonLdProcessor(options);

            // Set expanded input to the result of using the expand method using input and options.
            var expandedInput = await ExpandAsync(input, options);

            // If context is a dictionary having an @context member, set context to that member's value, otherwise to context.
            var contextObject = context as JObject;

            if (contextObject?.Property("@context") != null)
            {
                context = contextObject["@context"];
            }
            return(processor.FlattenWrapper(expandedInput, context, options?.CompactArrays ?? true));
        }
        public void JsonLdFramingTests(string inputPath, string framePath, string expectedOutputPath,
                                       bool pruneBlankNodeIdentifiers)
        {
            var inputJson          = File.ReadAllText(inputPath);
            var frameJson          = File.ReadAllText(framePath);
            var expectedOutputJson = File.ReadAllText(expectedOutputPath);
            var options            = new JsonLdProcessorOptions {
                PruneBlankNodeIdentifiers = pruneBlankNodeIdentifiers
            };
            var inputElement          = JToken.Parse(inputJson);
            var frameElement          = JToken.Parse(frameJson);
            var expectedOutputElement = JToken.Parse(expectedOutputJson);
            var actualOutput          = JsonLdProcessor.Frame(inputElement, frameElement, options);

            Assert.True(JToken.DeepEquals(expectedOutputElement, actualOutput),
                        $"Test failed for input {Path.GetFileName(inputPath)}\nExpected:\n{expectedOutputElement}\nActual:\n{actualOutput}");
        }
        private static RemoteDocument LoadJson(Uri remoteRef, JsonLdProcessorOptions options)
        {
            if (options.Loader != null)
            {
                return(options.Loader(remoteRef));
            }

            var client         = new RedirectingWebClient();
            var responseString = client.DownloadString(remoteRef);
            var contentType    = client.ResponseHeaders.GetValues("Content-Type");

            if (contentType == null ||
                !contentType.Any(x => x.Contains("application/json") ||
                                 x.Contains("application/ld+json") ||
                                 x.Contains("+json")))
            {
                throw new JsonLdProcessorException(
                          JsonLdErrorCode.LoadingDocumentFailed,
                          $"Loading document failed from {remoteRef} - retrieved content type ({contentType}) was not application/json, application/ld+json or */*+json.");
            }

            string contextLink = null;

            // If content type is application/ld+json the context link header is ignored
            if (!contentType.Any(x => x.Contains("application/ld+json")))
            {
                var contextLinks = ParseLinkHeaders(client.ResponseHeaders.GetValues("Link"))
                                   .Where(x => x.RelationTypes.Contains("http://www.w3.org/ns/json-ld#context"))
                                   .Select(x => x.LinkValue).ToList();
                if (contextLinks.Count > 1)
                {
                    throw new JsonLdProcessorException(JsonLdErrorCode.MultipleContextLinkHeaders, "Multiple context link headers");
                }
                contextLink = contextLinks.FirstOrDefault();
            }

            var ret = new RemoteDocument
            {
                ContextUrl  = contextLink == null ? null : new Uri(contextLink),
                DocumentUrl = client.ResponseUri,
                Document    = JToken.Parse(responseString),
            };

            return(ret);
        }
        private static JsonLdProcessorOptions MakeProcessorOptions(string inputPath,
                                                                   string baseIri,
                                                                   string processorMode,
                                                                   string expandContextPath,
                                                                   bool compactArrays,
                                                                   string rdfDirection)
        {
            var processorOptions = new JsonLdProcessorOptions
            {
                Base = baseIri != null
                    ? new Uri(baseIri)
                    : new Uri("http://json-ld.org/test-suite/tests/" + Path.GetFileName(inputPath))
            };

            if (processorMode != null)
            {
                processorOptions.ProcessingMode = processorMode.Equals("json-ld-1.1")
                    ? JsonLdProcessingMode.JsonLd11
                    : JsonLdProcessingMode.JsonLd10;
            }
            if (expandContextPath != null)
            {
                var expandContextJson = File.ReadAllText(expandContextPath);
                processorOptions.ExpandContext = JObject.Parse(expandContextJson);
            }
            processorOptions.CompactArrays = compactArrays;
            if (!string.IsNullOrEmpty(rdfDirection))
            {
                switch (rdfDirection)
                {
                case "i18n-datatype":
                    processorOptions.RdfDirection = JsonLdRdfDirectionMode.I18NDatatype;
                    break;

                case "compound-literal":
                    processorOptions.RdfDirection = JsonLdRdfDirectionMode.CompoundLiteral;
                    break;

                default:
                    throw new Exception($"Unexpected value for rdfDirection option in test {inputPath}");
                }
            }
            return(processorOptions);
        }
Exemple #6
0
        private static async Task <RemoteDocument> LoadJsonAsync(Uri remoteRef, JsonLdProcessorOptions options)
        {
            if (options.Loader != null)
            {
                return(options.Loader(remoteRef));
            }
            var client   = new HttpClient();
            var response = await client.GetAsync(remoteRef);

            response.EnsureSuccessStatusCode();
            if (response.Headers.GetValues("Content-Type")
                .Any(x => x.Contains("application/json") || x.Contains("application/ld+json") || x.Contains("+json")))
            {
                throw new JsonLdProcessorException(JsonLdErrorCode.LoadingDocumentFailed, "Loading document failed from {remoteRef} - retrieved content type was not application/json, application/ld+json or */*+json.");
            }
            var responseString = await response.Content.ReadAsStringAsync();

            string contextLink = null;

            // If content type is application/ld+json the context link header is ignored
            if (!response.Headers.GetValues("Content-Type").Any(x => x.Contains("application/ld+json")))
            {
                var contextLinks = ParseLinkHeaders(response.Headers.GetValues("Link"))
                                   .Where(x => x.RelationTypes.Contains("http://www.w3.org/ns/json-ld#context"))
                                   .Select(x => x.LinkValue).ToList();
                if (contextLinks.Count > 1)
                {
                    throw new JsonLdProcessorException(JsonLdErrorCode.MultipleContextLinkHeaders, "Multiple context link headers");
                }
                contextLink = contextLinks.FirstOrDefault();
            }

            var ret = new RemoteDocument
            {
                ContextUrl  = contextLink == null ? null : new Uri(contextLink),
                DocumentUrl = response.RequestMessage.RequestUri,
                Document    = JToken.Parse(responseString),
            };

            return(ret);
        }
        /// <summary>
        /// Apply the JSON-LD context expansion algorithm to the context found at the specified URL
        /// </summary>
        /// <param name="contextUrl">The URL to load the source context from</param>
        /// <param name="options">Options to apply during the expansion processing</param>
        /// <returns>The expanded JSON-LD contex</returns>
        public static JArray Expand(Uri contextUrl, JsonLdProcessorOptions options = null)
        {
            var parsedJson = LoadJson(contextUrl, options);

            return(Expand(parsedJson, contextUrl, options));
        }
Exemple #8
0
        /// <summary>
        /// Run the Compaction algorithm asynchronously
        /// </summary>
        /// <param name="input">The JSON-LD data to be compacted. Expected to be a JObject or JArray of JObject or a JString whose value is the IRI reference to a JSON-LD document to be retrieved</param>
        /// <param name="context">The context to use for the compaction process. May be a JObject, JArray of JObject, JString or JArray of JString. String values are treated as IRI references to context documents to be retrieved</param>
        /// <param name="options">Additional processor options</param>
        /// <returns></returns>
        public static async Task <JObject> CompactAsync(JToken input, JToken context, JsonLdProcessorOptions options)
        {
            var processor = new JsonLdProcessor(options);

            // Set expanded input to the result of using the expand method using input and options.
            var expandedInput = await ExpandAsync(input, options);

            // If context is a dictionary having an @context member, set context to that member's value, otherwise to context.
            var contextProperty = (context as JObject)?.Property("@context");

            if (contextProperty != null)
            {
                context = contextProperty.Value;
            }
            // Set compacted output to the result of using the Compaction algorithm, passing context as active context, an empty dictionary as inverse context, null as property, expanded input as element, and if passed, the compactArrays flag in options.
            var compactResult = processor.CompactWrapper(context, new JObject(), null, expandedInput, options.CompactArrays);

            return(compactResult);
        }
Exemple #9
0
        /// <summary>
        /// Return the result of expanding the JSON document retrieved from the specified URL
        /// </summary>
        /// <param name="inputUrl"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static async Task <JArray> ExpandAsync(Uri inputUrl, JsonLdProcessorOptions options = null)
        {
            var parsedJson = await LoadJsonAsync(inputUrl, options);

            return(await ExpandAsync(parsedJson, inputUrl, options));
        }
Exemple #10
0
 /// <summary>
 /// Return the result of expanding a parsed JSON document
 /// </summary>
 /// <param name="input">The parsed JSON to be expanded</param>
 /// <param name="options"></param>
 /// <returns></returns>
 public static JArray Expand(JToken input, JsonLdProcessorOptions options = null)
 {
     return(ExpandAsync(input, options).Result);
 }
Exemple #11
0
 /// <summary>
 /// Return the result of expanding the JSON-LD document retrieved from the specified URL
 /// </summary>
 /// <param name="inputUrl"></param>
 /// <param name="options"></param>
 /// <returns></returns>
 public static JArray Expand(Uri inputUrl, JsonLdProcessorOptions options = null)
 {
     return(ExpandAsync(inputUrl, options).Result);
 }
 /// <summary>
 /// Create a new provider instance configured using the specified options.
 /// </summary>
 /// <param name="options"></param>
 public RemoteContextProvider(JsonLdProcessorOptions options)
 {
     _options            = options;
     _remoteContextCache = new Dictionary <Uri, JsonLdRemoteContext>();
 }