KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > hp > hpl > jena > rdf > model > impl > NTripleWriter


1 /*
2  * (c) Copyright 2001, 2002, 2003, 2004, 2005 Hewlett-Packard Development Company, LP
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  * notice, this list of conditions and the following disclaimer in the
12  * documentation and/or other materials provided with the distribution.
13  * 3. The name of the author may not be used to endorse or promote products
14  * derived from this software without specific prior written permission.
15
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  *
27  * $Id: NTripleWriter.java,v 1.18 2005/02/21 12:14:46 andy_seaborne Exp $
28  */

29
30 package com.hp.hpl.jena.rdf.model.impl;
31
32 import com.hp.hpl.jena.rdf.model.*;
33 import com.hp.hpl.jena.util.FileUtils;
34 import com.hp.hpl.jena.shared.*;
35
36 import java.io.*;
37
38 import org.apache.commons.logging.Log;
39 import org.apache.commons.logging.LogFactory;
40
41 /** Writes out an XML serialization of a model.
42  *
43  * @author bwm
44  * @version Release='$Name: $' Revision='$Revision: 1.18 $' Date='$Date: 2005/02/21 12:14:46 $'
45  */

46 public class NTripleWriter extends Object JavaDoc implements RDFWriter {
47
48     RDFErrorHandler errorHandler = new RDFDefaultErrorHandler();
49
50     protected static Log logger = LogFactory.getLog( NTripleWriter.class );
51     
52     public NTripleWriter() {
53     }
54     public void write(Model model, OutputStream out, String JavaDoc base)
55          {
56         try {
57             Writer w;
58             try {
59                 w = new OutputStreamWriter(out, "ascii");
60             } catch (UnsupportedEncodingException e) {
61                 logger.warn( "ASCII is not supported: in NTripleWriter.write", e );
62                 w = FileUtils.asUTF8(out);
63             }
64             write(model, w, base);
65             w.flush();
66
67         } catch (Exception JavaDoc ioe) {
68             errorHandler.error(ioe);
69         }
70     }
71     public void write(Model baseModel, Writer writer, String JavaDoc base)
72          {
73         try {
74             Model model = ModelFactory.withHiddenStatements(baseModel);
75             PrintWriter pw;
76             if (writer instanceof PrintWriter) {
77                 pw = (PrintWriter) writer;
78             } else {
79                 pw = new PrintWriter(writer);
80             }
81
82             StmtIterator iter = model.listStatements();
83             Statement stmt = null;
84
85             while (iter.hasNext()) {
86                 stmt = iter.nextStatement();
87                 writeResource(stmt.getSubject(), pw);
88                 pw.print(" ");
89                 writeResource(stmt.getPredicate(), pw);
90                 pw.print(" ");
91                 writeNode(stmt.getObject(), pw);
92                 pw.println(" .");
93             }
94             pw.flush();
95         } catch (Exception JavaDoc e) {
96             errorHandler.error(e);
97         }
98     }
99
100     /** Set a property to control the writer's behaviour.
101      *
102      * <p>This writer currently recognises no properties. Invoking this
103      * method always causes an <CODE>UnknownPropertyException</CODE>
104      * to be raised.</p>?
105      * @param propName The name of the property to be set
106      * @param propValue The new value of the property
107      * @return the previous value of the property
108      */

109     public Object JavaDoc setProperty(String JavaDoc propName, Object JavaDoc propValue) {
110         throw new UnknownPropertyException( propName );
111     }
112
113     public void setNsPrefix(String JavaDoc prefix, String JavaDoc ns) {
114     }
115     
116     public String JavaDoc getPrefixFor( String JavaDoc uri )
117         { return null; }
118
119     public RDFErrorHandler setErrorHandler(RDFErrorHandler errHandler) {
120         RDFErrorHandler old = this.errorHandler;
121         this.errorHandler = errHandler;
122         return old;
123     }
124
125     public static void write(Model model, PrintWriter writer)
126         throws java.io.IOException JavaDoc {
127         StmtIterator iter = model.listStatements();
128         Statement stmt = null;
129
130         while (iter.hasNext()) {
131             stmt = iter.nextStatement();
132             writeResource(stmt.getSubject(), writer);
133             writer.print(" ");
134             writeResource(stmt.getPredicate(), writer);
135             writer.print(" ");
136             writeNode(stmt.getObject(), writer);
137             writer.println(" .");
138         }
139     }
140
141     protected static void writeResource(Resource r, PrintWriter writer)
142          {
143         if (r.isAnon()) {
144             writer.print(anonName(r.getId()));
145         } else {
146             writer.print("<");
147             writeURIString(r.getURI(), writer);
148             writer.print(">");
149         }
150     }
151     static private boolean okURIChars[] = new boolean[128];
152     static {
153         for (int i = 32; i < 127; i++)
154             okURIChars[i] = true;
155         okURIChars['<'] = false;
156         okURIChars['>'] = false;
157         okURIChars['\\'] = false;
158
159     }
160     private static void writeURIString(String JavaDoc s, PrintWriter writer) {
161
162         for (int i = 0; i < s.length(); i++) {
163             char c = s.charAt(i);
164             if (c < okURIChars.length && okURIChars[c]) {
165                 writer.print(c);
166             } else {
167                 String JavaDoc hexstr = Integer.toHexString(c).toUpperCase();
168                 int pad = 4 - hexstr.length();
169                 writer.print("\\u");
170                 for (; pad > 0; pad--)
171                     writer.print("0");
172                 writer.print(hexstr);
173             }
174         }
175     }
176     private static void writeString(String JavaDoc s, PrintWriter writer) {
177
178         for (int i = 0; i < s.length(); i++) {
179             char c = s.charAt(i);
180             if (c == '\\' || c == '"') {
181                 writer.print('\\');
182                 writer.print(c);
183             } else if (c == '\n') {
184                 writer.print("\\n");
185             } else if (c == '\r') {
186                 writer.print("\\r");
187             } else if (c == '\t') {
188                 writer.print("\\t");
189             } else if (c >= 32 && c < 127) {
190                 writer.print(c);
191             } else {
192                 String JavaDoc hexstr = Integer.toHexString(c).toUpperCase();
193                 int pad = 4 - hexstr.length();
194                 writer.print("\\u");
195                 for (; pad > 0; pad--)
196                     writer.print("0");
197                 writer.print(hexstr);
198             }
199         }
200     }
201     protected static void writeLiteral(Literal l, PrintWriter writer) {
202         String JavaDoc s = l.getString();
203         /*
204         if (l.getWellFormed())
205             writer.print("xml");
206         */

207         writer.print('"');
208         writeString(s, writer);
209         writer.print('"');
210         String JavaDoc lang = l.getLanguage();
211         if (lang != null && !lang.equals(""))
212             writer.print("@" + lang);
213         String JavaDoc dt = l.getDatatypeURI();
214         if (dt != null && !dt.equals(""))
215             writer.print("^^<" + dt + ">");
216     }
217
218     protected static void writeNode(RDFNode n, PrintWriter writer)
219          {
220         if (n instanceof Literal) {
221             writeLiteral((Literal) n, writer);
222         } else {
223             writeResource((Resource) n, writer);
224         }
225     }
226
227     protected static String JavaDoc anonName(AnonId id) {
228         String JavaDoc name = "_:A";
229         String JavaDoc sid = id.toString();
230         for (int i = 0; i < sid.length(); i++) {
231             char c = sid.charAt(i);
232             if (c == 'X') {
233                 name = name + "XX";
234             } else if (Character.isLetterOrDigit(c)) {
235                 name = name + c;
236             } else {
237                 name = name + "X" + Integer.toHexString((int) c) + "X";
238             }
239         }
240         return name;
241     }
242 }
243
Popular Tags