KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > daffodilwoods > daffodildb > server > datasystem > persistentsystem > PersistentSystem


1 package com.daffodilwoods.daffodildb.server.datasystem.persistentsystem;
2
3 import java.io.*;
4 import java.util.*;
5
6 import com.daffodilwoods.daffodildb.server.datadictionarysystem.*;
7 import com.daffodilwoods.daffodildb.server.datasystem.encryptdecrypt.*;
8 import com.daffodilwoods.daffodildb.server.datasystem.interfaces.*;
9 import com.daffodilwoods.daffodildb.server.datasystem.interfaces.Utility;
10 import com.daffodilwoods.daffodildb.server.datasystem.persistentsystem.versioninfo.*;
11 import com.daffodilwoods.daffodildb.server.serversystem.*;
12 import com.daffodilwoods.daffodildb.utils.*;
13 import com.daffodilwoods.daffodildb.utils.byteconverter.*;
14 import com.daffodilwoods.daffodildb.utils.comparator.*;
15 import com.daffodilwoods.database.resource.*;
16
17 /**
18  *
19  * <p>Title: Persistent System</p>
20  * <p>Description: It manages all the databases related to the DaffodilDB server with the help of
21  * <tt>SYSTEM DATABASE</tt> ,which is the master database in DaffodilDB.It controls all the database
22  * level operations like creating a new database,removing a database etc.It also maintains,
23  * currently used databases list. </p>
24  */

25 public class PersistentSystem implements DatabaseConstants, _DataSystem {
26
27    /**
28     * Maintains list of all databases which are Currently in use having mapping with Database name
29     */

30
31    private HashMap databaseMap;
32
33    /**
34     * To compare databaseName
35     */

36
37    private CTusjohJoTfotjujwfDpnqbsbups stringComparator;
38
39    /**
40     * Path Of DaffodilDBHome where all the databases reside.
41     */

42
43    private String JavaDoc daffodilHome;
44
45    /**
46     * To calculate memory used by database
47     */

48
49
50    private boolean isReadOnlyMode;
51
52    public PersistentSystem(String JavaDoc daffodilHome0, boolean isReadOnlyMode0) throws DException {
53       databaseMap = new HashMap();
54       stringComparator = new CTusjohJoTfotjujwfDpnqbsbups();
55       daffodilHome = daffodilHome0;
56       isReadOnlyMode = isReadOnlyMode0;
57    }
58 /*
59    public PersistentSystem(_MemoryManager mananger0) throws DException {
60       databaseMap = new HashMap();
61       stringComparator = new CTusjohJoTfotjujwfDpnqbsbups();
62       mananger = mananger0;
63    }
64 */

65    /**
66     * Store All the information of new database in SYSTEM DATABASE which user wants to create and
67     * creates a new file for new database at daffodilDBHome.
68     *
69     * initializes the bytes of first cluster by seeking to the 0th position
70     * and initializing it upto clusterSize (For Windows 98)
71     *
72     * @param databaseName Name of Database
73     * @param initialSize initial Size of Database
74     * @param incrementFactor Factor by which database size would be increased when Existing file is fully used
75     * @param unicodeSupport Whether unicode support is required or not
76     * @param multifileSupport Whether new files should be created or old file size has to increase in case of existing file is fully used
77     *
78     * @throws DException if database by given name is already created orthere is no space on disk to create another file with initial size specified by User
79     */

80
81    public synchronized void createDatabase(String JavaDoc databaseName, String JavaDoc initialSize, int incrementFactor, boolean unicodeSupport, boolean multifileSupport, boolean encryptionSupport, String JavaDoc encryptionAlgo, String JavaDoc encryptionKey, String JavaDoc clusterSize) throws DException {
82      File ff=null,ff1=null;
83       RandomAccessFile file = null;
84      try {
85          if (encryptionKey.length() > 256)
86             throw new DException("DSE2048", null);
87          String JavaDoc path = daffodilHome + File.separator + databaseName + File.separator + databaseName + ".ddb";
88          if(path.length()-3 > 256 ){ // -3 is for d:/path/databaseName.ddb its ://
89
throw new DException("DSE2051", new Object JavaDoc[] {path});
90          }
91          ff = new File(daffodilHome, databaseName);
92          if (!ff.getName().equals(databaseName))
93             throw new DException("DSE2049", new Object JavaDoc[] {databaseName});
94          ff = new File(path);
95          ff1 = ff.getParentFile();
96          ff1.mkdirs();
97          try {
98             file = new RandomAccessFile(ff, "rw");
99          } catch (FileNotFoundException ex1) {
100             if (!ff.exists())
101                throw new DException("DSE8118", new Object JavaDoc[] {ex1.getMessage()});
102          }
103          _Database database = getDatabase(DatabaseConstants.SYSTEMDATABASE);
104          _DataTable databaseInfoTable = (_DataTable) database.getTable(SystemTables.DATABASEINFO);
105          DatabaseUserTableIterator databaseTableIteartor = (DatabaseUserTableIterator) databaseInfoTable.getIterator();
106          _TableCharacteristics tableCharacteristics = databaseInfoTable.getTableCharacteristics();
107          BufferRange bytesOfDatabaseName = new BufferRange(CCzufDpowfsufs.getBytes(databaseName, databaseName.length(), false));
108          if (databaseTableIteartor.first()) {
109             do {
110                BufferRange bytesGot = (BufferRange) databaseTableIteartor.getColumnValues(0);
111                if (stringComparator.compare(bytesGot, bytesOfDatabaseName) == 0) {
112                   if (ff.exists() && ff.length() == 0) {
113                      file.close();
114                      throw new DException("DSE5539", new Object JavaDoc[] {databaseName}); //Removed from path
115
} else {
116                      file.close();
117                      throw new DException("DSE314", new Object JavaDoc[] {databaseName}); //Database already exists
118
}
119                }
120             } while (databaseTableIteartor.next());
121          }
122
123          file.setLength(getInitialSize(initialSize));
124          clusterSize = clusterSize == null ? ((PersistentDatabase)database).getVersionHandler().getDefaultClusterSize() : clusterSize;
125          int clusterSizeInInt = getClusterSize(clusterSize);
126          file.seek(0);
127          file.write(new byte[clusterSizeInInt]);
128          putDatabaseVersion(file,((PersistentDatabase)database).getVersionHandler().getVersionCode());
129          file.close();
130          ArrayList list = new ArrayList();
131         list.add(SystemTables.DATABASEINFO);
132         _DatabaseUser user = database.getDatabaseUser(list);
133         Object JavaDoc[] value = new Object JavaDoc[] {databaseName, initialSize, DATABASEVERSION, new Integer JavaDoc(DATABASECODE), new Integer JavaDoc(incrementFactor), Utility.getBooleanValue(unicodeSupport), Utility.getBooleanValue(multifileSupport), Utility.getBooleanValue(encryptionSupport), encryptionAlgo, encryptionKey, clusterSize};
134         BufferRange[] bytes = Utility.convertIntoBufferRange(tableCharacteristics.getColumnTypes(), value, tableCharacteristics.getCollator());
135         ( (_UserTableOperations) databaseTableIteartor).insert(user, bytes);
136         user.writeToFile();
137
138       } catch (Exception JavaDoc ex) {
139         if(ex instanceof DException){
140           if(((DException)ex).getDseCode().equalsIgnoreCase("DSE314") )
141             throw (DException)ex;
142         }
143         if(ff!=null){
144          if(file!= null){
145            try{
146              file.close();
147            }catch(IOException io){
148              io.printStackTrace() ;
149            }
150          }
151         ff.delete();
152        }
153       if(ff1 != null){
154         ff1.delete();
155       }
156       if(ex instanceof DException)
157          throw (DException)ex;
158        throw new DException("DSE2025", new Object JavaDoc[] {ex.getMessage()});
159       }
160    }
161
162    /**
163     * Returns database corresponding to databaseName.If gets database from map returns it
164     * otherwise Gets all the Properties of database from DataBaseInfo System Table, makes database file with its
165     * initial size, Makes database instance and puts its entry in databaseMap having Mapping with
166     * databaseName.
167     *
168     * @param databaseName name of database
169     * @return database corresponding to databaseName
170     *
171     * @throws DException if database does not exist
172     * */

173
174    public synchronized _Database getDatabase(String JavaDoc databaseName) throws DException {
175       _Database pd = (_Database) databaseMap.get(databaseName);
176       if (pd != null)
177          return pd;
178       if (DatabaseConstants.SYSTEMDATABASE.equalsIgnoreCase(databaseName))
179          return getSystemDatabase();
180       PersistentDatabase database = (PersistentDatabase) getDatabase(DatabaseConstants.SYSTEMDATABASE);
181       _DataTable databaseInfoTable = (_DataTable) database.getTable(SystemTables.DATABASEINFO);
182       DatabaseUserTableIterator databaseTableIteartor = (DatabaseUserTableIterator) databaseInfoTable.getIterator();
183       Object JavaDoc[] databaseProperties = null;
184       BufferRange bytesOfDatabaseName = new BufferRange(CCzufDpowfsufs.getBytes(databaseName, databaseName.length(), false));
185       if (databaseTableIteartor.first())
186          do {
187             BufferRange[] bytesGot = (BufferRange[]) databaseTableIteartor.getColumnValues();
188             if (stringComparator.compare(bytesGot[0], bytesOfDatabaseName) == 0) {
189                databaseProperties = (Object JavaDoc[]) databaseInfoTable.getTableCharacteristics().getObject(bytesGot);
190                return getDatabase(databaseProperties, databaseName, database);
191             }
192          } while (databaseTableIteartor.next());
193       throw new DException("DSE316", new Object JavaDoc[] {databaseName}); //Database doesn't exist
194
}
195
196    /**
197     * first check the entry in the databaseMap if it exists there then throws exception
198     * DATABASE_LOCKED_EXCEPTION
199     * if enrty is not there in databaseMap then gets database iterator on DATABASEINFO System Table and iterates till the entry
200     * for the database is found in this table and then gives call to dropDatabase(databaseTableIteartor,databaseName,database) method
201     *
202     * @param databaseName name of database which has to be dropped
203     *
204     * @throws DException if database is used by another user or database with this name does not exist
205     */

206
207    public synchronized void dropDatabase(String JavaDoc databaseName) throws DException {
208       PersistentDatabase pd = (PersistentDatabase) databaseMap.get(databaseName);
209       if (pd != null)
210          throw DATABASE_LOCKED_EXCEPTION;
211       _Database database = getDatabase(DatabaseConstants.SYSTEMDATABASE);
212       DatabaseUserTableIterator databaseTableIteartor = (DatabaseUserTableIterator) ( (_DataTable) database.getTable(SystemTables.DATABASEINFO)).getIterator();
213       BufferRange bytesOfDatabaseName = new BufferRange(CCzufDpowfsufs.getBytes(databaseName, databaseName.length(), false));
214       boolean found = false;
215       if (databaseTableIteartor.first())
216          do {
217             BufferRange bytesGot = (BufferRange) databaseTableIteartor.getColumnValues(0);
218             if (stringComparator.compare(bytesGot, bytesOfDatabaseName) == 0) {
219                dropDatabase(databaseTableIteartor, databaseName, database);
220                found = true;
221                break;
222             }
223          } while (databaseTableIteartor.next());
224       if ( ( (PersistentDatabase) database).getVersionHandler().isBackUpSupported()) {
225          try {
226             _DataTable scheduleInfoTable = (_DataTable) database.getTable(
227                 SystemTables.SCHEDULEINFO);
228             DatabaseUserTableIterator scheduleInfoTableIteartor = (
229                 DatabaseUserTableIterator) scheduleInfoTable.getIterator();
230             if (scheduleInfoTableIteartor.first()) {
231                do {
232                   BufferRange bytesGot = (BufferRange) scheduleInfoTableIteartor.
233                       getColumnValues(0);
234                   if (stringComparator.compare(bytesGot, bytesOfDatabaseName) == 0) {
235                      dropDatabase(scheduleInfoTableIteartor, databaseName, database);
236                   }
237                } while (scheduleInfoTableIteartor.next());
238             }
239          } catch (DException ex) {
240             if (!ex.getDseCode().equalsIgnoreCase("DSE959")) {
241                throw ex;
242             }
243          }
244       }
245       if (!found)
246          throw new DException("DSE316", new Object JavaDoc[] {databaseName});
247    }
248
249    /**
250     * Returns SystemDatabase,Makes system database
251     * initializes the bytes of first cluster by seeking to the 0th position
252     * and initializing it upto clusterSize (For Windows (98))
253     * with given properties and puts it in databaseMap.
254     *
255     * @return SystemDatabase
256     */

257    public _Database createSystemDatabase(String JavaDoc path0, String JavaDoc initialSize, int incrementFactor, boolean unicodeSupport, boolean multifileSupport) throws DException {
258
259       String JavaDoc path = daffodilHome + File.separator + DatabaseConstants.SYSTEMDATABASE + File.separator + DatabaseConstants.SYSTEMDATABASE + ".ddb";
260       long size = getInitialSize(initialSize); //Long.parseLong(initialSize)* 1024 * 1024 ;
261
PersistentDatabase pd = null;
262
263       try {
264          File ff = new File(path);
265          File ff1 = ff.getParentFile();
266          ff1.mkdirs();
267          RandomAccessFile file = new RandomAccessFile(new File(path), "rw");
268          file.setLength(size);
269
270
271          VersionHandler versionHandler = VersionHandlerFactory.getLatestVersionHandler() ;
272          int clusterSize = getClusterSize(versionHandler.getDefaultClusterSize() );
273          file.seek(0);
274          file.write(new byte[clusterSize]);
275          putDatabaseVersion(file,DatabaseConstants.DATABASEVERSION );
276          versionHandler.setClusterSize(clusterSize);
277          DRandomAccessFileUpto3_2 dRandomAccessFile = versionHandler.getDRandomAccessFile(file, size, path, incrementFactor, multifileSupport, null,clusterSize);
278          pd = new PersistentDatabase(dRandomAccessFile, DatabaseConstants.SYSTEMDATABASE, versionHandler, daffodilHome, isReadOnlyMode);
279       } catch (IOException io) {
280          throw new DException("DSE2025", new Object JavaDoc[] {io.getMessage()});
281       }
282       databaseMap.put(DatabaseConstants.SYSTEMDATABASE.toLowerCase(), pd);
283       return pd;
284    }
285    /**
286     * To get system database
287     * @throws DException
288     * @return _Database
289     */

290    private _Database getSystemDatabase() throws DException {
291       String JavaDoc path = daffodilHome + File.separator + DatabaseConstants.SYSTEMDATABASE + File.separator + DatabaseConstants.SYSTEMDATABASE + ".ddb";
292       long size = getInitialSize(DatabaseConstants.INITIALFILESIZE);
293       _Database pd = null;
294
295       try {
296          File ff = new File(path);
297          File ff1 = ff.getParentFile();
298          ff1.mkdirs();
299          RandomAccessFile file = null;
300          if (isReadOnlyMode) {
301             file = new RandomAccessFile(new File(path), "r");
302          } else {
303             file = new RandomAccessFile(new File(path), "rw");
304          }
305          if (ff.length() == 0) {
306            System.out.println("Database Path::::::: " + path);
307            file.close();
308            ff.delete();
309            ff1.delete();
310            throw new DException("DSE5539", new Object JavaDoc[] {DatabaseConstants.SYSTEMDATABASE});
311         }
312
313
314          VersionHandler versionHandler = VersionHandlerFactory.getVersionHandler(file);
315                int clusterSize = getClusterSize(versionHandler.getDefaultClusterSize() );
316              versionHandler.setClusterSize(clusterSize);
317          DRandomAccessFileUpto3_2 dRandomAccessFile = versionHandler.getDRandomAccessFile(file, size, path, 20, false, null,clusterSize);
318          pd = new PersistentDatabase(dRandomAccessFile, DatabaseConstants.SYSTEMDATABASE, versionHandler, daffodilHome, isReadOnlyMode);
319       } catch (IOException io) {
320          throw new DException("DSE2025", new Object JavaDoc[] {io.getMessage()});
321       }
322       databaseMap.put(DatabaseConstants.SYSTEMDATABASE.toLowerCase(), pd);
323       return pd;
324    }
325
326    /**
327     * Gets all the property of database from specified Properties and creates database
328     *
329     * @param databaseName Name of database
330     * @param prop Properties of database
331     * @throws DException if database already Exists
332     */

333
334    public void createDatabase(String JavaDoc databaseName, Properties prop) throws DException {
335       String JavaDoc initialSize = prop.getProperty(ServerSystem.INITIALFILESIZE);
336       initialSize = initialSize == null ? DatabaseConstants.INITIALFILESIZE : initialSize;
337       String JavaDoc incrmentFactor = prop.getProperty(ServerSystem.INCREMENTFACTOR);
338       int incrementFact = 0;
339     try {
340       incrementFact = incrmentFactor == null || Integer.parseInt(incrmentFactor) == 0 ?
341           DatabaseConstants.INCREMENTFACTOR : (Integer.parseInt(incrmentFactor) < 0 ? -1 :
342            Integer.parseInt(incrmentFactor));
343     }
344     catch (NumberFormatException JavaDoc ex) {
345       throw new DException("DSE2047", new Object JavaDoc[]{incrmentFactor});
346     }
347     if (incrementFact == -1)
348        throw new DException("DSE2047", new Object JavaDoc[]{incrmentFactor});
349
350
351       String JavaDoc multifileSupport = prop.getProperty(ServerSystem.MULTIFILESUPPORT);
352       boolean multiFile = multifileSupport == null ? false : multifileSupport.equalsIgnoreCase("true") ? true : false;
353       String JavaDoc uniCodeSupport = prop.getProperty(ServerSystem.UNICODESUPPORT);
354       boolean uniCode = uniCodeSupport == null ? false : uniCodeSupport.equalsIgnoreCase("true") ? true : false;
355       String JavaDoc encrytpionSupport = prop.getProperty(ServerSystem.ENCRYPTIONSUPPORT);
356       boolean encryption = encrytpionSupport == null ? false : encrytpionSupport.equalsIgnoreCase("true") ? _Server.ISONEDOLLARDB ? false : true : false;
357       String JavaDoc encryptionAlgo = prop.getProperty(ServerSystem.ENCRYPTIONALGO);
358       encryptionAlgo = encryption ? encryptionAlgo == null ? DatabaseConstants.DEFAULT_ALGO : encryptionAlgo : DatabaseConstants.NONE;
359       String JavaDoc encryptionKey = prop.getProperty(ServerSystem.ENCRYPTIONKEY);
360       encryptionKey = encryption ? encryptionKey == null ? DatabaseConstants.DEFAULT_KEY : encryptionKey : DatabaseConstants.NONE;
361
362       String JavaDoc clusterSize = prop.getProperty(ServerSystem.CLUSTERSIZE);
363
364       createDatabase(databaseName, initialSize, incrementFact, uniCode, multiFile, encryption, encryptionAlgo, encryptionKey, clusterSize);
365    }
366    /**
367     * TO get initial size of the database file in bytes.
368     * @param initialSize String
369     * @throws DException
370     * @return long
371     */

372    private long getInitialSize(String JavaDoc initialSize) throws DException {
373       initialSize = initialSize == null ? INITIALFILESIZE : initialSize.trim().toUpperCase();
374       long size = 0;
375       try {
376          if (initialSize.endsWith("M") || initialSize.endsWith("MB")) {
377             int index = initialSize.indexOf("M");
378             size = Long.parseLong(initialSize.substring(0, index).trim()) * 1024 * 1024;
379          } else if (initialSize.endsWith("G") || initialSize.endsWith("GB")) {
380             int index = initialSize.indexOf("G");
381             size = Long.parseLong(initialSize.substring(0, index).trim()) * 1024 * 1024 * 1024;
382          } else if (initialSize.endsWith("K") || initialSize.endsWith("KB")) {
383             int index = initialSize.indexOf("K");
384             size = Long.parseLong(initialSize.substring(0, index).trim()) * 1024;
385          } else {
386             size = Long.parseLong(initialSize.trim()) * 1024 * 1024;
387          }
388       } catch (NumberFormatException JavaDoc ex) {
389            size = 5 * 1024 * 1024;
390
391       }
392       if (size < 1024 * 1024) {
393          size = 5 * 1024 * 1024;
394       }
395       return size;
396    }
397
398    /**
399     * Makes userDatabase Entry in SystemDatabase.Used in Browser.
400     *
401     * @param databaseName Name of database
402     * @param properties properties of database
403     * @param numberOfFiles total number of files in case of multiFileSupport
404     * @throws DException if database already exists
405     */

406
407    public void addDatabase(String JavaDoc databaseName, Properties properties, int numberOfFiles) throws DException {
408       _Database db = getDatabase(databaseName);
409       if (db != null)
410          throw new DException("DSE314", null); // throw Exception if database already exist
411
String JavaDoc initialSize = properties.getProperty(ServerSystem.INITIALFILESIZE);
412       initialSize = initialSize == null ? DatabaseConstants.INITIALFILESIZE : initialSize;
413
414       String JavaDoc incrementFact = properties.getProperty(ServerSystem.INCREMENTFACTOR);
415       int incrementFactor = incrementFact == null ? DatabaseConstants.INCREMENTFACTOR : Integer.parseInt(incrementFact);
416       Boolean JavaDoc multipleFile = Utility.getBooleanValue(properties.getProperty(ServerSystem.MULTIFILESUPPORT));
417       if (!multipleFile.booleanValue() && numberOfFiles > 1) {
418          throw new DException("DSE2027", null);
419       }
420       Boolean JavaDoc uniCode = Utility.getBooleanValue(properties.getProperty(ServerSystem.UNICODESUPPORT));
421       try {
422          String JavaDoc path = daffodilHome + File.separator + databaseName + File.separator + databaseName + ".ddb";
423          File ff = new File(path);
424          File ff1 = ff.getParentFile();
425          ff1.mkdirs();
426          if (multipleFile.booleanValue()) {
427             int len = (int)new RandomAccessFile(path + "1", "rw").length();
428             if (len != Integer.parseInt(initialSize) * incrementFactor / 100)
429                throw new DException("DSE2028", new Object JavaDoc[] {new Integer JavaDoc(len), initialSize});
430          }
431          RandomAccessFile file = new RandomAccessFile(new File(path), "rw");
432          long size = getInitialSize(initialSize);
433          if (size < file.length())
434             throw new DException("DSE2029", null);
435          if ( (file.length() - size) % (size * incrementFactor / 100) != 0)
436             throw new DException("DSE2030", new Object JavaDoc[] {new Long JavaDoc(file.length()), new Long JavaDoc(size), new Integer JavaDoc(incrementFactor)});
437          _Database database = getDatabase(DatabaseConstants.SYSTEMDATABASE);
438          _DataTable databaseInfoTable = (_DataTable) database.getTable(SystemTables.DATABASEINFO);
439          DatabaseUserTableIterator databaseTableIteartor = (DatabaseUserTableIterator) databaseInfoTable.getIterator();
440          _TableCharacteristics tableCharacteristics = databaseInfoTable.getTableCharacteristics();
441          BufferRange bytesOfDatabaseName = new BufferRange(CCzufDpowfsufs.getBytes(databaseName, databaseName.length(), false));
442          if (databaseTableIteartor.first())
443             do {
444                if (stringComparator.compare( (BufferRange) databaseTableIteartor.getColumnValues(0), bytesOfDatabaseName) == 0) {
445                   throw new DException("DSE314", new Object JavaDoc[] {databaseName});
446                }
447             } while (databaseTableIteartor.next());
448          ArrayList list = new ArrayList();
449          list.add(SystemTables.DATABASEINFO);
450          _DatabaseUser user = database.getDatabaseUser(list);
451          try {
452             Object JavaDoc[] value = new Object JavaDoc[] {databaseName, initialSize, DATABASEVERSION, new Integer JavaDoc(DATABASECODE), new Integer JavaDoc(incrementFactor), uniCode, multipleFile};
453             BufferRange[] bytes = Utility.convertIntoBufferRange(tableCharacteristics.getColumnTypes(), value, tableCharacteristics.getCollator());
454             ( (_UserTableOperations) databaseTableIteartor).insert(user, bytes);
455             user.writeToFile();
456          } finally {
457             user.releaseCluster();
458          }
459       } catch (Exception JavaDoc de) {
460          throw new DException("DSE2025", new Object JavaDoc[] {de.getMessage()});
461       }
462    }
463
464    /**
465     * gets an ArrayList of all the databases created so far
466     *
467     */

468
469    public ArrayList getAllDatabases() throws DException {
470       ArrayList databaseList = new ArrayList();
471       _Database database = getDatabase(DatabaseConstants.SYSTEMDATABASE);
472       _DataTable databaseInfoTable = (_DataTable) database.getTable(SystemTables.DATABASEINFO);
473       DatabaseUserTableIterator databaseTableIteartor = (DatabaseUserTableIterator) databaseInfoTable.getIterator();
474       if (databaseTableIteartor.first()) {
475          do {
476             String JavaDoc databaseName = CCzufDpowfsufs.getString( ( (BufferRange) databaseTableIteartor.getColumnValues(0)).getBytes()).toLowerCase();
477             databaseList.add(databaseName);
478          } while (databaseTableIteartor.next());
479       }
480       return databaseList;
481    }
482
483    /**
484     * removes database entry form databaseMap
485     *
486     */

487
488    public void removeDatabase(String JavaDoc databaseName) throws DException {
489       PersistentDatabase ps = (PersistentDatabase) databaseMap.get(databaseName);
490       if (ps != null)
491          ps.closeFile();
492       databaseMap.remove(databaseName);
493    }
494
495    /**
496     * deletes all the .ddb files, temp file, power files and in case of MULTIFILESUPPORT
497     * deletes all the .dat files present corresponding to a database
498     *
499     */

500
501    private void deleteFiles(String JavaDoc databaseName, _DatabaseUser user) throws DException {
502       int index = getIndex(databaseName, user);
503       String JavaDoc path = daffodilHome + File.separator + databaseName + File.separator + databaseName + ".ddb";
504       File f = new File(path);
505       f.delete();
506       File ff1 = f.getParentFile();
507       File[] files = ff1.listFiles(new PowerFileFilter());
508       if (files != null)
509          for (int i = 0; i < files.length; i++) {
510             files[i].delete();
511          }
512
513       String JavaDoc str = f.getName();
514       str = str.substring(0, str.lastIndexOf("."));
515       File ff = new File(ff1, "_tempFile.swp");
516       ff.delete();
517       for (int i = 1; i < index; i++) {
518          path = daffodilHome + File.separator + databaseName + File.separator + "_" + i + ".dat";
519          f = new File(path);
520          f.delete();
521       }
522       ff1.delete();
523    }
524
525    /**
526     * returns the number of files created in case of MULTIFILESUPPORT property set to true
527     * else returns -1
528     *
529     */

530
531    private int getIndex(String JavaDoc databaseName, _DatabaseUser user) throws DException {
532       _Database database = getDatabase(DatabaseConstants.SYSTEMDATABASE);
533       DatabaseUserTableIterator iterator = (DatabaseUserTableIterator) ( (_DataTable) database.getTable(SystemTables.DATABASEFILEINFO)).getIterator();
534       if (iterator.first()) {
535          BufferRange bytesOfDatabaseName = new BufferRange(CCzufDpowfsufs.getBytes(databaseName, databaseName.length(), false));
536          BufferRange[] values;
537          do {
538             values = (BufferRange[]) iterator.getColumnValues();
539             if (stringComparator.compare(values[0], bytesOfDatabaseName) == 0) {
540                iterator.delete(user);
541                return CCzufDpowfsufs.getInt(values[1].getBytes()).hashCode();
542             }
543          } while (iterator.next());
544       }
545       return -1;
546    }
547
548     private EDBlockCipher initializeEncrytpionInfo(String JavaDoc algo,String JavaDoc key) throws DException{
549         EDBlockCipher m_EDBlockEDDes3Cipher = null;
550         if(!algo.equalsIgnoreCase(NONE))
551             m_EDBlockEDDes3Cipher = EDUtils.getEncryptDecryptCipher(algo, key);
552         return m_EDBlockEDDes3Cipher;
553     }
554
555     /**
556          * is referred by getDatabase(String) method
557          * makes database file with its initial size, makes database instance
558          * and puts its entry in databaseMap having Mapping with databaseName.
559          *
560          * @param databaseProps properties of database for which database file is to be created
561          * @param databaseName name with which this file is to be created
562          * @return Persistent database created
563          *
564          * @throws DException if Databasefile is either removed or deleted from path.
565          */

566
567     private _Database getDatabase(Object JavaDoc[] databaseProps, String JavaDoc databaseName,PersistentDatabase systemDatabase ) throws DException{
568         Object JavaDoc[] databaseProperties = Utility.convertIntoFieldBase(databaseProps);
569         String JavaDoc path = daffodilHome + File.separator +databaseName + File.separator + databaseName + ".ddb";
570         long size = getInitialSize((String JavaDoc)databaseProperties[1]);
571         int incrementFactor = databaseProperties[4].hashCode();
572         boolean multiFilesSupport = ((Boolean JavaDoc)databaseProperties[6]).booleanValue();
573         String JavaDoc encrytpioAlgo = (String JavaDoc)databaseProperties[8];
574         String JavaDoc encryptionKey = (String JavaDoc)databaseProperties[9];
575         int clusterSize = getClusterSize((String JavaDoc)databaseProperties[10]);
576         System.out.println("Cluster size "+clusterSize);
577         _Database pd = null;
578
579       try {
580          File ff = new File(daffodilHome, databaseName);
581          if (!ff.getName().equals(databaseName))
582             throw new DException("DSE2049", new Object JavaDoc[] {databaseName});
583          ff = new File(path);
584          File ff1 = ff.getParentFile();
585          RandomAccessFile file = null;
586          if (isReadOnlyMode) {
587             file = new RandomAccessFile(new File(path), "r");
588          } else {
589             file = new RandomAccessFile(new File(path), "rw");
590          }
591          if (ff.length() == 0) {
592             System.out.println("Database Path::::::: " + path);
593             file.close();
594             ff.delete();
595             ff1.delete();
596             throw new DException("DSE5539", new Object JavaDoc[] {databaseName});
597          }
598          EDBlockCipher bolckEDDes3Cipher = initializeEncrytpionInfo(encrytpioAlgo, encryptionKey);
599          VersionHandler versionHandler = VersionHandlerFactory.getVersionHandler(file);
600          versionHandler.setClusterSize(clusterSize);
601          DRandomAccessFileUpto3_2 dRandomAccessFile = bolckEDDes3Cipher != null ? versionHandler.getEncryptDRandomAccessFile(file, size, path, incrementFactor, multiFilesSupport, new FileGenerator(systemDatabase), bolckEDDes3Cipher, clusterSize)
602              : versionHandler.getDRandomAccessFile(file, size, path, incrementFactor, multiFilesSupport, new FileGenerator(systemDatabase),clusterSize);
603
604          pd = new PersistentDatabase(dRandomAccessFile, databaseName, versionHandler, daffodilHome, isReadOnlyMode);
605       } catch (IOException io) {
606          throw new DException("DSE2025", new Object JavaDoc[] {io.getMessage()});
607       }
608       databaseMap.put(databaseName, pd);
609       return pd;
610    }
611
612    /**
613     * Returns cluster size in bytes if any exception occurs than it returns default as 16384 bytes.
614     * @param clusterSize String
615     * @return int
616     */

617    public int getClusterSize(String JavaDoc clusterSize) throws DException{
618      int size = 0;
619       try {
620             size = Integer.parseInt(clusterSize.trim());
621
622       } catch (Exception JavaDoc ex) {
623          ex.printStackTrace();
624          return 8192;
625       }
626       if(size < 4096 || size > 32768){
627             System.out.println(" size ="+size);
628             throw new DException("DSE2031", null);
629           }
630        return size;
631
632    }
633
634    /**
635     * is refered to by dropDatabase(string)method
636     * Removes database from map and all stored information related to this database name from
637     * databaseInfo System Table and all Random Access files of this database
638     *
639     * @param databaseName name of database which has to drop
640     *
641     * @throws DException if database is used by another user or database with this name does not exist
642     */

643
644    private void dropDatabase(DatabaseUserTableIterator databaseTableIteartor, String JavaDoc databaseName, _Database database) throws DException {
645       ArrayList list = new ArrayList();
646       list.add(SystemTables.DATABASEINFO);
647       list.add(SystemTables.SCHEDULEINFO);
648       _DatabaseUser user = database.getDatabaseUser(list);
649       try {
650          ( (_UserTableOperations) databaseTableIteartor).delete(user);
651          if ( ( (PersistentDatabase) database).getVersionHandler().getDbVersion() > 3.2)
652             deleteFiles(databaseName, user);
653          else
654             deleteFilesForOlderVersions(databaseName, user);
655          databaseMap.remove(databaseName);
656          user.writeToFile();
657       } finally {
658          user.releaseCluster();
659       }
660
661    }
662
663    /**
664     * To filter power file's of databade.
665     * <p>Title: </p>
666     * <p>Description: </p>
667     * <p>Copyright: Copyright (c) 2003</p>
668     * <p>Company: </p>
669     * @author not attributable
670     * @version 1.0
671     */

672
673 static class PowerFileFilter implements FilenameFilter {
674       public boolean accept(File dir, String JavaDoc name) {
675          return name.endsWith("PowerFile.log") ? true
676              : false;
677       }
678    }
679
680    /**
681     * To store data base version in database file.
682     *
683     * @param file RandomAccessFile
684     * @param databaseVersion String
685     * @throws DException
686     */

687    private void putDatabaseVersion(RandomAccessFile file,String JavaDoc databaseVersion) throws DException {
688       try {
689          file.seek(VERSIONCODE);
690          file.writeBytes(databaseVersion);
691       } catch (IOException ex) {
692          throw new DException("DSE0", new Object JavaDoc[] {ex.getMessage()});
693       }
694    }
695
696    /**
697     * To update path of database while a user changes its home.
698     * @param path String
699     */

700    public void changeHome(String JavaDoc path) {
701       daffodilHome = path;
702
703    }
704
705    /**
706     * deletes all the .ddb files, temp file, power files and in case of MULTIFILESUPPORT
707     * deletes all the .dat files present corresponding to a database
708     *
709     */

710
711    private void deleteFilesForOlderVersions(String JavaDoc databaseName, _DatabaseUser user) throws DException {
712       int index = getIndex(databaseName, user);
713       String JavaDoc path = daffodilHome + File.separator + databaseName + File.separator + databaseName + ".ddb";
714       File f = new File(path);
715       f.delete();
716       File ff1 = f.getParentFile();
717       File[] files = ff1.listFiles(new PowerFileFilter());
718       if (files != null)
719          for (int i = 0; i < files.length; i++) {
720             files[i].delete();
721          }
722
723       String JavaDoc str = f.getName();
724       str = str.substring(0, str.lastIndexOf("."));
725       File ff = new File(ff1, str + "_tempFile.swp");
726       ff.delete();
727       for (int i = 1; i < index; i++) {
728          path = daffodilHome + File.separator + databaseName + File.separator + databaseName + i + ".dat";
729          f = new File(path);
730          f.delete();
731       }
732       ff1.delete();
733    }
734    /*
735
736    private void checkDatabaseVersion(RandomAccessFile file) throws DException {
737       try {
738          file.seek(VERSIONCODE);
739          byte[] bytes = new byte[DatabaseConstants.DATABASEVERSION.length()];
740          file.read(bytes);
741          String str = new String(bytes);
742          if (!DatabaseConstants.DATABASEVERSION.equalsIgnoreCase(str)) {
743             throw new DException("DSE2046", null);
744          }
745       } catch (IOException ex) {
746          throw new DException("DSE0", new Object[] {ex.getMessage()});
747
748       }
749    }
750
751        */

752 }
753
Popular Tags