001package org.apache.turbine.test; 002 003import java.nio.charset.StandardCharsets; 004import java.nio.file.Files; 005import java.nio.file.Paths; 006import java.sql.Connection; 007import java.sql.DriverManager; 008import java.sql.SQLException; 009import java.sql.Statement; 010 011import org.apache.commons.lang3.StringUtils; 012import org.apache.commons.logging.Log; 013import org.apache.commons.logging.LogFactory; 014import org.hsqldb.jdbcDriver; 015 016public class HsqlDB 017{ 018 private Connection connection = null; 019 private static Log log = LogFactory.getLog(HsqlDB.class); 020 021 public HsqlDB(String uri, String loadFile) 022 throws Exception 023 { 024 Class.forName(jdbcDriver.class.getName()); 025 026 this.connection = DriverManager.getConnection(uri, "sa", ""); 027 028 if (StringUtils.isNotEmpty(loadFile)) 029 { 030 loadSqlFile(loadFile); 031 } 032 } 033 034 public Connection getConnection() 035 { 036 return connection; 037 } 038 039 public void close() 040 { 041 try 042 { 043 connection.close(); 044 } 045 catch (Exception e) 046 { 047 // ignore 048 } 049 } 050 051 private void loadSqlFile(String fileName) 052 throws Exception 053 { 054 try (Statement statement = connection.createStatement()) 055 { 056 String commands = getFileContents(fileName); 057 058 for (int targetPos = commands.indexOf(';'); targetPos > -1; targetPos = commands.indexOf(';')) 059 { 060 String cmd = commands.substring(0, targetPos + 1).trim(); 061 062 if (cmd.startsWith("--")) 063 { 064 // comment 065 int lineend = commands.indexOf('\n'); 066 if (lineend > -1) 067 { 068 targetPos = lineend - 1; 069 } 070 } 071 else 072 { 073 try 074 { 075 statement.execute(cmd); 076 } 077 catch (SQLException sqle) 078 { 079 log.warn("Statement: " + cmd + ": " + sqle.getMessage()); 080 } 081 } 082 083 commands = commands.substring(targetPos + 2); 084 } 085 } 086 } 087 088 private String getFileContents(String fileName) 089 throws Exception 090 { 091 byte[] bytes = Files.readAllBytes(Paths.get(fileName)); 092 093 return new String(bytes, StandardCharsets.ISO_8859_1); 094 } 095} 096