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 JObject Run() { var doc = JObject.Parse(_docJson); var context = JObject.Parse(_contextJson); var opts = new JsonLdOptions(); var compacted = JsonLdProcessor.Compact(doc, context, opts); Console.WriteLine(compacted); /* * * Output: * { * "@id": "ld-experts", * "member": { * "image": "http://manu.sporny.org/images/manu.png", * "name": "Manu Sporny", * "homepage": "http://manu.sporny.org/", * }, * "name": "LD Experts", * "@context": . . . * } * */ return(compacted); }
public static void Main(string[] args) { String sparql = File.ReadAllText("../query.sparql"); //Console.WriteLine(sparql); var parameters = new Dictionary <string, string>(); parameters["query"] = sparql; parameters["format"] = "text/turtle"; var client = new HttpClient(); StringContent queryString = new StringContent(sparql); HttpResponseMessage resp = client.PostAsync("http://virhp07.libris.kb.se/sparql", new FormUrlEncodedContent(parameters)).Result; Console.WriteLine("Hello Mono World" + resp.StatusCode); var turtle = resp.Content.ReadAsStringAsync().Result; Console.WriteLine(turtle); var options = new JsonLdOptions() { format = "text/turtle" }; options.SetUseNativeTypes(true); var expanded = JsonLdProcessor.FromRDF(turtle, options); var context = File.ReadAllText("../context.jsonld"); var compOptions = new JsonLdOptions(); compOptions.SetEmbed(true); var compacted = JsonLdProcessor.Frame(expanded, context, compOptions); Console.WriteLine(turtle); Console.WriteLine(expanded); Console.WriteLine(compacted); }
public override async Task <ValidationResult> ValidateAsync(JToken proof, ProofOptions options) { var result = await base.ValidateAsync(proof, options); var verificationMethodId = Options.VerificationMethod["id"].ToString(); var controllerId = Controller ?? GetVerificationMethod() ?? throw new ProofValidationException("Controller or VerificationMethod not found"); var framed = JsonLdProcessor.Frame( controllerId, new JObject { { "@context", Constants.SECURITY_CONTEXT_V2_URL }, { "id", controllerId }, { Term, new JObject { { "@embed", "@never" }, { "id", verificationMethodId } } } }, options.GetProcessorOptions()); if (framed[Term] is JArray keys && keys.Any(x => x.ToString() == verificationMethodId)) { result.Controller = framed["id"].ToString(); return(result); } throw new ProofValidationException($"Verification method '{verificationMethodId}' not authorized " + $"by controller for proof purpose '{Term}'."); }
/// <inheritdoc /> public void Save(IGraph graph, TextWriter output) { JToken data = (_context != null ? JsonLdProcessor.Compact(MakeExpandedForm(graph), _context, new JsonLdOptions()) : MakeExpandedForm(graph)); output.Write(data.ToString()); output.Flush(); }
public bool VerifyProof(VerifyProofOptions proofOptions) { var suite = suiteFactory.GetSuite(proofOptions.LdSuiteType) ?? throw new Exception($"Suite not found for type '{proofOptions.LdSuiteType}'"); var processorOptions = new JsonLdProcessorOptions { CompactToRelative = false, DocumentLoader = documentLoader.GetDocumentLoader() }; if (proofOptions.CompactProof) { proofOptions.Document = JsonLdProcessor.Compact( input: proofOptions.Document, context: Constants.SECURITY_CONTEXT_V2_URL, options: processorOptions); } var proof = (JObject)proofOptions.Document["proof"].DeepClone(); proof["@context"] = Constants.SECURITY_CONTEXT_V2_URL; proofOptions.Document.Remove("proof"); proofOptions.Proof = proof; return(suite.VerifyProof(proofOptions, processorOptions)); }
public static void Run() { var doc = JObject.Parse(_docJson); var frame = JObject.Parse(_frameJson); var opts = new JsonLdOptions(); var flattened = JsonLdProcessor.Frame(doc, frame, opts); Console.WriteLine(flattened); /* * * Output: * { * "@context": . . ., * "@graph": [ * { * "@id": "_:b0", * "@type": "Person", * "image": "http://manu.sporny.org/images/manu.png", * "name": "Manu Sporny", * "homepage": "http://manu.sporny.org/" * } * ] * } * */ }
/// <summary> /// Cryptographically signs the provided document by adding a `proof` section, /// based on the provided suite and proof purpose. /// </summary> /// <param name="document"></param> /// <param name="options"></param> /// <returns></returns> public static async Task <JToken> SignAsync(JToken document, ProofOptions options) { if (options.Purpose is null) { throw new Exception("Proof purpose is required."); } if (options.Suite is null) { throw new Exception("Suite is required."); } options.AdditonalData["originalDocument"] = document; var documentCopy = document.DeepClone(); documentCopy = options.CompactProof ? JsonLdProcessor.Compact(documentCopy, Constants.SECURITY_CONTEXT_V2_URL, options.GetProcessorOptions()) : document.DeepClone(); documentCopy.Remove("proof"); // create the new proof (suites MUST output a proof using the security-v2 // `@context`) options.Input = documentCopy; var proof = await options.Suite.CreateProofAsync(options); // TODO: Check compaction again proof.Proof.Remove("@context"); var result = proof.UpdatedDocument ?? document.DeepClone(); result["proof"] = proof.Proof; return(result); }
public JToken CreateProof(CreateProofOptions options, JsonLdProcessorOptions processorOptions) { if (!(options.VerificationMethod is Bls12381VerificationKey2020 verificationMethod)) { throw new Exception( $"Invalid verification method. " + $"Expected '{nameof(Bls12381VerificationKey2020)}'. " + $"Found '{options.VerificationMethod?.GetType().Name}'."); } // Prepare proof var compactedProof = JsonLdProcessor.Compact( input: new BbsBlsSignature2020 { Context = Constants.SECURITY_CONTEXT_V2_URL, TypeName = "https://w3c-ccg.github.io/ldp-bbs2020/context/v1#BbsBlsSignature2020" }, context: Constants.SECURITY_CONTEXT_V2_URL, options: processorOptions); var proof = new BbsBlsSignature2020(compactedProof) { Context = Constants.SECURITY_CONTEXT_V2_URL, VerificationMethod = options.VerificationMethod switch { VerificationMethodReference reference => (string)reference, VerificationMethod method => method.Id, _ => throw new Exception("Unknown VerificationMethod type") },
public static IEnumerable <VerificationMethod> FindVerificationMethods(DidDocument didDocument, string proofPurpose, IDocumentLoader documentLoader) { var processorOptions = new JsonLdProcessorOptions { DocumentLoader = documentLoader.Load }; processorOptions.ExpandContext = Constants.SECURITY_CONTEXT_V2_URL; var result = JsonLdProcessor.Frame( input: didDocument, frame: new JObject { { "@context", Constants.SECURITY_CONTEXT_V2_URL }, { "@explicit", true }, { proofPurpose, new JObject { { "@embed", "@always" } } } }, options: processorOptions); if (result[proofPurpose] == null || !(result[proofPurpose] is JArray purposes)) { throw new Exception($"No verification keys found for prupose `{proofPurpose}`"); } return(purposes.Select(x => new VerificationMethod(x as JObject)).ToList()); }
public JToken CreateProof(CreateProofOptions options) { if (options.VerificationMethod is null) { throw new Exception("Verification method is required."); } if (options.ProofPurpose is null) { throw new Exception("Proof purpose is required."); } if (options.LdSuiteType is null) { throw new Exception("Suite type is required."); } var suite = suiteFactory.GetSuite(options.LdSuiteType) ?? throw new Exception($"Suite not found for type '{options.LdSuiteType}'"); var processorOptions = new JsonLdProcessorOptions { CompactToRelative = false, DocumentLoader = documentLoader.GetDocumentLoader() }; if (options.CompactProof) { options.Document = JsonLdProcessor.Compact( input: options.Document, context: Constants.SECURITY_CONTEXT_V2_URL, options: processorOptions); } return(suite.CreateProof(options, processorOptions)); }
public Task <IEnumerable <KeyValuePair <Iri, IEnumerable <Statement> > > > Read(StreamReader streamReader) { if (streamReader == null) { throw new ArgumentNullException(nameof(streamReader)); } var defaultGraph = new TypePrioritizingStatementCollection(); var graphMap = new Dictionary <Iri, IEnumerable <Statement> >(); var dataset = (RDFDataset)JsonLdProcessor.ToRDF(JSONUtils.FromReader(streamReader)); foreach (var graphName in dataset.GraphNames()) { var graphIri = (graphName == "@default" ? null : (graphName.StartsWith("_:") ? new Iri() : new Iri(graphName))); IEnumerable <Statement> statements; if (graphIri == null) { statements = defaultGraph; } else if (!graphMap.TryGetValue(graphIri, out statements)) { graphMap[graphIri] = statements = new TypePrioritizingStatementCollection(); } var statementsCollection = (ICollection <Statement>)statements; foreach (var quad in dataset.GetQuads(graphName)) { statementsCollection.Add(quad.AsStatement()); } } return(Task.FromResult(new[] { new KeyValuePair <Iri, IEnumerable <Statement> >(null, defaultGraph) }.Concat(graphMap))); }
public static void Run() { var doc = JObject.Parse(_docJson); var context = JObject.Parse(_contextJson); var opts = new JsonLdOptions(); var flattened = JsonLdProcessor.Flatten(doc, context, opts); Console.WriteLine(flattened); /* * * Output: * { * "@context": . . ., * "@graph": [ * { * "@id": "_:b0", * "image": "http://manu.sporny.org/images/manu.png", * "name": "Manu Sporny", * "homepage": "http://manu.sporny.org/" * }, * { * "@id": "ld-experts", * "member": { * "@id": "_:b0" * }, * "name": "LD Experts" * } * ] * } * */ }
public static void Run() { var doc = JObject.Parse(_docJson); var remoteContext = JObject.Parse("{'@context':'http://example.org/context.jsonld'}"); var opts = new JsonLdOptions { documentLoader = new CustomDocumentLoader() }; var compacted = JsonLdProcessor.Compact(doc, remoteContext, opts); Console.WriteLine(compacted); /* * * Output: * { * "@id": "http://example.org/ld-experts", * "member": { * "@type": "Person", * "image": "http://manu.sporny.org/images/manu.png", * "name": "Manu Sporny", * "homepage": "http://manu.sporny.org/" * }, * "name": "LD Experts" * } * */ }
public void Load(IGraph g, TextReader input) { JToken json; using (JsonReader jsonReader = new JsonTextReader(input)) { json = JToken.Load(jsonReader); JArray flattened = (JArray)JsonLdProcessor.Flatten(json, new JsonLdOptions()); foreach (JObject subjectJObject in flattened) { string subject = subjectJObject["@id"].ToString(); JToken type; if (subjectJObject.TryGetValue("@type", out type)) { if (type is JArray) { foreach (JToken t in (JArray)type) { Assert(g, subject, "http://www.w3.org/1999/02/22-rdf-syntax-ns#type", new Uri(t.ToString()), null); } } else { Assert(g, subject, "http://www.w3.org/1999/02/22-rdf-syntax-ns#type", new Uri(type.ToString()), null); } } foreach (JProperty property in subjectJObject.Properties()) { if (property.Name == "@id" || property.Name == "@type") { continue; } foreach (JObject objectJObject in property.Value) { JToken id; JToken value; if (objectJObject.TryGetValue("@id", out id)) { Assert(g, subject, property.Name, new Uri(id.ToString()), null); } else if (objectJObject.TryGetValue("@value", out value)) { string datatype = null; JToken datatypeJToken; if (objectJObject.TryGetValue("@type", out datatypeJToken)) { datatype = datatypeJToken.ToString(); } Assert(g, subject, property.Name, value.ToString(), datatype); } } } } } }
public JToken CreateProof(CreateProofOptions options, JsonLdProcessorOptions processorOptions) { var(document, proofs) = options.Document.GetProofs(processorOptions); var proof = new BbsBlsSignature2020(proofs.FirstOrDefault() ?? throw new Exception("Proof not found")); proof.Context = Constants.SECURITY_CONTEXT_V2_URL; var signature = Convert.FromBase64String(proof.ProofValue); var derivedProof = JsonLdProcessor.Compact(new BbsBlsSignatureProof2020(), Constants.SECURITY_CONTEXT_V2_URL, processorOptions); var documentStatements = BbsBlsSignature2020Suite.CreateVerifyDocumentData(document, processorOptions); var proofStatements = BbsBlsSignature2020Suite.CreateVerifyProofData(proof, processorOptions); var transformedInputDocumentStatements = documentStatements.Select(TransformBlankNodeToId).ToArray(); var compactInputDocument = Helpers.FromRdf(transformedInputDocumentStatements); var revealDocument = JsonLdProcessor.Frame(compactInputDocument, options.ProofRequest, processorOptions); var revealDocumentStatements = BbsBlsSignature2020Suite.CreateVerifyDocumentData(revealDocument, processorOptions); var numberOfProofStatements = proofStatements.Count(); var proofRevealIndicies = EnumerableFromInt(numberOfProofStatements).ToArray(); var documentRevealIndicies = revealDocumentStatements.Select(x => Array.IndexOf(transformedInputDocumentStatements, x) + numberOfProofStatements).ToArray(); if (documentRevealIndicies.Count() != revealDocumentStatements.Count()) { throw new Exception("Some statements in the reveal document not found in original proof"); } var revealIndicies = proofRevealIndicies.Concat(documentRevealIndicies); derivedProof["nonce"] = options.Nonce ?? Guid.NewGuid().ToString(); //Combine all the input statements that //were originally signed to generate the proof var allInputStatements = proofStatements.Concat(documentStatements); var verificationMethod = BbsBlsSignature2020Suite.GetVerificationMethod(proofs.First(), processorOptions); var outputProof = BbsProvider.CreateProof(new CreateProofRequest( publicKey: verificationMethod.ToBlsKeyPair().GeyBbsKeyPair((uint)allInputStatements.Count()), messages: GetProofMessages(allInputStatements.ToArray(), revealIndicies).ToArray(), signature: signature, blindingFactor: null, nonce: derivedProof["nonce"].ToString())); // Set the proof value on the derived proof derivedProof["proofValue"] = Convert.ToBase64String(outputProof); // Set the relevant proof elements on the derived proof from the input proof derivedProof["verificationMethod"] = proof["verificationMethod"]; derivedProof["proofPurpose"] = proof["proofPurpose"]; derivedProof["created"] = proof["created"]; revealDocument["proof"] = derivedProof; return(revealDocument); }
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); }
/// <summary> /// Returns the <see cref="RDFDataset" /> from the REST API response. /// </summary> /// <param name="response">The REST API response.</param> /// <returns>The <see cref="RDFDataset"/> from the REST API response.</returns> protected override RDFDataset LoadEntity(IRestResponse response) { var token = JSONUtils.FromString(response.Content); model = (RDFDataset)JsonLdProcessor.ToRDF(token, options); defaultQuads = model.GetQuads("@default"); return(model); }
/// <summary> /// Deserializes the JSON-LD object into a typed model. /// </summary> /// <typeparam name="T">destination entity model</typeparam> /// <param name="jsonLd">a JSON-LD object</param> public T Deserialize <T>(JObject jsonLd) { var jsonLdContext = _contextProvider.GetContext(typeof(T)); if (jsonLdContext == null) { return(jsonLd.ToObject <T>(_jsonSerializer)); } return(JsonLdProcessor.Compact(jsonLd, jsonLdContext, new JsonLdOptions()).ToObject <T>(_jsonSerializer)); }
public static IGraph CreateGraph(JToken compacted) { JToken flattened = JsonLdProcessor.Flatten(compacted, new JsonLdOptions()); IRdfReader rdfReader = new JsonLdReader(); IGraph graph = new Graph(); rdfReader.Load(graph, new StringReader(flattened.ToString())); return(graph); }
/// <summary> /// Deserializes the NQuads into a typed model /// </summary> /// <typeparam name="T">destination entity model type</typeparam> /// <param name="nQuads">RDF data in NQuads.</param> public T Deserialize <T>(string nQuads) { var jsonLdObject = JsonLdProcessor.FromRDF(nQuads); var jsonLdContext = _contextProvider.GetContext(typeof(T)); if (jsonLdContext == null) { throw new ContextNotFoundException(typeof(T)); } return(JsonLdProcessor.Compact(jsonLdObject, jsonLdContext, new JsonLdOptions()).ToObject <T>(_jsonSerializer)); }
/// <summary> /// Fetches a JSON-LD document from a URL and, if necessary, compacts it to /// the security v2 context. /// </summary> /// <param name="document"></param> /// <param name="isRoot"></param> /// <param name="options"></param> /// <returns></returns> public static async Task <JObject> FetchInSecurityContextAsync(JToken document, bool isRoot = false, JsonLdProcessorOptions options = null) { await Task.Yield(); if (document.Type == JTokenType.Object && document["@context"]?.Value <string>() == Constants.SECURITY_CONTEXT_V2_URL && !isRoot) { return(document as JObject); } return(JsonLdProcessor.Compact(document, Constants.SECURITY_CONTEXT_V2_URL, options)); }
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); }
/// <summary> /// Deserializes the NQuads into a typed model /// </summary> /// <typeparam name="T">destination entity model type</typeparam> /// <param name="nQuads">RDF data in NQuads.</param> public T Deserialize <T>(string nQuads) { var jsonLd = JsonLdProcessor.FromRDF(nQuads); var context = this.contextResolver.GetContext(typeof(T)); var frame = this.frameProvider.GetFrame(typeof(T)); if (context == null) { throw new ContextNotFoundException(typeof(T)); } return(this.Deserialize <T>(jsonLd, context, frame)); }
private static void Example3() { var data = new Graph(); data.Assert("http://person.com#bob", "http://schema.com#employer", "http://person.com#acme"); data.Assert("http://person.com#bob", "http://schema.com#name", "http://person.com#bob/name"); data.Assert("http://person.com#bob/name", "http://schema.com#first", GraphObject.FromData("Bob")); data.Assert("http://person.com#bob/name", "http://schema.com#second", GraphObject.FromData("Dylan")); Console.WriteLine(JsonLdProcessor.Frame(new Context { Base = "http://schema.com#" }, data, "http://person.com#bob")); }
public void Should_serialize_URI_values_as_expanded_object() { // given var serialized = this.serializer.Serialize(new UriPropertyForcedToExpand { Property = new IriRef(UriValue) }); // when // to remove @context, an empty JObject can be passed var noContext = JsonLdProcessor.Compact(serialized, new JObject(), new JsonLdOptions()); // then Assert.That(noContext[PropertyUri]["@id"].ToString(), Is.EqualTo(UriValue)); }
public void Should_serialize_URI_values_as_strings() { // given var serialized = this.serializer.Serialize(new UriPropertyMappedToAbsoluteUri { Property = new Uri(UriValue) }); // when // to remove @context, an empty JObject can be passed var noContext = JsonLdProcessor.Compact(serialized, new JObject(), new JsonLdOptions()); // then Assert.That(noContext[PropertyUri].ToString(), Is.EqualTo(UriValue)); }
public void Should_serialize_URI_values_as_strings_with_context() { // given var serialized = this.serializer.Serialize(new UriPropertyWithContext { Property = new Uri(UriValue) }); // when // to remove @context, an empty JObject can be passed var noContext = JsonLdProcessor.Compact(serialized, new JObject(), new JsonLdOptions()); // then Assert.Equal(UriValue, noContext[PropertyUri]["@id"].ToString()); }
internal static void Run() { var serialized = Sample6_ToRDF.Run(); var opts = new JsonLdOptions(); var jsonld = JsonLdProcessor.FromRDF(serialized, opts); Console.WriteLine(jsonld); /* * * Output: * [ * { * "@id": "_:b0", * "http://schema.org/image": [ * { * "@id": "http://manu.sporny.org/images/manu.png" * } * ], * "http://schema.org/name": [ * { * "@value": "Manu Sporny" * } * ], * "http://schema.org/url": [ * { * "@id": "http://manu.sporny.org/" * } * ], * "@type": [ * "http://schema.org/Person" * ] * }, * { * "@id": "http://example.org/ld-experts", * "http://schema.org/member": [ * { * "@id": "_:b0" * } * ], * "http://schema.org/name": [ * { * "@value": "LD Experts" * } * ] * } * ] */ }
public void Save(IGraph g, TextWriter output) { JToken flattened = MakeExpandedForm(g); if (Frame == null) { output.Write(flattened); } else { JObject framed = JsonLdProcessor.Frame(flattened, Frame, new JsonLdOptions()); JObject compacted = JsonLdProcessor.Compact(framed, framed["@context"], new JsonLdOptions()); output.Write(compacted); } }