KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > daffodilwoods > daffodildb > server > backup > BackupPersistentSystem


1 package com.daffodilwoods.daffodildb.server.backup;
2
3
4 import java.io.*;
5 import java.util.*;
6 import com.daffodilwoods.database.resource.*;
7 import com.daffodilwoods.database.general.*;
8 import com.daffodilwoods.daffodildb.server.datasystem.interfaces.*;
9 import com.daffodilwoods.daffodildb.server.serversystem.ServerSystem;
10 import com.daffodilwoods.daffodildb.server.datadictionarysystem.*;
11 import com.daffodilwoods.daffodildb.utils.byteconverter.*;
12 import com.daffodilwoods.database.utility.P;
13 import com.daffodilwoods.daffodildb.server.sql99.utils._Reference;
14 import com.daffodilwoods.daffodildb.server.datasystem.encryptdecrypt.*;
15 import com.daffodilwoods.daffodildb.utils.comparator.CTusjohJoTfotjujwfDpnqbsbups;
16 import com.daffodilwoods.daffodildb.utils.BufferRange;
17 import com.daffodilwoods.daffodildb.utils.field.FieldBase;
18 import com.daffodilwoods.daffodildb.server.datasystem.persistentsystem.DatabaseUserTableIterator;
19 import com.daffodilwoods.daffodildb.server.datasystem.persistentsystem.DatabaseConstants;
20 import com.daffodilwoods.daffodildb.server.datasystem.persistentsystem.PersistentDatabase;
21 import com.daffodilwoods.daffodildb.server.datasystem.persistentsystem.DatabaseProperties;
22 import com.daffodilwoods.daffodildb.server.datasystem.persistentsystem.DRandomAccessFile;
23 import com.daffodilwoods.daffodildb.server.datasystem.persistentsystem.EncryptDRandomAccessFile;
24 import com.daffodilwoods.daffodildb.server.datasystem.persistentsystem.FileGenerator;
25 import com.daffodilwoods.daffodildb.server.datasystem.persistentsystem.versioninfo.VersionHandler;
26 import com.daffodilwoods.daffodildb.server.datasystem.persistentsystem.versioninfo.VersionHandlerFactory;
27 import com.daffodilwoods.daffodildb.server.datasystem.persistentsystem.DRandomAccessFileUpto3_2;
28
29 /**
30  *
31  * <p>Title: Persistent System</p>
32  * <p>Description: It manages all the databases related to the DaffodilDB server with the help of
33  * <tt>SYSTEM DATABASE</tt> ,which is the master database in DaffodilDB.It controls all the database
34  * level operations like creating a new database,removing a database etc.It also maintains,
35  * currently used databases list. </p>
36  */

37 public class BackupPersistentSystem {
38
39   /**
40    * Maintains list of all databases which are Currently in use having mapping with Database name
41    */

42
43   private HashMap databaseMap;
44
45   /**
46    * To compare databaseName
47    */

48
49   private CTusjohJoTfotjujwfDpnqbsbups stringComparator;
50
51   /**
52    * Path Of DaffodilDBHome where all the databases reside.
53    */

54
55
56 /**
57  * To calculate memory used by database
58  */

59
60   private _MemoryManager mananger ;
61
62   private String JavaDoc destination;
63   private String JavaDoc SYSTEMDATABASE = DatabaseConstants.SYSTEMDATABASE+"_Bk";
64   private boolean isReadOnlyMode = false;
65
66   public BackupPersistentSystem(String JavaDoc destination0) {
67     destination = destination0;
68
69     databaseMap = new HashMap();
70     stringComparator = new CTusjohJoTfotjujwfDpnqbsbups();
71   }
72
73
74   /**
75    * Store All the information of new database in SYSTEM DATABASE which user wants to create and
76    * creates a new file for new database at daffodilDBHome.
77    *
78    * initializes the bytes of first cluster by seeking to the 0th position
79    * and initializing it upto clusterSize (For Windows 98)
80    *
81    * @param databaseName Name of Database
82    * @param initialSize initial Size of Database
83    * @param incrementFactor Factor by which database size would be increased when Existing file is fully used
84    * @param unicodeSupport Whether unicode support is required or not
85    * @param multifileSupport Whether new files should be created or old file size has to increase in case of existing file is fully used
86    *
87    * @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
88    */

89
90   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 {
91     try{
92
93       String JavaDoc path = destination + File.separator +databaseName + File.separator + databaseName + ".ddb";
94       File ff = new File(path);
95       File ff1 = ff.getParentFile();
96       ff1.mkdirs();
97       RandomAccessFile file = new RandomAccessFile(new File(path),"rw");
98       long size = getInitialSize(initialSize);
99       _Database database = getDatabase(SYSTEMDATABASE);
100       _DataTable databaseInfoTable = (_DataTable)database.getTable(SystemTables.DATABASEINFO);
101       DatabaseUserTableIterator databaseTableIteartor = (DatabaseUserTableIterator)databaseInfoTable.getIterator();
102       _TableCharacteristics tableCharacteristics = databaseInfoTable.getTableCharacteristics();
103       BufferRange bytesOfDatabaseName = new BufferRange(CCzufDpowfsufs.getBytes(databaseName,databaseName.length(),false));
104       if(databaseTableIteartor.first()){
105         do{
106           BufferRange bytesGot = (BufferRange)databaseTableIteartor.getColumnValues(0);
107           if(stringComparator.compare(bytesGot,bytesOfDatabaseName) == 0){
108             if(ff.exists() && ff.length() == 0 ){
109               file.close();
110               throw new DException("DSE5579",new Object JavaDoc[]{destination}); //Removed from path
111
}
112             else{
113               file.close();
114               throw new DException("DSE314",new Object JavaDoc[] {databaseName});//Database already exists
115
}
116           }
117         }while(databaseTableIteartor.next());
118       }
119       ArrayList list = new ArrayList();
120       list.add(SystemTables.DATABASEINFO);
121       _DatabaseUser user = database.getDatabaseUser(list);
122       try{
123
124         Object JavaDoc[] value = new Object JavaDoc[] {databaseName,initialSize,DatabaseConstants.DATABASEVERSION, new Integer JavaDoc(DatabaseConstants.DATABASECODE),new Integer JavaDoc(incrementFactor),new Boolean JavaDoc(unicodeSupport),new Boolean JavaDoc(multifileSupport),new Boolean JavaDoc(encryptionSupport),encryptionAlgo,encryptionKey,clusterSize};
125         BufferRange[] bytes = Utility.convertIntoBufferRange(tableCharacteristics.getColumnTypes(),value,tableCharacteristics.getCollator());
126         ((_UserTableOperations)databaseTableIteartor).insert(user,bytes);
127
128         user.writeToFile();
129
130       }
131       finally{
132         user.releaseCluster();
133         file.close();
134       }
135     }
136     catch(IOException io) {
137       throw new DException("DSE2025",new Object JavaDoc[] {io.getMessage()});
138     }
139   }
140
141
142   /**
143    * Returns database corresponding to databaseName.If gets database from map returns it
144    * otherwise Gets all the Properties of database from DataBaseInfo System Table, makes database file with its
145    * initial size, Makes database instance and puts its entry in databaseMap having Mapping with
146    * databaseName.
147    *
148    * @param databaseName name of database
149    * @return database corresponding to databaseName
150    *
151    * @throws DException if database does not exist
152    * */

153
154   public synchronized _Database getDatabase(String JavaDoc databaseName)throws DException{
155     _Database pd = (_Database)databaseMap.get(databaseName);
156     if(pd != null)
157       return pd;
158     if(SYSTEMDATABASE.equalsIgnoreCase(databaseName))
159       return getSystemDatabase();
160     PersistentDatabase database = (PersistentDatabase)getDatabase(SYSTEMDATABASE);
161     _DataTable databaseInfoTable = (_DataTable)database.getTable(SystemTables.DATABASEINFO);
162     DatabaseUserTableIterator databaseTableIteartor = (DatabaseUserTableIterator)databaseInfoTable.getIterator();
163     Object JavaDoc[] databaseProperties = null;
164     BufferRange bytesOfDatabaseName = new BufferRange(CCzufDpowfsufs.getBytes(databaseName,databaseName.length(),false));
165     if(databaseTableIteartor.first())
166       do{
167       BufferRange[] bytesGot = (BufferRange[])databaseTableIteartor.getColumnValues();
168       if(stringComparator.compare(bytesGot[0],bytesOfDatabaseName) == 0){
169         _TableCharacteristics tableCharacteristics = databaseInfoTable.getTableCharacteristics();
170         databaseProperties = (Object JavaDoc[])tableCharacteristics.getObject(bytesGot);
171         return getDatabase(databaseProperties,databaseName,database);
172       }
173     }while(databaseTableIteartor.next());
174     throw new DException("DSE316",new Object JavaDoc[] {databaseName});//Database doesn't exist
175
}
176
177   /**
178    * first check the entry in the databaseMap if it exists there then throws exception
179    * DATABASE_LOCKED_EXCEPTION
180    * if enrty is not there in databaseMap then gets database iterator on DATABASEINFO System Table and iterates till the entry
181    * for the database is found in this table and then gives call to dropDatabase(databaseTableIteartor,databaseName,database) method
182    *
183    * @param databaseName name of database which has to be dropped
184    *
185    * @throws DException if database is used by another user or database with this name does not exist
186    */

187
188   public synchronized void dropDatabase(String JavaDoc databaseName) throws DException{
189     PersistentDatabase pd = (PersistentDatabase)databaseMap.get(databaseName);
190     if(pd != null)
191       throw DatabaseConstants.DATABASE_LOCKED_EXCEPTION;
192     _Database database = getDatabase(SYSTEMDATABASE);
193     DatabaseUserTableIterator databaseTableIteartor = (DatabaseUserTableIterator)((_DataTable)database.getTable(SystemTables.DATABASEINFO)).getIterator();
194     BufferRange bytesOfDatabaseName = new BufferRange(CCzufDpowfsufs.getBytes(databaseName,databaseName.length(),false));
195     boolean found = false;
196     if(databaseTableIteartor.first())
197       do{
198       BufferRange bytesGot = (BufferRange)databaseTableIteartor.getColumnValues(0);
199       if(stringComparator.compare(bytesGot,bytesOfDatabaseName) == 0){
200         dropDatabase(databaseTableIteartor,databaseName,database);
201         found = true;
202         break;
203       }
204     }while(databaseTableIteartor.next());
205
206       try {
207         _DataTable scheduleInfoTable = (_DataTable) database.getTable(
208             SystemTables.SCHEDULEINFO);
209         DatabaseUserTableIterator scheduleInfoTableIteartor = (
210             DatabaseUserTableIterator) scheduleInfoTable.getIterator();
211         if (scheduleInfoTableIteartor.first()) {
212           do {
213             BufferRange bytesGot = (BufferRange) scheduleInfoTableIteartor.
214                                    getColumnValues(0);
215             if (stringComparator.compare(bytesGot, bytesOfDatabaseName) == 0) {
216               dropDatabase(scheduleInfoTableIteartor, databaseName, database);
217             }
218           }
219           while (scheduleInfoTableIteartor.next());
220         }
221       }
222       catch (DException ex) {
223         if (!ex.getDseCode().equalsIgnoreCase("DSE959"))
224           throw ex;
225       }
226
227       if (!found) {
228         throw new DException("DSE316", new Object JavaDoc[] {databaseName});
229       }
230
231   }
232
233
234   private _Database getSystemDatabase() throws DException{
235     String JavaDoc path = destination + File.separator +SYSTEMDATABASE+ File.separator + DatabaseConstants.SYSTEMDATABASE + ".ddb";
236     long size = getInitialSize(DatabaseConstants.INITIALFILESIZE);
237     _Database pd = null;
238
239     try{
240       File ff = new File(path);
241       File ff1 = ff.getParentFile();
242       ff1.mkdirs();
243       RandomAccessFile file = new RandomAccessFile(new File(path),"rw");
244       if (ff.length() == 0) {
245          ;//// Removed By Program ** System.out.println("Database Path::::::: " + path);
246
file.close();
247         ff.delete();
248         ff1.delete();
249         throw new DException("DSE5579", new Object JavaDoc[] {path});
250      }
251
252       EDBlockCipher bolckEDDes3Cipher = null;//initializeEncrytpionInfo(NONE,null);
253

254       VersionHandler versionHandler =VersionHandlerFactory.getVersionHandler(file);
255       int clusterSize = getClusterSize(versionHandler.getDefaultClusterSize() );
256       versionHandler.setClusterSize(clusterSize);
257       DRandomAccessFileUpto3_2 dRandomAccessFile = bolckEDDes3Cipher != null ? versionHandler.getEncryptDRandomAccessFile(file,size,path,20,false,null,bolckEDDes3Cipher,clusterSize)
258           : versionHandler.getDRandomAccessFile(file,size,path,20,false,null,clusterSize);
259       pd = new PersistentDatabase(dRandomAccessFile,DatabaseConstants.SYSTEMDATABASE,versionHandler,destination,isReadOnlyMode);
260     }
261     catch(IOException io){
262       throw new DException("DSE2025",new Object JavaDoc[] {io.getMessage()});
263     }
264     databaseMap.put(SYSTEMDATABASE.toLowerCase(),pd);
265     return pd;
266   }
267
268   /**
269    * Gets all the property of database from specified Properties and creates database
270    *
271    * @param databaseName Name of database
272    * @param prop Properties of database
273    * @throws DException if database already Exists
274    */

275
276   private long getInitialSize(String JavaDoc initialSize) throws DException{
277     initialSize = initialSize == null ? DatabaseConstants.INITIALFILESIZE : initialSize.trim().toUpperCase();
278     long size = 0;
279     try {
280       if(initialSize.endsWith("M") || initialSize.endsWith("MB") ){
281         int index = initialSize.indexOf("M");
282         size = Long.parseLong(initialSize.substring(0,index).trim())*1024*1024;
283       }
284       else if(initialSize.endsWith("G") || initialSize.endsWith("GB") ){
285         int index = initialSize.indexOf("G");
286         size = Long.parseLong(initialSize.substring(0,index).trim())*1024*1024*1024;
287       }
288       else if(initialSize.endsWith("K") || initialSize.endsWith("KB") ){
289         int index = initialSize.indexOf("K");
290         size = Long.parseLong(initialSize.substring(0,index).trim())*1024;
291       }
292       else{
293         size = Long.parseLong(initialSize.trim())*1024*1024;
294       }
295     }
296     catch(NumberFormatException JavaDoc ex) {
297       int index = initialSize.indexOf("M");
298       size = Long.parseLong(initialSize.substring(0,index).trim())*1024*1024;
299     }
300     if(size < 1024*1024){
301       size = 5*1024*1024;
302     }
303     return size;
304   }
305
306   /**
307    * removes database entry form databaseMap
308    *
309    */

310
311   public void removeDatabase(String JavaDoc databaseName)throws DException{
312     PersistentDatabase ps = (PersistentDatabase)databaseMap.get(databaseName);
313     if(ps != null)
314       ps.closeFile();
315     databaseMap.remove(databaseName);
316   }
317
318   /**
319    * deletes all the .ddb files, temp file, power files and in case of MULTIFILESUPPORT
320    * deletes all the .dat files present corresponding to a database
321    *
322    */

323
324   private void deleteFiles(String JavaDoc databaseName,_DatabaseUser user)throws DException{
325     int index = getIndex(databaseName,user);
326     String JavaDoc path = destination + File.separator +databaseName + File.separator + databaseName + ".ddb";
327     File f = new File(path);
328     f.delete();
329     File ff1 = f.getParentFile();
330     File [] files = ff1.listFiles(new PowerFileFilter());
331     if(files != null)
332       for (int i = 0; i < files.length; i++) {
333     boolean b = files[i].delete();
334       }
335
336       if(index != -1){
337         files = ff1.listFiles(new MultiFileFilter());
338         if(files != null)
339           for (int i = 0; i < files.length; i++) {
340         files[i].delete();
341           }
342       }
343       files = ff1.listFiles();
344       if(files!=null)
345         for (int i = 0; i < files.length; i++) {
346       if(files[i].getName().endsWith(".swp"))
347         files[i].delete();
348         }
349
350         ff1.delete();
351   }
352
353   /**
354    * returns the number of files created in case of MULTIFILESUPPORT property set to true
355    * else returns -1
356    *
357    */

358
359   private int getIndex(String JavaDoc databaseName,_DatabaseUser user) throws DException{
360     _Database database = getDatabase(SYSTEMDATABASE);
361     DatabaseUserTableIterator iterator = (DatabaseUserTableIterator)((_DataTable)database.getTable(SystemTables.DATABASEFILEINFO)).getIterator();
362     BufferRange bytesOfDatabaseName = new BufferRange(CCzufDpowfsufs.getBytes(databaseName,databaseName.length(),false));
363     if(iterator.first()){
364       do{
365         BufferRange[] values = (BufferRange[])iterator.getColumnValues();
366         if(stringComparator.compare(values[0],bytesOfDatabaseName) == 0){
367           iterator.delete(user);
368           return CCzufDpowfsufs.getInt(values[1].getBytes()).hashCode();
369         }
370       }while(iterator.next());
371     }
372     return -1;
373   }
374
375   private EDBlockCipher initializeEncrytpionInfo(String JavaDoc algo,String JavaDoc key) throws DException{
376     String JavaDoc s1 = key;
377     String JavaDoc s2 = algo;
378     EDBlockCipher m_EDBlockEDDes3Cipher = null;
379     if(!s2.equalsIgnoreCase(DatabaseConstants.NONE))
380       m_EDBlockEDDes3Cipher = EDUtils.getEncryptDecryptCipher(s2, s1);
381     return m_EDBlockEDDes3Cipher;
382   }
383
384   /**
385    * is referred by getDatabase(String) method
386    * makes database file with its initial size, makes database instance
387    * and puts its entry in databaseMap having Mapping with databaseName.
388    *
389    * @param databaseProps properties of database for which database file is to be created
390    * @param databaseName name with which this file is to be created
391    * @return Persistent database created
392    *
393    * @throws DException if Databasefile is either removed or deleted from path.
394    */

395
396   private _Database getDatabase(Object JavaDoc[] databaseProps, String JavaDoc databaseName,PersistentDatabase systemDatabase ) throws DException{
397     Object JavaDoc[] databaseProperties = Utility.convertIntoFieldBase(databaseProps);
398     String JavaDoc path = destination + File.separator +databaseName+"_Bk" + File.separator + databaseName + ".ddb";
399     String JavaDoc initialSize = (String JavaDoc)databaseProperties[1];
400     long size = getInitialSize(initialSize);
401     int incrementFactor = databaseProperties[4].hashCode();
402     boolean unicodeSupport = ((Boolean JavaDoc)databaseProperties[5]).booleanValue();
403     boolean multiFilesSupport = ((Boolean JavaDoc)databaseProperties[6]).booleanValue();
404     String JavaDoc encrytpioAlgo = (String JavaDoc)databaseProperties[8];
405     String JavaDoc encryptionKey = (String JavaDoc)databaseProperties[9];
406     int clusterSize = getClusterSize((String JavaDoc)databaseProperties[10]);
407     if(clusterSize < 4096 || clusterSize > 32768)
408       throw new DException("DSE2031",null);
409     _Database pd = null;
410     try{
411       File ff = new File(path);
412       File ff1 = ff.getParentFile();
413       ff1.mkdirs();
414       RandomAccessFile file = new RandomAccessFile(new File(path),"rw");
415       if(ff.length() == 0){
416          ;//// Removed By Program ** System.out.println("Database Path::::::: "+path);
417
file.close();
418         ff.delete();
419         ff1.delete();
420         throw new DException("DSE5579",new Object JavaDoc[]{destination});
421       }
422       EDBlockCipher bolckEDDes3Cipher = initializeEncrytpionInfo(encrytpioAlgo,encryptionKey);
423
424       VersionHandler versionHandler =VersionHandlerFactory.getVersionHandler(file);
425       versionHandler.setClusterSize(clusterSize);
426       DRandomAccessFileUpto3_2 dRandomAccessFile = bolckEDDes3Cipher != null ? versionHandler.getEncryptDRandomAccessFile(file,size,path,incrementFactor, multiFilesSupport,new FileGenerator(systemDatabase),bolckEDDes3Cipher,clusterSize)
427           : versionHandler.getDRandomAccessFile(file,size,path,incrementFactor, multiFilesSupport,new FileGenerator(systemDatabase),clusterSize);
428       pd = new PersistentDatabase(dRandomAccessFile,databaseName,versionHandler,destination,isReadOnlyMode);
429     }
430     catch(IOException io){
431       throw new DException("DSE2025",new Object JavaDoc[] {io.getMessage()});
432     }
433     databaseMap.put(databaseName,pd);
434     return pd;
435   }
436
437   public int getClusterSize(String JavaDoc clusterSize) {
438     try {
439       int size = Integer.parseInt(clusterSize.trim());
440       return size;
441     }
442     catch (Exception JavaDoc ex) {
443       return 16384;
444     }
445   }
446
447   /**
448    * is refered to by dropDatabase(string)method
449    * Removes database from map and all stored information related to this database name from
450    * databaseInfo System Table and all Random Access files of this database
451    *
452    * @param databaseName name of database which has to drop
453    *
454    * @throws DException if database is used by another user or database with this name does not exist
455    */

456
457   private void dropDatabase(DatabaseUserTableIterator databaseTableIteartor,String JavaDoc databaseName,_Database database ) throws DException{
458     ArrayList list = new ArrayList();
459     list.add(SystemTables.DATABASEINFO);
460     list.add(SystemTables.SCHEDULEINFO);
461     _DatabaseUser user = database.getDatabaseUser(list);
462     try{
463       ((_UserTableOperations)databaseTableIteartor).delete(user);
464       deleteFiles(databaseName,user);
465       databaseMap.remove(databaseName);
466       user.writeToFile();
467     }
468     finally{
469       user.releaseCluster();
470     }
471
472   }
473
474   private void checkDatabaseVersion(RandomAccessFile file) throws DException{
475     try {
476       file.seek(DatabaseConstants.VERSIONCODE);
477       byte[] bytes = new byte[DatabaseConstants.DATABASEVERSION.length()];
478       file.read(bytes);
479       String JavaDoc str = new String JavaDoc(bytes);
480       if(!DatabaseConstants.DATABASEVERSION.equalsIgnoreCase(str) ){
481         throw new DException("DSE2046", null);
482       }
483     }
484     catch (IOException ex) {
485       throw new DException("DSE0",new Object JavaDoc[] {ex.getMessage()});
486
487     }
488   }
489   class PowerFileFilter implements FilenameFilter {
490     public boolean accept(File dir, String JavaDoc name){
491       return name.endsWith("PowerFile.log")? true
492       : false;
493     }
494   }
495
496   class MultiFileFilter
497       implements FilenameFilter {
498     public boolean accept(File dir, String JavaDoc name) {
499       return name.endsWith(".dat") ? true
500       : false;
501     }
502   }
503
504 }
505
Popular Tags