View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *  http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.any23.writer;
18  
19  import com.fasterxml.jackson.core.JsonFactory;
20  import com.fasterxml.jackson.core.JsonGenerator;
21  import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
22  import java.io.IOException;
23  import java.io.OutputStream;
24  import java.util.Optional;
25  
26  import org.eclipse.rdf4j.model.BNode;
27  import org.eclipse.rdf4j.model.IRI;
28  import org.eclipse.rdf4j.model.Literal;
29  import org.eclipse.rdf4j.model.Resource;
30  import org.eclipse.rdf4j.model.Value;
31  
32  /**
33   * Implementation of <i>JSON</i> {@link TripleWriter}.
34   *
35   * @author Michele Mostarda (mostarda@fbk.eu)
36   *
37   * @deprecated since 2.3. Use {@link JSONLDWriter} instead.
38   */
39  @Deprecated
40  public class JSONWriter extends TripleWriterHandler implements FormatWriter {
41  
42      private JsonGenerator ps;
43      private boolean documentStarted = false;
44  
45      public JSONWriter(OutputStream os) {
46          if (os == null) {
47              throw new NullPointerException("Output stream cannot be null.");
48          }
49          JsonFactory factory = new JsonFactory();
50          try {
51              this.ps = factory.createGenerator(os)
52                      .disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET)
53                      .enable(JsonGenerator.Feature.FLUSH_PASSED_TO_STREAM)
54                      .setPrettyPrinter(new DefaultPrettyPrinter());
55          } catch (IOException ex) {
56          }
57      }
58  
59      private void start(boolean throwIfStarted) throws TripleHandlerException {
60          if (documentStarted) {
61              if (throwIfStarted) {
62                  throw new IllegalStateException("Document already started.");
63              }
64              return;
65          }
66          documentStarted = true;
67          try {
68              ps.writeStartObject();
69              ps.writeFieldName("quads");
70              ps.writeStartArray();
71          } catch (IOException ex) {
72              throw new TripleHandlerException("IO Error while starting document.", ex);
73          }
74      }
75  
76      @Override
77      public void startDocument(IRI documentIRI) throws TripleHandlerException {
78          start(true);
79      }
80  
81      @Override
82      public void writeTriple(Resource s, IRI p, Value o, Resource g)
83              throws TripleHandlerException {
84          start(false);
85          try {
86              ps.writeStartArray();
87  
88              if (s instanceof IRI) {
89                  printExplicitIRI(s.stringValue());
90              } else {
91                  printBNode(s.stringValue());
92              }
93  
94              printIRI(p.stringValue());
95  
96              if (o instanceof IRI) {
97                  printExplicitIRI(o.stringValue());
98              } else if (o instanceof BNode) {
99                  printBNode(o.stringValue());
100             } else {
101                 printLiteral((Literal) o);
102             }
103 
104             printIRI(g == null ? null : g.stringValue());
105 
106             ps.writeEndArray();
107         } catch (IOException ex) {
108             throw new TripleHandlerException("IO Error while writing triple", ex);
109         }
110     }
111 
112     @Override
113     public void writeNamespace(String prefix, String uri)
114             throws TripleHandlerException {
115         // Empty.
116     }
117 
118     @Override
119     public void endDocument(IRI documentIRI) throws TripleHandlerException {
120         validateDocumentStarted();
121     }
122 
123     @Override
124     public void close() throws TripleHandlerException {
125         start(false);
126 
127         try {
128             ps.writeEndArray();
129             ps.writeEndObject();
130             ps.close();
131         } catch (IOException ex) {
132             throw new TripleHandlerException("IO Error while closing document.", ex);
133         } finally {
134             ps = null;
135         }
136     }
137 
138     private void validateDocumentStarted() {
139         if (!documentStarted) {
140             throw new IllegalStateException("Document didn't start.");
141         }
142     }
143 
144     private void printIRI(String uri) throws IOException {
145         printValue(uri);
146     }
147 
148     private void printExplicitIRI(String uri) throws IOException {
149         printValue("uri", uri);
150     }
151 
152     private void printBNode(String bnode) throws IOException {
153         printValue("bnode", bnode);
154     }
155 
156     private void printLiteral(Literal literal) throws IOException {
157         ps.writeStartObject();
158         ps.writeStringField("type", "literal");
159         ps.writeStringField("value", literal.stringValue());
160 
161         final Optional<String> language = literal.getLanguage();
162         ps.writeStringField("lang", language.isPresent() ? literal.getLanguage().get() : null);
163 
164         final IRI datatype = literal.getDatatype();
165         ps.writeStringField("datatype", datatype != null ? datatype.stringValue() : null);
166         ps.writeEndObject();
167     }
168 
169     private void printValue(String type, String value) throws IOException {
170         ps.writeStartObject();
171         ps.writeStringField("type", type);
172         ps.writeStringField("value", value);
173         ps.writeEndObject();
174     }
175 
176     private void printValue(String value) throws IOException {
177         ps.writeString(value);
178     }
179 
180     @Override
181     public boolean isAnnotated() {
182         return false; // TODO: add annotation support.
183     }
184 
185     @Override
186     public void setAnnotated(boolean f) {
187         // Empty.
188     }
189 }