public static JObject Expand(JToken swidTag) { // then, expand it out so we can walk it with strong types var expanded = JsonLdProcessor.Expand(Compact(swidTag), _options).FirstOrDefault().ToJObject(); return(SetStandardContext(expanded)); }
public static void Run() { var json = "{'@context':{'test':'http://www.example.org/'},'test:hello':'world'}"; var document = JObject.Parse(json); var expanded = JsonLdProcessor.Expand(document); Console.WriteLine(expanded); }
public static Page Create(Uri address, JToken compacted) { Page newPage = new Page(address); List <JToken> nodes = new List <JToken>(); int marker = 0; Mark(compacted, ref marker, nodes); JToken expanded = JsonLdProcessor.Expand(compacted, new JsonLdOptions()); Load(expanded, newPage._fragments, address, nodes); return(newPage); }
public static string GetExpandedIri(JToken context, string term) { if (term == JsonLdKeywords.Context) { return(null); } var value = new JObject { { JsonLdKeywords.Context, context }, { term, "value" } }; var expanded = JsonLdProcessor.Expand(value, new JsonLdOptions()); if (expanded.Any()) { return(((JProperty)expanded[0].First).Name); } return(null); }
/// <summary> /// Serializes the specified content type. /// </summary> /// <typeparam name="TModel">The type of the model.</typeparam> /// <param name="mediaRange">Type of the content.</param> /// <param name="model">The model.</param> /// <param name="outputStream">The output stream.</param> public void Serialize <TModel>(MediaRange mediaRange, TModel model, Stream outputStream) { WrappedModel?wrappedModel = model as WrappedModel?; var actualModel = wrappedModel == null ? model : wrappedModel.Value.Model; using (var writer = new StreamWriter(new UnclosableStreamWrapper(outputStream))) { JToken serialized = this.serializer.Serialize(actualModel); if (wrappedModel.HasValue) { serialized.AddBaseToContext(wrappedModel.Value.BaseUrl); } if (mediaRange.Parameters["profile"]?.Trim('"') == JsonLdProfiles.Expanded) { serialized = JsonLdProcessor.Expand(serialized); } else { if (serialized[JsonLdKeywords.Context] != null) { var contextMap = this.contextPathMapper.Contexts.FirstOrDefault(map => map.ModelType == actualModel.GetType()); if (contextMap != default(ContextPathMap) && wrappedModel != null) { var newContext = wrappedModel.Value.BaseUrl .Append(this.contextPathMapper.BasePath) .Append(contextMap.Path); serialized[JsonLdKeywords.Context] = newContext; } } } Debug.WriteLine("Serialized model: {0}", new object[] { serialized }); writer.Write(serialized); } }
public static JArray Run() { var compacted = Sample1_Compact.Run(); var expanded = JsonLdProcessor.Expand(compacted); Console.WriteLine(expanded); /* * * Output: * [ * { * "@id": "http://example.org/ld-experts", * "http://schema.org/member": [ * { * "http://schema.org/url": [ * { * "@id": "http://manu.sporny.org/" * } * ], * "http://schema.org/image": [ * { * "@id": "http://manu.sporny.org/images/manu.png" * } * ], * "http://schema.org/name": [ * { * "@value": "Manu Sporny" * } * ] * } * ] * } * ] * */ return(expanded); }
public IEnumerator <object[]> GetEnumerator() { foreach (string manifest in manifests) { JToken manifestJson; manifestJson = GetJson(manifest); foreach (JObject testcase in manifestJson["sequence"]) { Func <JToken> run; ConformanceCase newCase = new ConformanceCase(); newCase.input = GetJson(testcase["input"]); newCase.context = GetJson(testcase["context"]); newCase.frame = GetJson(testcase["frame"]); var options = new JsonLdOptions("http://json-ld.org/test-suite/tests/" + (string)testcase["input"]); var testType = (JArray)testcase["@type"]; if (testType.Any((s) => (string)s == "jld:NegativeEvaluationTest")) { newCase.error = testcase["expect"]; } else if (testType.Any((s) => (string)s == "jld:PositiveEvaluationTest")) { if (testType.Any((s) => new List <string> { "jld:ToRDFTest", "jld:NormalizeTest" }.Contains((string)s))) { newCase.output = File.ReadAllText(Path.Combine("W3C", (string)testcase["expect"])); } else if (testType.Any((s) => (string)s == "jld:FromRDFTest")) { newCase.input = File.ReadAllText(Path.Combine("W3C", (string)testcase["input"])); newCase.output = GetJson(testcase["expect"]); } else { newCase.output = GetJson(testcase["expect"]); } } else { throw new Exception("Expecting either positive or negative evaluation test."); } JToken optionToken; JToken value; if (testcase.TryGetValue("option", out optionToken)) { JObject optionDescription = (JObject)optionToken; if (optionDescription.TryGetValue("compactArrays", out value)) { options.SetCompactArrays((bool)value); } if (optionDescription.TryGetValue("base", out value)) { options.SetBase((string)value); } if (optionDescription.TryGetValue("expandContext", out value)) { newCase.context = GetJson(testcase["option"]["expandContext"]); options.SetExpandContext((JObject)newCase.context); } if (optionDescription.TryGetValue("produceGeneralizedRdf", out value)) { options.SetProduceGeneralizedRdf((bool)value); } if (optionDescription.TryGetValue("useNativeTypes", out value)) { options.SetUseNativeTypes((bool)value); } if (optionDescription.TryGetValue("useRdfType", out value)) { options.SetUseRdfType((bool)value); } } if (testType.Any((s) => (string)s == "jld:CompactTest")) { run = () => JsonLdProcessor.Compact(newCase.input, newCase.context, options); } else if (testType.Any((s) => (string)s == "jld:ExpandTest")) { run = () => JsonLdProcessor.Expand(newCase.input, options); } else if (testType.Any((s) => (string)s == "jld:FlattenTest")) { run = () => JsonLdProcessor.Flatten(newCase.input, newCase.context, options); } else if (testType.Any((s) => (string)s == "jld:FrameTest")) { run = () => JsonLdProcessor.Frame(newCase.input, newCase.frame, options); } else if (testType.Any((s) => (string)s == "jld:NormalizeTest")) { run = () => new JValue( RDFDatasetUtils.ToNQuads((RDFDataset)JsonLdProcessor.Normalize(newCase.input, options)).Replace("\n", "\r\n") ); } else if (testType.Any((s) => (string)s == "jld:ToRDFTest")) { options.format = "application/nquads"; run = () => new JValue( ((string)JsonLdProcessor.ToRDF(newCase.input, options)).Replace("\n", "\r\n") ); } else if (testType.Any((s) => (string)s == "jld:FromRDFTest")) { options.format = "application/nquads"; run = () => JsonLdProcessor.FromRDF(newCase.input, options); } else { run = () => { throw new Exception("Couldn't find a test type, apparently."); }; } if ((string)manifestJson["name"] == "Remote document") { Func <JToken> innerRun = run; run = () => { var remoteDoc = options.documentLoader.LoadDocument("https://json-ld.org/test-suite/tests/" + (string)testcase["input"]); newCase.input = remoteDoc.Document; options.SetBase(remoteDoc.DocumentUrl); options.SetExpandContext((JObject)remoteDoc.Context); return(innerRun()); }; } if (testType.Any((s) => (string)s == "jld:NegativeEvaluationTest")) { Func <JToken> innerRun = run; run = () => { try { return(innerRun()); } catch (JsonLdError err) { JObject result = new JObject(); result["error"] = err.Message; return(result); } }; } newCase.run = run; yield return(new object[] { manifest + (string)testcase["@id"], (string)testcase["name"], newCase }); } } }
/// <inheritdoc/> public void Load(IRdfHandler handler, TextReader input) { handler.StartRdf(); var rdfTypeNode = handler.CreateUriNode(new Uri(RdfNs + "type")); try { JToken element; using (var reader = new JsonTextReader(input) { DateParseHandling = DateParseHandling.None }) { element = JToken.ReadFrom(reader); } var expandedElement = JsonLdProcessor.Expand(element, ParserOptions); var nodeMap = JsonLdProcessor.GenerateNodeMap(expandedElement); foreach (var p in nodeMap.Properties()) { var graphName = p.Name; var graph = p.Value as JObject; if (graph == null) { continue; } Uri graphIri; if (graphName == "@default") { graphIri = null; } else { if (!Uri.TryCreate(graphName, UriKind.Absolute, out graphIri)) { continue; } } foreach (var gp in graph.Properties()) { var subject = gp.Name; var node = gp.Value as JObject; INode subjectNode; if (IsBlankNodeIdentifier(subject)) { subjectNode = handler.CreateBlankNode(subject.Substring(2)); } else { Uri subjectIri; if (!Uri.TryCreate(subject, UriKind.Absolute, out subjectIri)) { continue; } subjectNode = handler.CreateUriNode(subjectIri); } foreach (var np in node.Properties()) { var property = np.Name; var values = np.Value as JArray; if (property.Equals("@type")) { foreach (var type in values) { var typeNode = MakeNode(handler, type); handler.HandleTriple(new Triple(subjectNode, rdfTypeNode, typeNode, graphIri)); } } else if (JsonLdProcessor.IsKeyword(property)) { continue; } else if (JsonLdProcessor.IsBlankNodeIdentifier(property) && !ParserOptions.ProduceGeneralizedRdf) { continue; } else if (JsonLdProcessor.IsRelativeIri(property)) { continue; } else { foreach (var item in values) { var predicateNode = MakeNode(handler, property); var objectNode = MakeNode(handler, item); if (objectNode != null) { handler.HandleTriple(new Triple(subjectNode, predicateNode, objectNode, graphIri)); } } } } } } } catch (Exception) { handler.EndRdf(false); throw; } handler.EndRdf(true); }
private async Task <string> GetServiceUri(Uri type) { // Read the root document (usually out of the cache :)) JObject doc; var sourceUrl = new Uri(_source.Url); if (sourceUrl.IsFile) { using (var reader = new System.IO.StreamReader( sourceUrl.LocalPath)) { string json = await reader.ReadToEndAsync(); doc = JObject.Parse(json); } } else { doc = await _client.GetFile(sourceUrl); } var obj = JsonLdProcessor.Expand(doc).FirstOrDefault(); if (obj == null) { throw new NuGetProtocolException(Strings.Protocol_IndexMissingResourcesNode); } var resources = obj[ServiceUris.Resources.ToString()] as JArray; if (resources == null) { throw new NuGetProtocolException(Strings.Protocol_IndexMissingResourcesNode); } // Query it for the requested service var candidates = (from resource in resources.OfType <JObject>() let resourceType = resource["@type"].Select(t => t.ToString()).FirstOrDefault() where resourceType != null && Equals(resourceType, type.ToString()) select resource) .ToList(); NuGetTraceSources.V3SourceRepository.Verbose( "service_candidates", "Found {0} candidates for {1} service: [{2}]", candidates.Count, type, String.Join(", ", candidates.Select(c => c.Value <string>("@id")))); var selected = candidates.FirstOrDefault(); if (selected != null) { NuGetTraceSources.V3SourceRepository.Info( "getserviceuri", "Found {0} service at {1}", selected["@type"][0], selected["@id"]); return(selected.Value <string>("@id")); } else { NuGetTraceSources.V3SourceRepository.Error( "getserviceuri_failed", "Unable to find compatible {0} service on {1}", type, _root); return(null); } }
public async virtual Task <JArray> GetExpanded() { return(JsonLdProcessor.Expand(await GetJObject())); }
protected override void AssertSingleEntityMessage(string result) { JsonLdProcessor.Expand(JToken.Parse(result)).ToString().Should().Be(JsonLdProcessor.Expand(JToken.Parse(Body)).ToString()); }