KickJava   Java API By Example, From Geeks To Geeks.

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


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

87
88    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 {
89        try{
90
91          String JavaDoc path = destination + File.separator +databaseName + File.separator + databaseName + ".ddb";
92            File ff = new File(path);
93            File ff1 = ff.getParentFile();
94            ff1.mkdirs();
95            RandomAccessFile file = new RandomAccessFile(new File(path),"rw");
96            long size = getInitialSize(initialSize);
97            _Database database = getDatabase(DatabaseConstants.SYSTEMDATABASE);
98            _DataTable databaseInfoTable = (_DataTable)database.getTable(SystemTables.DATABASEINFO);
99            DatabaseUserTableIterator databaseTableIteartor = (DatabaseUserTableIterator)databaseInfoTable.getIterator();
100            _TableCharacteristics tableCharacteristics = databaseInfoTable.getTableCharacteristics();
101            BufferRange bytesOfDatabaseName = new BufferRange(CCzufDpowfsufs.getBytes(databaseName,databaseName.length(),false));
102                if(databaseTableIteartor.first()){
103                do{
104                    BufferRange bytesGot = (BufferRange)databaseTableIteartor.getColumnValues(0);
105                    if(stringComparator.compare(bytesGot,bytesOfDatabaseName) == 0){
106                        if(ff.exists() && ff.length() == 0 ){
107                            file.close();
108                            throw new DException("DSE5579",new Object JavaDoc[]{destination}); //Removed from path
109
}
110                        else{
111                            file.close();
112                            throw new DException("DSE314",new Object JavaDoc[] {databaseName});//Database already exists
113
}
114                    }
115                }while(databaseTableIteartor.next());
116            }
117            ArrayList list = new ArrayList();
118            list.add(SystemTables.DATABASEINFO);
119            _DatabaseUser user = database.getDatabaseUser(list);
120            try{
121
122                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};
123                BufferRange[] bytes = Utility.convertIntoBufferRange(tableCharacteristics.getColumnTypes(),value,tableCharacteristics.getCollator());
124                ((_UserTableOperations)databaseTableIteartor).insert(user,bytes);
125
126                user.writeToFile();
127                file.setLength(size);
128            }
129            catch(Exception JavaDoc ex) {
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(DatabaseConstants.SYSTEMDATABASE.equalsIgnoreCase(databaseName))
159            return getSystemDatabase();
160        PersistentDatabase database = (PersistentDatabase)getDatabase(DatabaseConstants.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(DatabaseConstants.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     try {
206       _DataTable scheduleInfoTable = (_DataTable) database.getTable(
207           SystemTables.SCHEDULEINFO);
208       DatabaseUserTableIterator scheduleInfoTableIteartor = (
209           DatabaseUserTableIterator) scheduleInfoTable.getIterator();
210       if (scheduleInfoTableIteartor.first()) {
211         do {
212           BufferRange bytesGot = (BufferRange) scheduleInfoTableIteartor.
213               getColumnValues(0);
214           if (stringComparator.compare(bytesGot, bytesOfDatabaseName) == 0) {
215             dropDatabase(scheduleInfoTableIteartor, databaseName, database);
216           }
217         }
218         while (scheduleInfoTableIteartor.next());
219       }
220     }
221     catch (DException ex) {
222       if (!ex.getDseCode().equalsIgnoreCase("DSE959"))
223           throw ex;
224     }
225     if(!found)
226       throw new DException("DSE316",new Object JavaDoc[] {databaseName});
227    }
228
229
230    private _Database getSystemDatabase() throws DException{
231      String JavaDoc path = destination + File.separator +DatabaseConstants.SYSTEMDATABASE+ File.separator + DatabaseConstants.SYSTEMDATABASE + ".ddb";
232        long size = getInitialSize(DatabaseConstants.INITIALFILESIZE);
233        _Database pd = null;
234
235        try{
236            File ff = new File(path);
237            File ff1 = ff.getParentFile();
238            ff1.mkdirs();
239            RandomAccessFile file = new RandomAccessFile(new File(path),"rw");
240            if (ff.length() == 0) {
241          ;//// Removed By Program ** System.out.println("Database Path::::::: " + path);
242
file.close();
243              ff.delete();
244              ff1.delete();
245              throw new DException("DSE5579", new Object JavaDoc[] {path});
246            }
247
248            EDBlockCipher bolckEDDes3Cipher = null;//initializeEncrytpionInfo(NONE,null);
249

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

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

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

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

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

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

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