View Javadoc

1   /*
2    * Created on 15.09.2004
3    */
4   package myx;
5   
6   import org.xmldb.api.base.Collection;
7   import org.xmldb.api.base.ErrorCodes;
8   import org.xmldb.api.base.Resource;
9   import org.xmldb.api.base.Service;
10  import org.xmldb.api.base.XMLDBException;
11  import org.xmldb.api.modules.XMLResource;
12  import org.xmldb.api.reference.modules.XMLResourceImpl;
13  
14  //import org.apache.xerces.framework.XMLParser;
15  
16  import java.io.File;
17  import java.io.FileInputStream;
18  import java.sql.Clob;
19  import java.sql.Types;
20  import java.sql.Connection;
21  import java.sql.PreparedStatement;
22  import java.sql.ResultSet;
23  import java.sql.SQLException;
24  import java.util.ArrayList;
25  import java.util.logging.Level;
26  import java.util.logging.Logger;
27  
28  /***
29   * @author Mladen Adamovic (adamm@blic.net)
30   */
31  public class myxCollection implements Collection {
32      private static Logger logger = Logger.getLogger(myxCollection.class.getName());
33      private myxDatabase db = null;
34  
35      String collectionName;
36  
37      public myxCollection() {
38          super();
39          if (db == null) {
40              myxDatabase db = new myxDatabase();
41          }
42      }
43  
44      public myxCollection(myxDatabase cachedDB, String name) throws XMLDBException {
45          db = cachedDB;
46          logger.fine("myxCollection(...) enter ");
47          if(name!=null) {
48          	while(name.startsWith("//"))
49          		name=name.substring(1);
50          }
51          if (name==null || name.equals("/") || name.equals(""))
52              collectionName = "/";
53          else {
54              name = name.substring(name.lastIndexOf('/') + 1);
55              this.collectionName = name;
56              PreparedStatement stmt;
57              try {
58                  stmt = db.getConnection().prepareStatement("select name from " + name);
59                  //logger.fine("myxCollection(...) use statement " +
60                  // stmt.toString());
61                  ResultSet rs = stmt.executeQuery();
62              } 
63  	    catch (SQLException e) {
64  		logger.log(Level.SEVERE,"Cannot find Collection "+name,e);
65                  throw new XMLDBException(ErrorCodes.VENDOR_ERROR,
66  					 "Can't find the collection named " + name);
67              }
68          }
69      }
70  
71      /***
72       * @see org.xmldb.api.base.Collection#getName()
73       */
74      public String getName() throws XMLDBException {
75          return collectionName;
76      }
77  
78      /***
79       * @see org.xmldb.api.base.Collection#getServices()
80       */
81      public Service[] getServices() throws XMLDBException {
82          Service[] service = new Service[10];
83          service[0] = getService("XPathQueryService", "1.0");
84          service[1] = getService("CollectionManagementService", "1.0");
85          //XUpdateQueryService is not implemented yet
86          return service;
87      }
88  
89      /***
90       * @see org.xmldb.api.base.Collection#getService(java.lang.String,
91       *      java.lang.String)
92       */
93      public Service getService(String name, String version)
94              throws XMLDBException {
95          if (name.equals("XPathQueryService")) {
96              return new myxSaxonQueryService(this);
97          } else if (name.equals("CollectionManagementService")) {
98              return new myxCollectionManagementService();
99          } else if (name.equals("XQueryService"))
100             return new myxXQuerySaxonService(this);
101         //XUpdateQueryService is not implemented yet
102         return null;
103     }
104 
105     /***
106      * @see org.xmldb.api.base.Collection#getParentCollection()
107      */
108     public Collection getParentCollection() throws XMLDBException {
109         if (collectionName == null)
110             return null;
111         else
112             return new myxCollection();
113     }
114 
115     /***
116      * @see org.xmldb.api.base.Collection#getChildCollectionCount()
117      */
118     public int getChildCollectionCount() throws XMLDBException {
119         String[] list = listChildCollections();
120         if (list == null)
121             return 0;
122         else
123             return list.length;
124     }
125 
126     /***
127      * @see org.xmldb.api.base.Collection#listChildCollections()
128      */
129     public String[] listChildCollections() throws XMLDBException {
130         ArrayList list = new ArrayList();
131         String res[];
132         if (collectionName != null)
133             return new String[0];
134         else {
135             PreparedStatement stmt;
136             try {
137                 stmt = db.getConnection().prepareStatement("show tables");
138                 ResultSet rs = stmt.executeQuery();
139                 while (rs.next()) {
140                     list.add(rs.getString(1));
141                 }
142             } catch (SQLException e) {
143                 logger.log(Level.SEVERE, "Error retrieving child collections",e); 
144                 throw new XMLDBException(ErrorCodes.VENDOR_ERROR,
145                         "Can't find child collections for " + collectionName);
146             }
147         }
148         res = new String[list.size()];
149         int i;
150         for (i = 0; i < list.size(); i++) {
151             res[i] = (String) list.get(i);
152         }
153         return res;
154     }
155 
156     /***
157      * @see org.xmldb.api.base.Collection#getChildCollection(java.lang.String)
158      */
159     public Collection getChildCollection(String name) throws XMLDBException {
160         if (collectionName == null)
161             try { 
162                 return new myxCollection(db, name);
163             } 
164 	    catch(XMLDBException xe) {
165                 logger.log(Level.WARNING, "Error retrieving child collections",xe); 
166                 return null;
167             }
168         else
169             throw new XMLDBException(ErrorCodes.VENDOR_ERROR, "Collection "
170                     + collectionName + "  don't have child collection named "
171                     + name);
172     }
173 
174     /***
175      * @see org.xmldb.api.base.Collection#getResourceCount()
176      */
177     public int getResourceCount() throws XMLDBException {
178         if (collectionName == null)
179             return 0;
180         else
181             return listResources().length;
182     }
183 
184     /***
185      * @see org.xmldb.api.base.Collection#listResources()
186      */
187     public String[] listResources() throws XMLDBException {
188         ArrayList list = new ArrayList();
189         String res[];
190         if (collectionName == null)
191             return new String[0];
192         else {
193             PreparedStatement stmt;
194             try {
195                 stmt = db.getConnection().prepareStatement("select name from "
196                         + collectionName);
197                 ResultSet rs = stmt.executeQuery();
198                 while (rs.next()) {
199                     list.add(rs.getString(1));
200                 }
201             } catch (SQLException e) {
202                 logger.log(Level.WARNING, "Error listing resources",e); 
203 
204                 throw new XMLDBException(ErrorCodes.VENDOR_ERROR,
205                         "Can't find child collections for " + collectionName);
206             }
207         }
208         res = new String[list.size()];
209         int i;
210         for (i = 0; i < list.size(); i++) {
211             res[i] = (String) list.get(i);
212         }
213         return res;
214     }
215 
216     /***
217      * @see org.xmldb.api.base.Collection#createResource(java.lang.String,
218      *      java.lang.String)
219      */
220     public Resource createResource(String id, String type)
221             throws XMLDBException {
222         Resource resource = null;
223         if (type.equals(XMLResource.RESOURCE_TYPE)) {
224             resource = new XMLResourceImpl(this, id, id, "");
225 	    return resource;
226 	}
227 	throw new XMLDBException(ErrorCodes.VENDOR_ERROR,
228 				 "Unknown resource type in Collection.createResource(...) ");
229     }
230 
231     /***
232      * @see org.xmldb.api.base.Collection#removeResource(org.xmldb.api.base.Resource)
233      */
234     public void removeResource(Resource res) throws XMLDBException {
235         if (collectionName == null)
236             return;
237         else {
238             PreparedStatement stmt;
239             try {
240                 stmt = db.getConnection().prepareStatement("delete from " + collectionName
241                         + " where name=?");
242                 stmt.setString(1, res.getId());
243                 stmt.execute();
244             } catch (SQLException e) {
245                 logger.log(Level.SEVERE, "Error removing resource",e); 
246 
247                 throw new XMLDBException(ErrorCodes.VENDOR_ERROR,
248                         "Can't find child collections for " + collectionName);
249             }
250         }
251     }
252 
253     /***
254      * @see org.xmldb.api.base.Collection#storeResource(org.xmldb.api.base.Resource)
255      */
256     public void storeResource(Resource res) throws XMLDBException {
257         PreparedStatement stmt=null;
258         if (collectionName == null)
259             return;
260         else {
261             try {
262                 stmt = db.getConnection().prepareStatement("insert into " + collectionName
263                         + " values (?, ?)");
264                 stmt.setString(1, res.getId());
265                 //this way to create clob from is just for mysql.
266                 stmt.setObject(2, (String) res.getContent(),
267                         java.sql.Types.CLOB);
268                 //logger.fine(stmt.toString());
269                 stmt.execute();
270             } catch (SQLException e) {
271                 logger.log(Level.SEVERE, "Error storing resource",e); 
272 
273                 throw new XMLDBException(ErrorCodes.VENDOR_ERROR,
274                         "Can't find child collections for " + collectionName);
275             }
276         }
277     }
278 
279     /***
280      * @see org.xmldb.api.base.Collection#getResource(java.lang.String)
281      */
282     public Resource getResource(String id) throws XMLDBException {
283         String textDoc;
284         if (collectionName == null || collectionName.equals(""))
285             return null;
286         try {
287             PreparedStatement stmt = db.getConnection().prepareStatement("select content from " + collectionName
288                             + " where name=?");
289             stmt.setString(1, id);
290             logger.fine(stmt.toString());
291             ResultSet rs = stmt.executeQuery();
292             if (!rs.next()) //result set empty no such document
293                 return null;
294             java.sql.Clob clob = rs.getClob(1);
295             //khm... converting clob into String
296             textDoc = clob.getSubString(1l, (int) clob.length());
297         } catch (SQLException e) {
298 	    logger.log(Level.SEVERE, "Error retrieving resource",e); 
299             throw new XMLDBException(ErrorCodes.VENDOR_ERROR,
300                     "Exception when trying to read file " + id
301                             + "from collection " + collectionName);
302         }
303         return new XMLResourceImpl(this, id, id, textDoc);
304     }
305 
306     /***
307      * @see org.xmldb.api.base.Collection#createId()
308      */
309     public String createId() throws XMLDBException {
310         // TODO Auto-generated method stub
311         return null;
312     }
313 
314     /***
315      * import one file into this myxCollection
316      * 
317      * @param file
318      *            file you want to import into this myxCollection
319      * @throws XMLDBException
320      */
321     public void importFile(File file) throws XMLDBException {
322         logger.fine("importing file " + file.getName() + "...");
323         byte[] fileBuffer;
324         try {
325             FileInputStream insr = new FileInputStream(file);
326             fileBuffer = new byte[(int) file.length()];
327             insr.read(fileBuffer);
328             insr.close();
329         } catch (Exception e) {
330             throw new XMLDBException(ErrorCodes.VENDOR_ERROR,
331                     "File IO exception in myxCollection.importFile");
332         }
333         String fileContent = new String(fileBuffer);
334         XMLResourceImpl res = new XMLResourceImpl(this, file.getName(), file
335                 .getName(), fileContent);
336         logger.fine("length of file to store: " + fileContent.length());
337         storeResource(res);
338     }
339 
340     /***
341      * import all files from one directory into this myxCollection
342      * 
343      * @param directoryPath
344      * @throws XMLDBException
345      *             myxCollection.importdirectory parametar must be valid
346      *             directory name
347      */
348     public void importDirectoryContents(String directoryPath)
349             throws XMLDBException {
350         File dir = new File(directoryPath);
351         logger.fine("directoryPath : " + directoryPath);
352         logger.fine("dir : " + dir.toString());
353         if (!dir.isDirectory()) {
354             throw new XMLDBException(ErrorCodes.VENDOR_ERROR,
355                     "myxCollection.importdirectory parametar must be valid directory name");
356         } else {
357             File file[] = dir.listFiles();
358             int i;
359             for (i = 0; i < file.length; i++)
360                 importFile(file[i]);
361         }
362     }
363 
364     /***
365      * @see org.xmldb.api.base.Collection#isOpen()
366      */
367     public boolean isOpen() throws XMLDBException {
368         return (db.getConnection() != null);
369     }
370 
371     /***
372      * @see org.xmldb.api.base.Collection#close()
373      */
374     public void close() throws XMLDBException {
375 	db.closeConnection();       
376         collectionName = null;
377     }
378 
379     /***
380      * @see org.xmldb.api.base.Configurable#getProperty(java.lang.String)
381      */
382     public String getProperty(String name) throws XMLDBException {
383         // TODO Auto-generated method stub
384         return null;
385     }
386 
387     /***
388      * @see org.xmldb.api.base.Configurable#setProperty(java.lang.String,
389      *      java.lang.String)
390      */
391     public void setProperty(String name, String value) throws XMLDBException {
392         // TODO Auto-generated method stub
393 
394     }
395 
396 }