KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > hp > hpl > jena > graph > impl > FileGraphMaker


1 /*
2   (c) Copyright 2003, 2004, 2005 Hewlett-Packard Development Company, LP
3   [See end of file]
4   $Id: FileGraphMaker.java,v 1.22 2005/04/10 12:45:47 chris-dollin Exp $
5 */

6
7 package com.hp.hpl.jena.graph.impl;
8
9 import com.hp.hpl.jena.graph.*;
10
11 import java.io.*;
12 import java.util.*;
13
14 import com.hp.hpl.jena.shared.*;
15 import com.hp.hpl.jena.util.CollectionFactory;
16 import com.hp.hpl.jena.util.iterator.*;
17 import com.hp.hpl.jena.vocabulary.*;
18
19 /**
20     A FileGraph factory, making FileGraphs based round some supplied
21     directory. We have to keep track of created files ourselves, because a
22     FileGraph that has been created but not closed is not visible in the
23     filing system. (This might count as a bug at some point.)
24     
25     @author hedgehog
26 */

27 public class FileGraphMaker extends BaseGraphMaker
28     {
29     private String JavaDoc fileBase;
30     private boolean deleteOnClose;
31     private Map created = CollectionFactory.createHashedMap();
32     
33     /**
34         Construct a file graph factory whose files will appear in root. The reifier
35         style is Minimal and the files will be retained when the maker is closed.
36         
37         @param root the directory to keep the files in.
38      */

39     public FileGraphMaker( String JavaDoc root )
40         { this( root, ReificationStyle.Minimal ); }
41         
42     /**
43         Construct a file graph factory whose files will appear in root. The files
44         will be retained when the maker is closed.
45     
46         @param root the directory to keep the files in.
47         @param style the reification style of the resulting graph
48      */

49     public FileGraphMaker( String JavaDoc root, ReificationStyle style )
50         { this( root, style, false ); }
51  
52     /**
53         Construct a file graph factory whose files will appear in root.
54         If deleteOnClose is true, the files created by this factory will be deleted
55         when the factory is closed.
56         
57         @param root the directory to keep the files in
58         @param style the reification style of the graph
59         @param deleteOnClose iff true, delete created files on close
60      */

61     public FileGraphMaker( String JavaDoc root, ReificationStyle style, boolean deleteOnClose )
62         {
63         super( style );
64         this.fileBase = root;
65         this.deleteOnClose = deleteOnClose;
66         }
67
68     /**
69         Answer the RDFS class of a FileGraphMaker
70         @return JenaModelSpec.FileMakerClass [node version]
71     */

72     public Node getMakerClass()
73         { return JenaModelSpec.FileMakerSpec.asNode(); }
74
75     /**
76         Answer the fileBase of all the graphs created by this FileGraphMaker.
77         @return the fileBase of this Maker
78     */

79     public String JavaDoc getFileBase()
80         { return fileBase; }
81         
82     protected void augmentDescription( Graph g, Node self )
83         { g.add( Triple.create( self, JenaModelSpec.fileBase.asNode(), Node.createLiteral( fileBase, "", false ) ) ); }
84                 
85     /**
86         Answer a new, anonynous FileGraph. See FileGraph.create().
87         @return a new anonymous FileGraph
88     */

89     public Graph createGraph()
90         { return FileGraph.create(); }
91         
92     public Graph createGraph( String JavaDoc name, boolean strict )
93         {
94         File f = withRoot( name );
95         FileGraph already = (FileGraph) created.get( f );
96         if (already == null)
97             return remember( f, new FileGraph( f, true, strict, style ) );
98         else
99             {
100             if (strict) throw new AlreadyExistsException( name );
101             else return already.openAgain();
102             }
103         }
104
105     public Graph openGraph( String JavaDoc name, boolean strict )
106         {
107         File f = withRoot( name );
108         return created.containsKey( f )
109             ? ((FileGraph) created.get( f )).openAgain()
110             : remember( f, new FileGraph( f, false, strict, style ) )
111             ;
112         }
113
114     private File withRoot( String JavaDoc name )
115         { return new File( fileBase, toFilename( name ) ); }
116         
117     /**
118         Make <code>name</name> into a "safe" filename. "safe" is a bit weak
119         here; we want to allow URIs as graph names and assume that our filing
120         systems will be reasonably liberal. We'll see ...
121         
122         @param name
123         @return name with underbar, slash, and colon escaped as _U, _S, _C
124      */

125     public static String JavaDoc toFilename( String JavaDoc name )
126         {
127         return replaceBy( name, "_/:", "USC" );
128 // Jave 1.4 please!
129
// return name
130
// .replaceAll( "_", "_U" )
131
// .replaceAll( "/", "_S" )
132
// .replaceAll( ":", "_C" )
133
// ;
134
}
135         
136     private static String JavaDoc replaceBy( String JavaDoc x, String JavaDoc from, String JavaDoc to )
137         {
138         int len = x.length();
139         StringBuffer JavaDoc result = new StringBuffer JavaDoc( len + 10 );
140         for (int i = 0; i < len; i += 1)
141             {
142             char ch = x.charAt( i );
143             int where = from.indexOf( ch );
144             if (where < 0) result.append( ch );
145             else result.append( '_' ).append( to.charAt( where ) );
146             }
147         return result.toString();
148         }
149
150     /**
151         Answer the graphname corresponding to the given filename, undoing the
152         conversion done by toFilename.
153         
154         @param fileName a filename, possible containing _U, _C, and _S escapes
155         @return the unescaped name
156      */

157     public static String JavaDoc toGraphname( String JavaDoc fileName )
158         {
159         StringBuffer JavaDoc result = new StringBuffer JavaDoc( fileName.length() );
160         int here = 0;
161         while (true)
162             {
163             int ubar = fileName.indexOf( '_', here );
164             if (ubar < 0) break;
165             result.append( fileName.substring( here, ubar ) );
166             char ch = fileName.charAt( ubar + 1 );
167             if (ch == 'S') result.append( '/' );
168             else if (ch == 'U') result.append( '_' );
169             else if (ch == 'C') result.append( ':' );
170             here = ubar + 2;
171             }
172         result.append( fileName.substring( here ) );
173         return result.toString();
174 // Java 1.4 please!
175
// return fileName
176
// .replaceAll( "_C", ":" )
177
// .replaceAll( "_S", "/" )
178
// .replaceAll( "_U", "_" );
179
}
180                 
181     public void removeGraph( String JavaDoc name )
182         { forget( withRoot( name ) ).delete(); }
183
184     private FileGraph remember( File f, FileGraph g )
185         {
186         created.put( f, g );
187         return g;
188         }
189         
190     private File forget( File f )
191         {
192         created.remove( f );
193         return f;
194         }
195         
196     public boolean hasGraph( String JavaDoc name )
197         {
198         File f = withRoot( name );
199         return created.containsKey( f ) || f.exists();
200         }
201         
202     public void close()
203         {
204         if (deleteOnClose)
205             {
206             Iterator it = created.keySet().iterator();
207             while (it.hasNext()) ((File) it.next()).delete();
208             }
209         }
210         
211     /**
212         A Map1 that will convert filename strings to the corresponding graphname strings.
213     */

214     private static Map1 unconvert = new Map1()
215         { public Object JavaDoc map1( Object JavaDoc x )
216             { return toGraphname( (String JavaDoc) x ); }
217         };
218         
219     /**
220         Answer a FilenameFilter which recognises plausibly RDF filenames; they're not
221         directories, and FileGraph likes them. Pass the buck, pass the buck ...
222         
223         @return a FilenameFilter that accepts plausible graph names
224      */

225     public static FilenameFilter graphName()
226         { return new FilenameFilter()
227             {
228             public boolean accept( File file, String JavaDoc name )
229                 { return !new File( file, name ).isDirectory()
230                     && FileGraph.isPlausibleGraphName( name ); }
231             }; }
232             
233     /**
234         Answer an iterator over the names of graphs in the FileGraphMaker. This is all the
235         names of freshly-created graphs, plus the names of any files in the fileBase that
236         might be RDF files. "Might" is weaker than we'd like for now.
237          
238         @see com.hp.hpl.jena.graph.GraphMaker#listGraphs()
239      */

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