1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 package net.sumaris.rdf.util;
24
25 import de.uni_stuttgart.vis.vowl.owl2vowl.Owl2Vowl;
26 import net.sumaris.core.exception.SumarisTechnicalException;
27 import net.sumaris.core.util.StringUtils;
28 import org.apache.jena.rdf.model.Model;
29
30 import java.io.ByteArrayInputStream;
31 import java.io.ByteArrayOutputStream;
32 import java.io.IOException;
33
34 public class ModelUtils {
35
36 protected ModelUtils() {
37
38 }
39
40
41 public static String toJenaOutputFormat(String userFormat) {
42 if (StringUtils.isBlank(userFormat)) {
43 return "RDF/XML";
44 }
45
46 switch(userFormat.toLowerCase()) {
47 case "rdf":
48 return "RDF/XML";
49 case "json":
50 return "RDF/JSON";
51 case "n3":
52 return "N3";
53 case "trig":
54 return "TriG";
55 case "trix":
56 return "TriX";
57 case "jsonld":
58 case "json-ld":
59 return "JSON-LD";
60 case "ttl":
61 return "TURTLE";
62 default:
63 return userFormat.toUpperCase();
64 }
65 }
66
67
68
69
70
71
72
73
74 public static String modelToString(Model model, String format) {
75
76 format = toJenaOutputFormat(format);
77
78
79 if ("VOWL".equalsIgnoreCase(format)) {
80 try (
81 ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
82 ) {
83 model.write(bos);
84 bos.flush();
85
86 return new Owl2Vowl(new ByteArrayInputStream(bos.toByteArray())).getJsonAsString();
87 } catch (Exception e) {
88 throw new SumarisTechnicalException("Error converting model into VOWL", e);
89 }
90 }
91
92
93 else {
94 try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) {
95 if (format == null) {
96 model.write(os);
97 } else {
98 model.write(os, format);
99 }
100 os.flush();
101 os.close();
102 return new String(os.toByteArray(), "UTF8");
103 } catch (IOException e) {
104 throw new SumarisTechnicalException("Unable to serialize model to string: " + e.getMessage(), e);
105 }
106 }
107 }
108 }