Debian Codegraph @

rdfwriter/rdfwriter.go

raw symbols SCIP
1 package rdfwriter
2
3 import (
4 "fmt"
5 "github.com/spdx/gordf/rdfloader/parser"
6 "github.com/spdx/gordf/uri"
7 "io"
8 "strings"
9 )
10
11 // returns the triples that matches the input subject, object and the predicate.
12 // reason behind using string pointers is that it allows the user to pass a nil
13 // if the user is unsure about the other types.
14 // For example, if the user wants all the triples with subject rdf:about, the
15 // user can call FilterTriples(triples, &rdfAboutString, nil, nil)
16 // where, rdfAboutString := "rdf:about"
17 func FilterTriples(triples []*parser.Triple, subject, predicate, object *string) (result []*parser.Triple) {
18 for _, triple := range triples {
19 if (subject == nil || *subject == triple.Subject.ID) && (predicate == nil || *predicate == triple.Predicate.ID) && (object == nil || *object == triple.Object.ID) {
20 result = append(result, triple)
21 }
22 }
23 return
24 }
25
26 // returns the string form of the root tag with all the uri definitions
27 func getRootTagFromSchemaDefinition(schemaDefinition map[string]uri.URIRef, tab string) string {
28 rootTag := "<rdf:RDF\n"
29 for tag := range schemaDefinition {
30 tagURI := schemaDefinition[tag]
31 if tag == "" {
32 rootTag += tab + fmt.Sprintf(`%s="%s"`, "xmlns", tagURI.String()) + "\n"
33 } else {
34 rootTag += tab + fmt.Sprintf(`%s:%s="%s"`, "xmlns", tag, tagURI.String()) + "\n"
35 }
36 }
37 rootTag = rootTag[:len(rootTag)-1] // removing the last \n char.
38 rootTag += ">"
39 return rootTag
40 }
41
42 // returns the string form of the opening and closing tag from the given triples.
43 func getOpeningAndClosingTags(triples []*parser.Triple, rdfNSAbbrev string, invSchemaDefinition map[string]string, tabs string, node *parser.Node) (openingTag string, closingTag string, err error) {
44 rdfTypeURI := parser.RDFNS + "type"
45 rdfNodeIDURI := parser.RDFNS + "nodeID"
46
47 openingTagFormat := "<%s%s%s>"
48 closingTagFormat := "</%s>"
49 // taking example of the following tag:
50 // <spdx:name rdf:nodeID="ID" rdf:about="https://sample.com#name">Apache License 2.0</spdx:name>
51 // Description of the %s used in the openingTagFormat
52 // 1st %s: node's name and schemaName
53 // spdx:name in case of the example
54 // 2nd %s: nodeId attribute
55 // rdf:nodeID="ID" for the given example
56 // 3rd %s: rdf:about property
57 // rdf:about="https://sample.com#name" for the given example
58 // NOTE: 2nd and 3rd %s can be given in any order. won't affect the semantics of the output.
59 // Description of the %s used in the closingTagFormat:
60 // 1st %s: same as first %s of openingTagFormat
61
62 rdfTypeTriples := FilterTriples(triples, nil, &rdfTypeURI, nil)
63 if n := len(rdfTypeTriples); n != 1 {
64 return openingTag, closingTag, fmt.Errorf("every subject node must be associated with exactly 1 triple of type rdf:type predicate. Found %v triples", n)
65 }
66 rdfnodeIDTriples := FilterTriples(triples, nil, &rdfNodeIDURI, nil)
67 if n := len(rdfnodeIDTriples); n > 1 {
68 return openingTag, closingTag, fmt.Errorf("there must be atmost nodeID attribute. found %v nodeID attributes", n)
69 }
70
71 rdfNodeID := ""
72 if len(rdfnodeIDTriples) == 1 {
73 rdfNodeID = fmt.Sprintf(` %s:nodeID="%s"`, rdfNSAbbrev, rdfnodeIDTriples[0].Object.ID)
74 }
75 rdfAbout := ""
76 if node.NodeType == parser.IRI {
77 rdfAbout = fmt.Sprintf(` %s:about="%s"`, rdfNSAbbrev, node.ID)
78 }
79
80 tagName, err := shortenURI(rdfTypeTriples[0].Object.ID, invSchemaDefinition)
81 if err != nil {
82 return openingTag, closingTag, err
83 }
84
85 openingTag = tabs + fmt.Sprintf(openingTagFormat, tagName, rdfNodeID, rdfAbout)
86 closingTag = tabs + fmt.Sprintf(closingTagFormat, tagName)
87 return openingTag, closingTag, nil
88 }
89
90 // returns the string equivalent of the triples associated with the given node in rdf/xml format.
91 func stringify(node *parser.Node, nodeToTriples map[string][]*parser.Triple, invSchemaDefinition map[string]string, depth int, tab string) (output string, err error) {
92 // Any rdf/xml tag is formed of OpeningTag, childrenString, ClosingTag
93 var openingTag, childrenString, closingTag string
94
95 tabs := strings.Repeat(tab, depth)
96
97 // getting the abbreviation used for rdf namespace.
98 rdfNSAbbrev := getRDFNSAbbreviation(invSchemaDefinition)
99
100 openingTag, closingTag, err = getOpeningAndClosingTags(nodeToTriples[node.String()], rdfNSAbbrev, invSchemaDefinition, tabs, node)
101 if err != nil {
102 return
103 }
104
105 // getting rest of the triples after rdf attributes are parsed
106 restTriples := getRestTriples(nodeToTriples[node.String()])
107
108 depth++ // we'll be parsing one level deep now.
109 tabs += tab // or strings.Repeat(tab, depth)
110 for _, triple := range restTriples {
111 predicateURI, err := shortenURI(triple.Predicate.ID, invSchemaDefinition)
112 if err != nil {
113 return "", err
114 }
115
116 if triple.Object.NodeType == parser.RESOURCELITERAL {
117 childrenString += tabs + fmt.Sprintf(`<%s %s:resource="%s"/>`, predicateURI, rdfNSAbbrev, triple.Object.ID) + "\n"
118 continue
119 }
120
121 var childString string
122 // adding opening tag to the child tag:
123 childString += tabs + fmt.Sprintf("<%s>", predicateURI) + "\n"
124 if len(nodeToTriples[triple.Object.String()]) == 0 {
125 // the tag ends here and doesn't have any further childs.
126 // object is even one level deep
127 // number of tabs increases.
128 childString += strings.Repeat(tab, depth+1) + triple.Object.ID
129 } else {
130 // we have a sub-child which is not a literal type. it can be a blank or a IRI node.
131 temp, err := stringify(triple.Object, nodeToTriples, invSchemaDefinition, depth+1, tab)
132 if err != nil {
133 return "", err
134 }
135 childString += temp
136 }
137 // adding the closing tag
138 childString += "\n" + tabs + fmt.Sprintf("</%s>", predicateURI)
139 childrenString += childString + "\n"
140 }
141 childrenString = strings.TrimSuffix(childrenString, "\n")
142 return fmt.Sprintf("%s\n%v\n%s", openingTag, childrenString, closingTag), nil
143 }
144
145 // function provided to the user for converting triples to string.
146 // Arg Description:
147 // triples: list of triples of a rdf graph
148 // schemaDefinition: maps the prefix given by xmlns to the URI
149 // tab: tab character to be used in the output. It can be four-spaces,
150 // two-spaces, single tab character, double tab character, etc
151 // depending upon the choice of the user.
152 func TriplesToString(triples []*parser.Triple, schemaDefinition map[string]uri.URIRef, tab string) (outputString string, err error) {
153 // linearly ordering the triples in a non-increasing order of depth.
154 sortedTriples, err := TopologicalSortTriples(triples)
155 if err != nil {
156 return outputString, err
157 }
158
159 invSchemaDefinition := invertSchemaDefinition(schemaDefinition)
160 nodeToTriples := GetNodeToTriples(sortedTriples)
161 rootTags := GetRootNodes(sortedTriples)
162
163 // now, we can iterate over all the root-nodes and generate the string representation of the nodes.
164 for _, tag := range rootTags {
165 currString, err := stringify(tag, nodeToTriples, invSchemaDefinition, 1, tab)
166 if err != nil {
167 return outputString, err
168 }
169 outputString += currString + "\n"
170 }
171 rootTagString := getRootTagFromSchemaDefinition(schemaDefinition, tab)
172 rootEndTag := "</rdf:RDF>"
173 return fmt.Sprintf("%s\n%s%s", rootTagString, outputString, rootEndTag), nil
174 }
175
176 // converts the input triples to string and writes it to the file.
177 // Args Description:
178 // w: writer in which the output data will be written.
179 // rest all params are same as that of the TriplesToString function.
180 func WriteToFile(w io.Writer, triples []*parser.Triple, schemaDefinition map[string]uri.URIRef, tab string) error {
181 opString, err := TriplesToString(triples, schemaDefinition, tab)
182 if err != nil {
183 return err
184 }
185 _, err = fmt.Fprint(w, opString)
186 return err
187 }