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).disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET)
52                      .enable(JsonGenerator.Feature.FLUSH_PASSED_TO_STREAM).setPrettyPrinter(new DefaultPrettyPrinter());
53          } catch (IOException ex) {
54          }
55      }
56  
57      private void start(boolean throwIfStarted) throws TripleHandlerException {
58          if (documentStarted) {
59              if (throwIfStarted) {
60                  throw new IllegalStateException("Document already started.");
61              }
62              return;
63          }
64          documentStarted = true;
65          try {
66              ps.writeStartObject();
67              ps.writeFieldName("quads");
68              ps.writeStartArray();
69          } catch (IOException ex) {
70              throw new TripleHandlerException("IO Error while starting document.", ex);
71          }
72      }
73  
74      @Override
75      public void startDocument(IRI documentIRI) throws TripleHandlerException {
76          start(true);
77      }
78  
79      @Override
80      public void writeTriple(Resource s, IRI p, Value o, Resource g) throws TripleHandlerException {
81          start(false);
82          try {
83              ps.writeStartArray();
84  
85              if (s instanceof IRI) {
86                  printExplicitIRI(s.stringValue());
87              } else {
88                  printBNode(s.stringValue());
89              }
90  
91              printIRI(p.stringValue());
92  
93              if (o instanceof IRI) {
94                  printExplicitIRI(o.stringValue());
95              } else if (o instanceof BNode) {
96                  printBNode(o.stringValue());
97              } else {
98                  printLiteral((Literal) o);
99              }
100 
101             printIRI(g == null ? null : g.stringValue());
102 
103             ps.writeEndArray();
104         } catch (IOException ex) {
105             throw new TripleHandlerException("IO Error while writing triple", ex);
106         }
107     }
108 
109     @Override
110     public void writeNamespace(String prefix, String uri) throws TripleHandlerException {
111         // Empty.
112     }
113 
114     @Override
115     public void endDocument(IRI documentIRI) throws TripleHandlerException {
116         validateDocumentStarted();
117     }
118 
119     @Override
120     public void close() throws TripleHandlerException {
121         start(false);
122 
123         try {
124             ps.writeEndArray();
125             ps.writeEndObject();
126             ps.close();
127         } catch (IOException ex) {
128             throw new TripleHandlerException("IO Error while closing document.", ex);
129         } finally {
130             ps = null;
131         }
132     }
133 
134     private void validateDocumentStarted() {
135         if (!documentStarted) {
136             throw new IllegalStateException("Document didn't start.");
137         }
138     }
139 
140     private void printIRI(String uri) throws IOException {
141         printValue(uri);
142     }
143 
144     private void printExplicitIRI(String uri) throws IOException {
145         printValue("uri", uri);
146     }
147 
148     private void printBNode(String bnode) throws IOException {
149         printValue("bnode", bnode);
150     }
151 
152     private void printLiteral(Literal literal) throws IOException {
153         ps.writeStartObject();
154         ps.writeStringField("type", "literal");
155         ps.writeStringField("value", literal.stringValue());
156 
157         final Optional<String> language = literal.getLanguage();
158         ps.writeStringField("lang", language.isPresent() ? literal.getLanguage().get() : null);
159 
160         final IRI datatype = literal.getDatatype();
161         ps.writeStringField("datatype", datatype != null ? datatype.stringValue() : null);
162         ps.writeEndObject();
163     }
164 
165     private void printValue(String type, String value) throws IOException {
166         ps.writeStartObject();
167         ps.writeStringField("type", type);
168         ps.writeStringField("value", value);
169         ps.writeEndObject();
170     }
171 
172     private void printValue(String value) throws IOException {
173         ps.writeString(value);
174     }
175 
176     @Override
177     public boolean isAnnotated() {
178         return false; // TODO: add annotation support.
179     }
180 
181     @Override
182     public void setAnnotated(boolean f) {
183         // Empty.
184     }
185 }