コード例 #1
0
        private static JToken GetJsonRepresentation(RemoteDocument remoteDoc)
        {
            switch (remoteDoc.Document)
            {
            case JToken representation:
                return(representation);

            case string docStr:
            {
                try
                {
                    return(JToken.Parse(docStr));
                }
                catch (Exception ex)
                {
                    throw new JsonLdProcessorException(JsonLdErrorCode.InvalidRemoteContext,
                                                       "Could not parse remote content as a JSON document. ", ex);
                }
            }

            default:
                throw new JsonLdProcessorException(JsonLdErrorCode.InvalidRemoteContext,
                                                   "Could not parse remote content as a JSON document.");
            }
        }
コード例 #2
0
        public static RemoteDocument LoadJson(Uri remoteRef, JsonLdLoaderOptions loaderOptions)
        {
            var client = new RedirectingWebClient();

            client.Headers.Set(HttpRequestHeader.Accept, "application/ld+json;q=1.0, application/json;q=0.9, */*+json;q=0.8");

            var  responseString     = client.DownloadString(remoteRef);
            var  contentType        = client.ResponseHeaders.GetValues("Content-Type");
            bool matchesContentType =
                contentType != null &&
                contentType.Any(x => x.Contains("application/json") ||
                                (x.Contains("application/ld+json") &&
                                 string.IsNullOrEmpty(loaderOptions.RequestProfile)) ||
                                (x.Contains("application/ld+json") &&
                                 !string.IsNullOrEmpty(loaderOptions.RequestProfile) &&
                                 x.Contains(loaderOptions.RequestProfile)) ||
                                x.Contains("+json"));
            var    documentUrl = client.ResponseUri;
            string contextLink = null;

            if (!matchesContentType)
            {
                var contextLinks  = ParseLinkHeaders(client.ResponseHeaders.GetValues("Link"));
                var alternateLink = contextLinks.FirstOrDefault(link =>
                                                                link.RelationTypes.Contains("alternate") && link.MediaTypes.Contains("application/ld+json"));
                if (alternateLink != null)
                {
                    return(LoadJson(new Uri(remoteRef, alternateLink.LinkValue), loaderOptions));
                }
                else
                {
                    throw new JsonLdProcessorException(JsonLdErrorCode.LoadingDocumentFailed,
                                                       "Loading document failed. The server did not respond with a processable JSON document.");
                }
            }

            // 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(JsonLdVocabulary.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);
        }
コード例 #3
0
        private static async Task <JArray> ExpandAsync(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 = await LoadJsonAsync(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));
        }
コード例 #4
0
        private static async Task <RemoteDocument> LoadJsonAsync(Uri remoteRef, JsonLdProcessorOptions options)
        {
            if (options.Loader != null)
            {
                return(options.Loader(remoteRef));
            }
            var client = new HttpClient()
            {
                Timeout = TimeSpan.FromMilliseconds(Options.UriLoaderTimeout),
            };
            var response = await client.GetAsync(remoteRef).ConfigureAwait(false);

            response.EnsureSuccessStatusCode();
            var mediaType = response.Content.Headers.ContentType.MediaType;

            if (!(mediaType.Equals("application/json") || mediaType.EndsWith("+json")))
            {
                throw new JsonLdProcessorException(
                          JsonLdErrorCode.LoadingDocumentFailed,
                          $"Loading document failed from {remoteRef} - retrieved content type ({mediaType}) was not application/json, application/ld+json or */*+json.");
            }
            var responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            string contextLink = null;

            // If content type is application/ld+json the context link header is ignored
            if (!mediaType.Equals("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);
        }
コード例 #5
0
        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);
        }