Source Code Cross Referenced for TestUtil.java in  » Database-Client » SQL-Workbench » workbench » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Database Client » SQL Workbench » workbench 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:         * TestUtil.java
003:         *
004:         * This file is part of SQL Workbench/J, http://www.sql-workbench.net
005:         *
006:         * Copyright 2002-2008, Thomas Kellerer
007:         * No part of this code maybe reused without the permission of the author
008:         *
009:         * To contact the author please send an email to: support@sql-workbench.net
010:         *
011:         */
012:        package workbench;
013:
014:        import java.io.BufferedReader;
015:        import java.io.File;
016:        import java.io.FileNotFoundException;
017:        import java.io.FileOutputStream;
018:        import java.io.FileReader;
019:        import java.io.FileWriter;
020:        import java.io.IOException;
021:        import java.io.PrintWriter;
022:        import java.io.StringReader;
023:        import java.sql.Connection;
024:        import java.sql.DriverManager;
025:        import java.sql.SQLException;
026:        import java.sql.Statement;
027:        import java.util.ArrayList;
028:        import java.util.List;
029:        import javax.xml.xpath.XPath;
030:        import javax.xml.xpath.XPathConstants;
031:        import javax.xml.xpath.XPathFactory;
032:        import org.xml.sax.InputSource;
033:        import workbench.db.ConnectionMgr;
034:        import workbench.db.ConnectionProfile;
035:        import workbench.db.WbConnection;
036:        import workbench.sql.BatchRunner;
037:        import workbench.sql.DefaultStatementRunner;
038:        import workbench.sql.ScriptParser;
039:        import workbench.util.ArgumentParser;
040:        import workbench.util.SqlUtil;
041:        import workbench.util.StringUtil;
042:        import workbench.util.WbFile;
043:
044:        /**
045:         *
046:         * @author support@sql-workbench.net
047:         */
048:        public class TestUtil {
049:
050:            private String basedir;
051:            private String testName;
052:
053:            public TestUtil(String name) {
054:                this (name, true);
055:            }
056:
057:            public TestUtil(String name, boolean noTemplates) {
058:                try {
059:                    testName = name;
060:                    prepareEnvironment(noTemplates);
061:                } catch (Exception e) {
062:                    e.printStackTrace();
063:                }
064:            }
065:
066:            public void prepareEnvironment() throws IOException {
067:                prepareEnvironment(true);
068:            }
069:
070:            public void prepareEnvironment(boolean noTemplates)
071:                    throws IOException {
072:                prepareBaseDir();
073:                WbManager.prepareForTest(getArgs(noTemplates));
074:            }
075:
076:            public String[] getArgs(boolean noTemplates) {
077:                String cmdline = "-nosettings -configdir='" + basedir + "' ";
078:
079:                if (noTemplates) {
080:                    cmdline += " -notemplates";
081:                }
082:
083:                return new String[] { cmdline };
084:            }
085:
086:            public void prepareBaseDir() throws IOException {
087:                File tempdir = new File(System.getProperty("java.io.tmpdir"));
088:                File dir = new File(tempdir, "wbtest");
089:                dir.mkdir();
090:                basedir = dir.getAbsolutePath();
091:
092:                PrintWriter pw = new PrintWriter(new FileWriter(new File(dir,
093:                        "workbench.settings")));
094:                pw.println("workbench.log.console=false");
095:                pw
096:                        .println("workbench.log.format={type} {timestamp} {source} {message} {error} {stacktrace}");
097:                pw.println("workbench.log.level=DEBUG");
098:                pw.println("workbench.log.maxfilesize=150000");
099:                pw.println("workbench.gui.language=en");
100:                pw.println("workbench.gui.autoconnect=false");
101:                pw.println("workbench.gui.updatecheck.interval=0");
102:                pw.println("workbench.db.previewsql=false");
103:                pw.close();
104:                emptyBaseDirectory();
105:            }
106:
107:            public void emptyBaseDirectory() {
108:                // Cleanup old database files
109:                File dir = new File(basedir);
110:                deleteFiles(dir);
111:            }
112:
113:            private void deleteFiles(File dir) {
114:                File[] files = dir.listFiles();
115:                for (int i = 0; i < files.length; i++) {
116:                    if (files[i].isDirectory()) {
117:                        deleteFiles(files[i]);
118:                    }
119:                    if (files[i].getName().equals("workbench.settings"))
120:                        continue;
121:                    if (files[i].getName().equals("workbench.log"))
122:                        continue;
123:
124:                    if (!files[i].delete()) {
125:                        System.out.println("Could not delete file: "
126:                                + files[i].getAbsolutePath());
127:                    }
128:                }
129:            }
130:
131:            public WbConnection getHSQLConnection(String dbName)
132:                    throws SQLException, ClassNotFoundException {
133:                ArgumentParser parser = new AppArguments();
134:                parser
135:                        .parse("-url='jdbc:hsqldb:mem:"
136:                                + dbName
137:                                + ";shutdown=true' -user=sa -driver=org.hsqldb.jdbcDriver");
138:                ConnectionProfile prof = BatchRunner
139:                        .createCmdLineProfile(parser);
140:                prof.setName(dbName);
141:                ConnectionMgr.getInstance().addProfile(prof);
142:                WbConnection con = ConnectionMgr.getInstance().getConnection(
143:                        prof, dbName);
144:                dropAll(con, false);
145:                return con;
146:            }
147:
148:            public WbConnection getConnection() throws SQLException,
149:                    ClassNotFoundException {
150:                return getConnection(this .testName);
151:            }
152:
153:            public WbConnection getConnection(String db) throws SQLException,
154:                    ClassNotFoundException {
155:                ArgumentParser parser = new AppArguments();
156:                parser.parse("-url='jdbc:h2:mem:" + db
157:                        + "' -user=sa -driver=org.h2.Driver");
158:                ConnectionProfile prof = BatchRunner
159:                        .createCmdLineProfile(parser);
160:                prof.setName(db);
161:                ConnectionMgr.getInstance().addProfile(prof);
162:                WbConnection con = ConnectionMgr.getInstance().getConnection(
163:                        prof, db);
164:                dropAll(con, true);
165:                return con;
166:            }
167:
168:            private void dropAll(WbConnection con, boolean isH2) {
169:                Statement stmt = null;
170:                try {
171:                    stmt = con.createStatement();
172:                    if (isH2) {
173:                        stmt.executeUpdate("DROP ALL OBJECTS");
174:                    } else {
175:                        stmt.executeUpdate("DROP SCHEMA PUBLIC CASCADE");
176:                    }
177:                    con.commit();
178:                } catch (Exception e) {
179:                    System.out.println("Could not drop all objects");
180:                } finally {
181:                    SqlUtil.closeStatement(stmt);
182:                }
183:            }
184:
185:            public WbConnection getConnection(File db) throws SQLException,
186:                    ClassNotFoundException {
187:                return getConnection(db, "WbUnitTest");
188:            }
189:
190:            public WbConnection getConnection(File db, String id)
191:                    throws SQLException, ClassNotFoundException {
192:                ArgumentParser parser = new AppArguments();
193:                parser.parse("-url='jdbc:h2:" + db.getAbsolutePath()
194:                        + "' -user=sa -driver=org.h2.Driver");
195:                ConnectionProfile prof = BatchRunner
196:                        .createCmdLineProfile(parser);
197:                WbConnection con = ConnectionMgr.getInstance().getConnection(
198:                        prof, id);
199:                return con;
200:            }
201:
202:            public DefaultStatementRunner createConnectedStatementRunner()
203:                    throws Exception {
204:                return createConnectedStatementRunner(getConnection());
205:            }
206:
207:            public DefaultStatementRunner createConnectedStatementRunner(
208:                    WbConnection con) throws Exception {
209:                DefaultStatementRunner runner = new DefaultStatementRunner();
210:                runner.setBaseDir(getBaseDir());
211:                runner.setConnection(con);
212:                return runner;
213:            }
214:
215:            public String getBaseDir() {
216:                return this .basedir;
217:            }
218:
219:            public static List<String> readLines(File f) throws IOException {
220:                ArrayList<String> result = new ArrayList<String>();
221:                BufferedReader in = null;
222:                int lines = 0;
223:                try {
224:                    in = new BufferedReader(new FileReader(f));
225:                    String s = in.readLine();
226:                    while (s != null) {
227:                        result.add(s);
228:                        s = in.readLine();
229:                    }
230:                } finally {
231:                    try {
232:                        in.close();
233:                    } catch (Throwable th) {
234:                    }
235:                }
236:                return result;
237:            }
238:
239:            public static int countLines(File f) throws IOException {
240:                BufferedReader in = null;
241:                int lines = 0;
242:                try {
243:                    in = new BufferedReader(new FileReader(f));
244:                    String s = in.readLine();
245:                    while (s != null) {
246:                        lines++;
247:                        s = in.readLine();
248:                    }
249:                } finally {
250:                    try {
251:                        in.close();
252:                    } catch (Throwable th) {
253:                    }
254:                }
255:                return lines;
256:            }
257:
258:            public static String getXPathValue(String xml, String expression) {
259:                try {
260:                    XPath xpath = XPathFactory.newInstance().newXPath();
261:                    InputSource inputSource = new InputSource(new StringReader(
262:                            xml));
263:                    String value = (String) xpath.evaluate(expression,
264:                            inputSource, XPathConstants.STRING);
265:                    return value;
266:                } catch (Exception e) {
267:                    e.printStackTrace();
268:                    return null;
269:                }
270:            }
271:
272:            public static void writeFile(File f, String content)
273:                    throws IOException {
274:                FileWriter w = new FileWriter(f);
275:                w.write(content);
276:                w.close();
277:            }
278:
279:            public static void executeScript(WbConnection con, String script)
280:                    throws SQLException {
281:                ScriptParser parser = new ScriptParser(script);
282:                int count = parser.getSize();
283:                for (int i = 0; i < count; i++) {
284:                    String sql = parser.getCommand(i);
285:                    Statement stmt = null;
286:                    try {
287:                        stmt = con.createStatement();
288:                        stmt.execute(sql);
289:                    } catch (SQLException e) {
290:                        System.out
291:                                .println("**** Error executing statement at index= "
292:                                        + i + ", sql=" + sql);
293:                        throw e;
294:                    } finally {
295:                        SqlUtil.closeStatement(stmt);
296:                    }
297:                }
298:            }
299:
300:            public void prepareSource(WbFile sourceDb) throws SQLException,
301:                    ClassNotFoundException {
302:                Connection con = null;
303:                Statement stmt = null;
304:
305:                try {
306:                    Class.forName("org.h2.Driver");
307:                    con = DriverManager.getConnection("jdbc:h2:"
308:                            + sourceDb.getFullPath(), "sa", "");
309:                    stmt = con.createStatement();
310:                    stmt
311:                            .executeUpdate("CREATE TABLE person (id integer primary key, firstname varchar(50), lastname varchar(50))");
312:                    stmt
313:                            .executeUpdate("insert into person (id, firstname, lastname) values (1, 'Arthur', 'Dent')");
314:                    stmt
315:                            .executeUpdate("insert into person (id, firstname, lastname) values (2, 'Mary', 'Moviestar')");
316:                    stmt
317:                            .executeUpdate("insert into person (id, firstname, lastname) values (3, 'Major', 'Bug')");
318:                    stmt
319:                            .executeUpdate("insert into person (id, firstname, lastname) values (4, 'General', 'Failure')");
320:                    con.commit();
321:                    stmt.close();
322:                    con.close();
323:                } finally {
324:                    SqlUtil.closeStatement(stmt);
325:                    try {
326:                        con.close();
327:                    } catch (Throwable th) {
328:                    }
329:                }
330:            }
331:
332:            public void prepareTarget(WbFile targetDb) throws SQLException,
333:                    ClassNotFoundException {
334:                Connection con = DriverManager.getConnection("jdbc:h2:"
335:                        + targetDb.getFullPath(), "sa", "");
336:                Statement stmt = null;
337:                try {
338:                    Class.forName("org.h2.Driver");
339:                    stmt = con.createStatement();
340:                    stmt
341:                            .executeUpdate("CREATE TABLE person (id integer primary key, firstname varchar(50), lastname varchar(50))");
342:                    con.commit();
343:                    stmt.close();
344:                    con.close();
345:                } finally {
346:                    SqlUtil.closeStatement(stmt);
347:                    try {
348:                        con.close();
349:                    } catch (Throwable th) {
350:                    }
351:                }
352:            }
353:
354:            public void createProfiles(WbFile sourceDb, WbFile targetDb)
355:                    throws FileNotFoundException {
356:                String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>  \n"
357:                        + "<java version=\"1.5.0_08\" class=\"java.beans.XMLDecoder\">  \n"
358:                        + "	 \n"
359:                        + " <object class=\"java.util.ArrayList\">  \n"
360:                        + "  <void method=\"add\">  \n"
361:                        + "   <object class=\"workbench.db.ConnectionProfile\">  \n"
362:                        + "    <void property=\"driverclass\">  \n"
363:                        + "     <string>org.h2.Driver</string>  \n"
364:                        + "    </void>  \n"
365:                        + "    <void property=\"name\">  \n"
366:                        + "     <string>SourceConnection</string>  \n"
367:                        + "    </void>  \n" + "    <void property=\"url\">  \n"
368:                        + "     <string>" + "jdbc:h2:"
369:                        + StringUtil.replace(sourceDb.getFullPath(), "\\", "/")
370:                        + "</string>  \n"
371:                        + "    </void>  \n"
372:                        + "    <void property=\"username\">  \n"
373:                        + "     <string>sa</string>  \n"
374:                        + "    </void>  \n"
375:                        + "   </object>  \n"
376:                        + "  </void>  \n"
377:                        + "	 \n"
378:                        + "  <void method=\"add\">  \n"
379:                        + "   <object class=\"workbench.db.ConnectionProfile\">  \n"
380:                        + "    <void property=\"driverclass\">  \n"
381:                        + "     <string>org.h2.Driver</string>  \n"
382:                        + "    </void>  \n"
383:                        + "    <void property=\"name\">  \n"
384:                        + "     <string>TargetConnection</string>  \n"
385:                        + "    </void>  \n"
386:                        + "    <void property=\"url\">  \n"
387:                        + "     <string>"
388:                        + "jdbc:h2:"
389:                        + StringUtil.replace(targetDb.getFullPath(), "\\", "/")
390:                        + "</string>  \n"
391:                        + "    </void>  \n"
392:                        + "    <void property=\"username\">  \n"
393:                        + "     <string>sa</string>  \n"
394:                        + "    </void>  \n"
395:                        + "   </object>  \n"
396:                        + "  </void>  \n"
397:                        + "	 \n"
398:                        + " </object>  \n" + "</java> ";
399:                PrintWriter writer = new PrintWriter(new FileOutputStream(
400:                        new File(getBaseDir(), "WbProfiles.xml")));
401:                writer.println(xml);
402:                writer.close();
403:                // Make sure the new profiles are read
404:                ConnectionMgr.getInstance().readProfiles();
405:            }
406:
407:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.