KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > hp > hpl > jena > shared > impl > PrefixMappingImpl


1 /*
2   (c) Copyright 2003, 2004, 2005 Hewlett-Packard Development Company, LP
3   [See end of file]
4   $Id: PrefixMappingImpl.java,v 1.22 2005/03/18 13:56:44 chris-dollin Exp $
5 */

6
7 package com.hp.hpl.jena.shared.impl;
8
9 import com.hp.hpl.jena.rdf.model.impl.Util;
10 import com.hp.hpl.jena.shared.*;
11 import com.hp.hpl.jena.util.CollectionFactory;
12
13 import java.util.*;
14 import org.apache.xerces.util.XMLChar;
15
16 /**
17     An implementation of PrefixMapping. The mappings are stored in a hash
18     prefixToURI, with the reverse lookup done with a linear search. This may need
19     improving but could get complicated. The test for a legal prefix is left to
20     xerces's XMLChar.isValidNCName() predicate.
21         
22     @author kers
23 */

24 public class PrefixMappingImpl implements PrefixMapping
25     {
26     protected Map prefixToURI;
27     protected Map URItoPrefix;
28     protected boolean locked;
29     
30     public PrefixMappingImpl()
31         { prefixToURI = CollectionFactory.createHashedMap();
32         URItoPrefix = CollectionFactory.createHashedMap(); }
33     
34     protected void set( String JavaDoc prefix, String JavaDoc uri )
35         { prefixToURI.put( prefix, uri );
36         URItoPrefix.put( uri, prefix ); }
37     
38     protected String JavaDoc get( String JavaDoc prefix )
39         { return (String JavaDoc) prefixToURI.get( prefix ); }
40            
41     public PrefixMapping lock()
42         {
43         locked = true;
44         return this;
45         }
46         
47     public PrefixMapping setNsPrefix( String JavaDoc prefix, String JavaDoc uri )
48         {
49         checkUnlocked();
50         checkLegal( prefix );
51         if (!prefix.equals( "" ))
52             { checkProper( uri );
53             /* removeExistingNonDefault( uri ); */ }
54         set( prefix, uri );
55         return this;
56         }
57     
58     public PrefixMapping removeNsPrefix( String JavaDoc prefix )
59         {
60         checkUnlocked();
61         String JavaDoc uri = (String JavaDoc) prefixToURI.remove( prefix );
62         regenerateReverseMapping();
63         return this;
64         }
65     
66     protected void regenerateReverseMapping()
67         {
68         URItoPrefix.clear();
69         Iterator it = prefixToURI.entrySet().iterator();
70         while (it.hasNext())
71             {
72             Map.Entry e = (Map.Entry) it.next();
73             URItoPrefix.put( e.getValue(), e.getKey() );
74             }
75         }
76         
77     protected void checkUnlocked()
78         { if (locked) throw new JenaLockedException( this ); }
79         
80     private void checkProper( String JavaDoc uri )
81         { // suppressed by popular demand. TODO consider optionality
82
// if (!isNiceURI( uri )) throw new NamespaceEndsWithNameCharException( uri );
83
}
84         
85     public static boolean isNiceURI( String JavaDoc uri )
86         {
87         if (uri.equals( "" )) return false;
88         char last = uri.charAt( uri.length() - 1 );
89         return Util.notNameChar( last );
90         }
91         
92     /**
93         Add the bindings of other to our own. We defer to the general case
94         because we have to ensure the URIs are checked.
95         
96         @param other the PrefixMapping whose bindings we are to add to this.
97     */

98     public PrefixMapping setNsPrefixes( PrefixMapping other )
99         { return setNsPrefixes( other.getNsPrefixMap() ); }
100     
101     /**
102          Answer this PrefixMapping after updating it with the <code>(p, u)</code>
103          mappings in <code>other</code> where neither <code>p</code> nor
104          <code>u</code> appear in this mapping.
105     */

106     public PrefixMapping withDefaultMappings( PrefixMapping other )
107         {
108         checkUnlocked();
109         Iterator it = other.getNsPrefixMap().entrySet().iterator();
110         while (it.hasNext())
111             {
112             Map.Entry e = (Map.Entry) it.next();
113             String JavaDoc prefix = (String JavaDoc) e.getKey(), uri = (String JavaDoc) e.getValue();
114             if (getNsPrefixURI( prefix ) == null && getNsURIPrefix( uri ) == null)
115                 setNsPrefix( prefix, uri );
116             }
117         return this;
118         }
119         
120     /**
121         Add the bindings in the prefixToURI to our own. This will fail with a ClassCastException
122         if any key or value is not a String; we make no guarantees about order or
123         completeness if this happens. It will fail with an IllegalPrefixException if
124         any prefix is illegal; similar provisos apply.
125         
126          @param other the Map whose bindings we are to add to this.
127     */

128     public PrefixMapping setNsPrefixes( Map other )
129         {
130         checkUnlocked();
131         Iterator it = other.entrySet().iterator();
132         while (it.hasNext())
133             {
134             Map.Entry e = (Map.Entry) it.next();
135             setNsPrefix( (String JavaDoc) e.getKey(), (String JavaDoc) e.getValue() );
136             }
137         return this;
138         }
139          
140     /**
141         Checks that a prefix is "legal" - it must be a valid XML NCName.
142     */

143     private void checkLegal( String JavaDoc prefix )
144         {
145         if (prefix.length() > 0 && !XMLChar.isValidNCName( prefix ))
146             throw new PrefixMapping.IllegalPrefixException( prefix );
147         }
148         
149     public String JavaDoc getNsPrefixURI( String JavaDoc prefix )
150         { return get( prefix ); }
151         
152     public Map getNsPrefixMap()
153         { return CollectionFactory.createHashedMap( prefixToURI ); }
154         
155     public String JavaDoc getNsURIPrefix( String JavaDoc uri )
156         {
157         return (String JavaDoc) URItoPrefix.get( uri );
158 // Map.Entry e = findMapping( uri, false );
159
// return e == null ? null : (String) e.getKey();
160
}
161         
162     /**
163         Expand a prefixed URI. There's an assumption that any URI of the form
164         Head:Tail is subject to mapping if Head is in the prefix mapping. So, if
165         someone takes it into their heads to define eg "http" or "ftp" we have problems.
166     */

167     public String JavaDoc expandPrefix( String JavaDoc prefixed )
168         {
169         int colon = prefixed.indexOf( ':' );
170         if (colon < 0)
171             return prefixed;
172         else
173             {
174             String JavaDoc prefix = prefixed.substring( 0, colon );
175             String JavaDoc uri = get( prefix );
176             return uri == null ? prefixed : uri + prefixed.substring( colon + 1 );
177             }
178         }
179         
180     /**
181         Answer a readable (we hope) representation of this prefix mapping.
182     */

183     public String JavaDoc toString()
184         { return "pm:" + prefixToURI; }
185         
186     /**
187         Answer the qname for <code>uri</code> which uses a prefix from this
188         mapping, or null if there isn't one.
189     <p>
190         Relies on <code>splitNamespace</code> to carve uri into namespace and
191         localname components; this ensures that the localname is legal and we just
192         have to (reverse-)lookup the namespace in the prefix table.
193         
194         @see com.hp.hpl.jena.shared.PrefixMapping#qnameFor(java.lang.String)
195      */

196     public String JavaDoc qnameFor( String JavaDoc uri )
197         {
198         int split = Util.splitNamespace( uri );
199         String JavaDoc ns = uri.substring( 0, split ), local = uri.substring( split );
200         if (local.equals( "" )) return null;
201         String JavaDoc prefix = (String JavaDoc) URItoPrefix.get( ns );
202         return prefix == null ? null : prefix + ":" + local;
203 // Map.Entry e = findMapping( ns, false );
204
// return e == null ? null : (String) e.getKey() + ":" + local;
205
}
206     
207     /**
208         Obsolete - use shortForm.
209         @see com.hp.hpl.jena.shared.PrefixMapping#usePrefix(java.lang.String)
210      */

211     public String JavaDoc usePrefix( String JavaDoc uri )
212         { return shortForm( uri ); }
213     
214     /**
215         Compress the URI using the prefix mapping. This version of the code looks
216         through all the maplets and checks each candidate prefix URI for being a
217         leading substring of the argument URI. There's probably a much more
218         efficient algorithm available, preprocessing the prefix strings into some
219         kind of search table, but for the moment we don't need it.
220     */

221     public String JavaDoc shortForm( String JavaDoc uri )
222         {
223         Map.Entry e = findMapping( uri, true );
224         return e == null ? uri : e.getKey() + ":" + uri.substring( ((String JavaDoc) e.getValue()).length() );
225         }
226         
227     /**
228         Answer a prefixToURI entry in which the value is an initial substring of <code>uri</code>.
229         If <code>partial</code> is false, then the value must equal <code>uri</code>.
230         
231         Does a linear search of the entire prefixToURI, so not terribly efficient for large maps.
232         
233         @param uri the value to search for
234         @param true if the match can be any leading substring, false for exact match
235         @return some entry (k, v) such that uri starts with v [equal for partial=false]
236     */

237     private Map.Entry findMapping( String JavaDoc uri, boolean partial )
238         {
239         Iterator it = prefixToURI.entrySet().iterator();
240         while (it.hasNext())
241             {
242             Map.Entry e = (Map.Entry) it.next();
243             String JavaDoc ss = (String JavaDoc) e.getValue();
244             if (uri.startsWith( ss ) && (partial || ss.length() == uri.length())) return e;
245             }
246         return null;
247         }
248
249     }
250
251
252 /*
253     (c) Copyright 2002, 2003, 2004, 2005 Hewlett-Packard Development Company, LP
254     All rights reserved.
255
256     Redistribution and use in source and binary forms, with or without
257     modification, are permitted provided that the following conditions
258     are met:
259
260     1. Redistributions of source code must retain the above copyright
261        notice, this list of conditions and the following disclaimer.
262
263     2. Redistributions in binary form must reproduce the above copyright
264        notice, this list of conditions and the following disclaimer in the
265        documentation and/or other materials provided with the distribution.
266
267     3. The name of the author may not be used to endorse or promote products
268        derived from this software without specific prior written permission.
269
270     THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
271     IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
272     OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
273     IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
274     INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
275     NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
276     DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
277     THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
278     (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
279     THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
280 */
Popular Tags