001 /* 002 @license.text@ 003 */ 004 package biz.hammurapi.sql.hypersonic; 005 006 import java.io.File; 007 import java.io.IOException; 008 import java.io.InputStream; 009 import java.io.InputStreamReader; 010 import java.io.Reader; 011 import java.sql.SQLException; 012 import java.text.SimpleDateFormat; 013 import java.util.Date; 014 015 016 /** 017 * Hypersonic temporary data source. It is similar to standalone datasource, but 018 * data files are created in system temporary directory and are scheduled to deletion 019 * on JVM exit. Use this datasource if you need to keep large amount of temporary data, 020 * for example data pumping applications can benefit from such data source. 021 * @author Pavel Vlasov 022 * @version $Revision: 1.6 $ 023 */ 024 public class HypersonicTmpDataSource extends HypersonicDataSource { 025 026 /** 027 * @param initScript Fully qualified name of database initialization script to be loaded by 028 * classloader. Can be null. 029 * @throws ClassNotFoundException 030 * @throws IOException 031 * @throws SQLException 032 */ 033 public HypersonicTmpDataSource(Reader scriptReader) throws ClassNotFoundException, IOException, SQLException { 034 super("jdbc:hsqldb:"+createTmpDir(), "sa", "", null); 035 initDB(scriptReader, null); 036 } 037 038 /** 039 * @param initScript Fully qualified name of database initialization script to be loaded by 040 * classloader. Can be null. 041 * @throws ClassNotFoundException 042 * @throws IOException 043 * @throws SQLException 044 */ 045 public HypersonicTmpDataSource(String initScript) throws ClassNotFoundException, IOException, SQLException { 046 super("jdbc:hsqldb:"+createTmpDir(), "sa", "", null); 047 InputStream in = getClass().getClassLoader().getResourceAsStream(initScript); 048 if (in==null) { 049 throw new IOException("Resource not found: "+initScript); 050 } 051 initDB(new InputStreamReader(in), null); 052 } 053 054 private static String createTmpDir() throws IOException { 055 String tmpDir=System.getProperty("java.io.tmpdir"); 056 SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss"); 057 String prefix = "HypersonicDB_"+sdf.format(new Date())+"_"; 058 String suffix = "_TMP"; 059 final File tmpDbDir = tmpDir==null ? File.createTempFile(prefix, suffix) : File.createTempFile(prefix, suffix, new File(tmpDir)); 060 if (tmpDbDir.delete()) { 061 if (tmpDbDir.mkdirs()) { 062 Runtime.getRuntime().addShutdownHook( new Thread() { 063 public void run() { 064 065 File[] dbFiles=tmpDbDir.listFiles(); 066 for (int i=0; i<dbFiles.length; i++) { 067 dbFiles[i].deleteOnExit(); 068 } 069 070 tmpDbDir.deleteOnExit(); 071 } 072 }); 073 return tmpDbDir.getAbsolutePath()+File.separator+"HypersonicTmpDB"; 074 } 075 throw new IOException("Cannot create directory "+tmpDbDir.getAbsolutePath()); 076 } 077 throw new IOException("Cannot delete file "+tmpDbDir.getAbsolutePath()); 078 } 079 }