View Javadoc

1   /* (c) Copyright 2003 Caleigo AB, All rights reserved. 
2    * 
3    * This library is free software; you can redistribute it and/or
4    * modify it under the terms of the GNU Lesser General Public
5    * License as published by the Free Software Foundation; either
6    * version 2.1 of the License, or (at your option) any later version.
7    * 
8    * This library is distributed in the hope that it will be useful,
9    * but WITHOUT ANY WARRANTY; without even the implied warranty of
10   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11   * Lesser General Public License for more details.
12   * 
13   * You should have received a copy of the GNU Lesser General Public
14   * License along with this library; if not, write to the Free Software
15   * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16   *  
17   */
18  package org.caleigo.core.service;
19  
20  import java.io.*;
21  import java.io.BufferedReader;
22  import java.io.IOException;
23  import java.io.InputStream;
24  import java.io.InputStreamReader;
25  import java.io.Reader;
26  import java.net.URL;
27  import java.sql.Connection;
28  import java.sql.SQLException;
29  import java.sql.Statement;
30  import java.util.ArrayList;
31  import java.util.Iterator;
32  
33  import org.caleigo.core.*;
34  import org.caleigo.toolkit.log.Log;
35  
36  
37  
38  /***
39   * @author Klas Ehnrot
40   *
41   * DataService used only for Demo databases that is read from a URL, and put into Memory
42   */
43  public class DemoDataService extends JDBCDataService
44  {
45      // Static methods ----------------------------------------------------------
46      static
47      {
48          try
49          {
50              // Load the hsqldb driver
51              Class.forName("org.hsqldb.jdbcDriver");
52          } catch (ClassNotFoundException e)
53          {
54              Log.printError(null, "Failed to load hsqldb driver", e);
55          }
56      }
57      
58      // Costructors -------------------------------------------------------------
59  
60      /***
61       * Creates empty Demo Database
62       * 
63       * @param descriptor descriptor
64       */
65      public DemoDataService(IDataSourceDescriptor descriptor)
66      {
67          super(descriptor);
68      }
69  
70      /***
71       * Creates the Demo Database and copy data from the supplied URL
72       * The File pointed out by the URL should contain CREATE, INSERT and
73       * ALTER TABLE commands, and they will be run in the memory database
74       * 
75       * @param descriptor 
76       * @param serviceIdentity
77       * @param url
78       */
79      public DemoDataService(IDataSourceDescriptor descriptor, URL databaseURL)
80      {
81          super(descriptor, descriptor.getSourceName(), "jdbc:hsqldb:.", "sa", "", 1);
82          copyDataFromURL(databaseURL);
83      }
84      
85      /***
86       * Creates the Demo Database and copy data from the supplied HSQLDB database.
87       * 
88       * @param descriptor
89       * @param hsqldbDir  the directory containing the hsqldb database from which
90       *                   data should be copied.
91       * @param dbName     the name of the hsqldb database.
92       */
93      public DemoDataService(IDataSourceDescriptor descriptor, File hsqldbDir, String dbName)
94      {
95          super(descriptor, descriptor.getSourceName(), "jdbc:hsqldb:.", "sa", "", 0);
96          copyDataFromHSQLDB(descriptor, hsqldbDir, dbName);
97          this.setMaxConnectionPoolSize(1);
98      }
99      
100     // Help methods ------------------------------------------------------------
101     private void copyDataFromURL(URL scriptFileURL) 
102     {
103         InputStream stream = null;
104         Connection conn = openConnection();
105         Statement stmnt = null;
106         try
107         {
108             stmnt = conn.createStatement();
109             
110             stream = scriptFileURL.openStream();
111             ArrayList creates = new ArrayList();
112             ArrayList inserts = new ArrayList();
113             ArrayList constraints = new ArrayList();
114             
115             Reader fileReader = null;
116             if (stream != null) 
117             {
118                 fileReader = new InputStreamReader(stream);
119                 BufferedReader bufferedReader = new BufferedReader(fileReader, 10000);
120                 String currentLine = translateEscapeCodes(bufferedReader.readLine());
121                 while (currentLine != null)
122                 {
123                      if (currentLine != null) 
124                      {
125                         if (currentLine.indexOf ("CREATE TABLE") != -1)
126                         {
127                             creates.add(currentLine);
128                         }
129                         else if (currentLine.indexOf("ALTER TABLE") != -1)
130                         {
131                             constraints.add(currentLine);
132                         }
133                         else if (currentLine.indexOf("INSERT INTO") != -1)
134                         {
135                             inserts.add(currentLine);
136                         }
137                      }
138                      currentLine = translateEscapeCodes(bufferedReader.readLine());
139                 }   
140                 bufferedReader.close();
141             }
142             
143             // Turn off referential integrity checks.
144             stmnt.executeQuery("SET REFERENTIAL_INTEGRITY FALSE;");
145             
146             // First do creates.            
147             Iterator iter = creates.iterator();
148             while (iter.hasNext()) 
149             {
150                 String sql = (String) iter.next();
151                 stmnt.executeUpdate(sql);
152             }
153             
154             // Secondly copy the data.            
155             iter = inserts.iterator();
156             while (iter.hasNext()) 
157             {
158                 String sql = (String) iter.next();
159                 stmnt.executeUpdate(sql);
160             }
161             
162             // Thirdly perform table alterations.
163             iter = constraints.iterator();
164             while (iter.hasNext()) 
165             {
166                 String sql = (String) iter.next();
167                 stmnt.executeUpdate(sql);
168             }
169             
170             // Log success.
171             Log.print(this, "Memory database successfully created... ");
172             Log.print(this, "    "+creates.size()+" tables created.");
173             Log.print(this, "    "+inserts.size()+" rows copied.");
174             
175             // Turn on referential integrity checks.
176             stmnt.executeQuery("SET REFERENTIAL_INTEGRITY TRUE;");
177                         
178         } 
179         catch (IOException e)
180         {
181            e.printStackTrace();
182         } 
183         catch (SQLException e2)
184         {
185             e2.printStackTrace();
186         } 
187         finally 
188         {
189             try
190             {
191                 
192                 if (stmnt != null) 
193                 {
194                     stmnt.close();
195                 } 
196             
197                 if (conn != null)
198                 {
199                     closeConnection(conn);
200                 }
201             } 
202             catch (SQLException e3)
203             {
204                 e3.printStackTrace();
205             }   
206         }    
207     }
208     
209     private void copyDataFromHSQLDB(IDataSourceDescriptor descriptor, File hsqldbDir, String dbName) 
210     {
211         JDBCDataService sourceService = new JDBCDataService(descriptor, descriptor.getSourceName(), "jdbc:hsqldb:" + hsqldbDir.getAbsolutePath() + "/" + dbName, "sa", "", 0);
212         this.setValidating(false);
213         IDataSource.DataSourceCreator.createDataSource(new SingleServiceDataSource(sourceService), this, true);
214         this.setValidating(true);
215     }
216     
217     public static void main(String args[]) 
218     {
219         translateEscapeCodes("Test börjar-<>-Test Slut!//u00e");
220     } 
221     
222     /***
223      * Help method that translates escape codes like "\u0063" to their real 
224      * characters.
225      */
226     protected static String translateEscapeCodes(String text)
227     {
228         try
229         {
230             StringBuffer buf = new StringBuffer(text.length());
231             int prevIndex = 0;
232             
233             int index = text.indexOf("//u");
234             while(index>=0)
235             {
236                 if(text.length()>=index+6)
237                 { 
238                     int charNum = Integer.parseInt(text.substring(index+2, index+6), 16);                
239                     buf.append(text.substring(prevIndex, index));
240                     buf.append((char)charNum);
241                     
242                     prevIndex = index+6;
243                     index = text.indexOf("//u", prevIndex);
244                 }   
245                 else
246                     index=-1;
247             }
248             
249             buf.append(text.substring(prevIndex));
250             return buf.toString();
251         }
252         catch(Exception e)
253         {
254             Log.printWarning(null, "Failed to translate escape codes for: \""+text+"\"");
255             return text;
256         }
257     }
258 }