Update ooo320-m1
[ooovba.git] / qadevOOo / runner / util / DBTools.java
blob92434cfd89f2403903446e55444ad51e2b6f2849
1 /*************************************************************************
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * Copyright 2008 by Sun Microsystems, Inc.
7 * OpenOffice.org - a multi-platform office productivity suite
9 * $RCSfile: DBTools.java,v $
10 * $Revision: 1.8 $
12 * This file is part of OpenOffice.org.
14 * OpenOffice.org is free software: you can redistribute it and/or modify
15 * it under the terms of the GNU Lesser General Public License version 3
16 * only, as published by the Free Software Foundation.
18 * OpenOffice.org is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU Lesser General Public License version 3 for more details
22 * (a copy is included in the LICENSE file that accompanied this code).
24 * You should have received a copy of the GNU Lesser General Public License
25 * version 3 along with OpenOffice.org. If not, see
26 * <http://www.openoffice.org/license.html>
27 * for a copy of the LGPLv3 License.
29 ************************************************************************/
31 package util;
33 import java.io.PrintWriter ;
35 // access the implementations via names
36 import com.sun.star.uno.XInterface;
37 import com.sun.star.lang.XMultiServiceFactory;
38 import com.sun.star.uno.UnoRuntime;
40 import com.sun.star.beans.PropertyValue;
41 import com.sun.star.beans.XPropertySet;
42 import com.sun.star.sdbc.XConnection ;
43 import com.sun.star.sdbc.XResultSet ;
44 import com.sun.star.sdbc.XResultSetUpdate ;
45 import com.sun.star.sdbc.XStatement ;
46 import com.sun.star.sdbc.XRowUpdate ;
47 import com.sun.star.util.Date ;
48 import com.sun.star.uno.XNamingService ;
49 import com.sun.star.task.XInteractionHandler ;
50 import com.sun.star.sdb.XCompletedConnection ;
51 import com.sun.star.container.XEnumeration ;
52 import com.sun.star.container.XEnumerationAccess ;
53 import com.sun.star.io.XInputStream ;
54 import com.sun.star.io.XTextInputStream ;
55 import com.sun.star.io.XDataInputStream ;
56 import com.sun.star.container.XNameAccess ;
57 import com.sun.star.frame.XStorable;
58 import com.sun.star.sdb.XDocumentDataSource;
59 import com.sun.star.sdbc.XCloseable ;
60 import java.sql.Statement;
61 import java.sql.Connection;
62 import java.sql.DriverManager;
64 /**
65 * Provides useful methods for working with SOffice databases.
66 * Database creation, data transfering, outputting infromation.
68 public class DBTools {
70 private XMultiServiceFactory xMSF = null ;
71 private XNamingService dbContext = null ;
73 //JDBC driver
74 public final static String TST_JDBC_DRIVER = "org.gjt.mm.mysql.Driver";
76 // constants for TestDB table column indexes
77 public final static int TST_STRING = 1 ;
78 public final static int TST_INT = 2 ;
79 public final static int TST_DOUBLE = 5 ;
80 public final static int TST_DATE = 6 ;
81 public final static int TST_BOOLEAN = 10 ;
82 public final static int TST_CHARACTER_STREAM = 11 ;
83 public final static int TST_BINARY_STREAM = 12 ;
85 // constants for TestDB columns names
86 public final static String TST_STRING_F = "_TEXT" ;
87 public final static String TST_INT_F = "_INT" ;
88 public final static String TST_DOUBLE_F = "_DOUBLE" ;
89 public final static String TST_DATE_F = "_DATE" ;
90 public final static String TST_BOOLEAN_F = "_BOOL" ;
91 public final static String TST_CHARACTER_STREAM_F = "_MEMO1" ;
92 public final static String TST_BINARY_STREAM_F = "_MEMO2" ;
94 /**
95 * Values for filling test table.
97 public final static Object[][] TST_TABLE_VALUES = new Object[][] {
98 {"String1", new Integer(1), null, null, new Double(1.1),
99 new Date((short) 1,(short) 1, (short) 2001), null, null, null,
100 Boolean.TRUE, null, null},
101 {"String2", new Integer(2), null, null, new Double(1.2),
102 new Date((short) 2, (short) 1,(short) 2001), null, null, null,
103 Boolean.FALSE, null, null},
104 {null, null, null, null, null,
105 null, null, null, null,
106 null, null, null}
110 * Array of lengths of streams for each row in of the
111 * <code>TST_TABLE_VALUES</code> constants.
113 public final static int[] TST_STREAM_LENGTHS = {0, 0, 0} ;
116 * It's just a structure with some useful methods for representing
117 * <code>com.sun.star.sdb.DataSource</code> service. All this
118 * service's properties are stored in appropriate class fields.
119 * Class also allows to construct its instances using service
120 * information, and create new service instance upon class
121 * fields.
122 * @see com.sun.star.sdb.DataSource
124 public class DataSourceInfo {
126 * Representation of <code>'Name'</code> property.
128 public String Name = null ;
130 * Representation of <code>'URL'</code> property.
132 public String URL = null ;
134 * Representation of <code>'Info'</code> property.
136 public PropertyValue[] Info = null ;
138 * Representation of <code>'User'</code> property.
140 public String User = null ;
142 * Representation of <code>'Password'</code> property.
144 public String Password = null ;
146 * Representation of <code>'IsPasswordRequired'</code> property.
148 public Boolean IsPasswordRequired = null ;
150 * Representation of <code>'SuppressVersionColumns'</code> property.
152 public Boolean SuppressVersionColumns = null ;
154 * Representation of <code>'IsReadOnly'</code> property.
156 public Boolean IsReadOnly = null ;
158 * Representation of <code>'TableFilter'</code> property.
160 public String[] TableFilter = null ;
162 * Representation of <code>'TableTypeFilter'</code> property.
164 public String[] TableTypeFilter = null ;
167 * Creates an empty instance.
169 public DataSourceInfo() {}
172 * Creates an instance laying upon specified DataSource.
173 * @param dataSource All source properties are copied into
174 * class fields.
176 public DataSourceInfo(Object dataSource) {
177 XPropertySet xProps = (XPropertySet)
178 UnoRuntime.queryInterface(XPropertySet.class, dataSource) ;
180 try {
181 Name = (String)xProps.getPropertyValue("Name") ;
182 URL = (String)xProps.getPropertyValue("URL") ;
183 Info = (PropertyValue[])xProps.getPropertyValue("Info") ;
184 User = (String)xProps.getPropertyValue("User") ;
185 Password = (String)xProps.getPropertyValue("Password") ;
186 IsPasswordRequired = (Boolean)xProps.getPropertyValue("IsPasswordRequired") ;
187 SuppressVersionColumns = (Boolean)
188 xProps.getPropertyValue("SuppressVersionColumns") ;
189 IsReadOnly = (Boolean)xProps.getPropertyValue("IsReadOnly") ;
190 TableFilter = (String[])xProps.getPropertyValue("TableFilter") ;
191 TableTypeFilter = (String[])xProps.getPropertyValue("TableTypeFilter") ;
192 } catch (com.sun.star.beans.UnknownPropertyException e) {
193 System.err.println("util.DBTools.DataSourceInfo: Error retrieving property") ;
194 e.printStackTrace(System.err) ;
195 } catch (com.sun.star.lang.WrappedTargetException e) {
196 System.err.println("util.DBTools.DataSourceInfo: Error retrieving property") ;
197 e.printStackTrace(System.err) ;
202 * Prints datasource info.
203 * @param out Stream to which information is printed.
205 public void printInfo(PrintWriter out) {
206 out.println("Name = '" + Name + "'") ;
207 out.println(" URL = '" + URL + "'") ;
208 out.print(" Info = ") ;
209 if (Info == null) out.println("null") ;
210 else {
211 out.print("{") ;
212 for (int i = 0; i < Info.length; i++) {
213 out.print(Info[i].Name + " = '" + Info[i].Value + "'") ;
214 if (i + 1 < Info.length) out.print("; ") ;
216 out.println("}") ;
218 out.println(" User = '" + User + "'") ;
219 out.println(" Password = '" + Password + "'") ;
220 out.println(" IsPasswordRequired = '" + IsPasswordRequired + "'") ;
221 out.println(" SuppressVersionColumns = '" + SuppressVersionColumns + "'") ;
222 out.println(" IsReadOnly = '" + IsReadOnly + "'") ;
223 out.print(" TableFilter = ") ;
224 if (TableFilter == null) out.println("null") ;
225 else {
226 out.print("{") ;
227 for (int i = 0; i < TableFilter.length; i++) {
228 out.print("'" + TableFilter[i] + "'") ;
229 if (i+1 < TableFilter.length) out.print("; ");
231 out.println("}") ;
233 out.print(" TableTypeFilter = ") ;
234 if (TableTypeFilter == null) out.println("null") ;
235 else {
236 out.print("{") ;
237 for (int i = 0; i < TableTypeFilter.length; i++) {
238 out.print("'" + TableTypeFilter[i] + "'") ;
239 if (i+1 < TableTypeFilter.length) out.print("; ");
241 out.println("}") ;
246 * Creates new <code>com.sun.star.sdb.DataSource</code> service
247 * instance and copies all fields (which are not null) to
248 * appropriate service properties.
249 * @return <code>com.sun.star.sdb.DataSource</code> service.
251 public Object getDataSourceService() {
252 Object src = null ;
253 try {
254 src = xMSF.createInstance("com.sun.star.sdb.DataSource") ;
255 } catch (com.sun.star.uno.Exception e) {}
257 if (src == null) return null ;
259 XPropertySet props = (XPropertySet) UnoRuntime.queryInterface
260 (XPropertySet.class, src) ;
262 try {
263 if (Name != null) props.setPropertyValue("Name", Name) ;
264 if (URL != null) props.setPropertyValue("URL", URL) ;
265 if (Info != null) props.setPropertyValue("Info", Info) ;
266 if (User != null) props.setPropertyValue("User", User) ;
267 if (Password != null) props.setPropertyValue("Password", Password) ;
268 if (IsPasswordRequired != null) props.setPropertyValue("IsPasswordRequired", IsPasswordRequired) ;
269 if (SuppressVersionColumns != null) props.setPropertyValue("SuppressVersionColumns", SuppressVersionColumns) ;
270 if (IsReadOnly != null) props.setPropertyValue("IsReadOnly", IsReadOnly) ;
271 if (TableFilter != null) props.setPropertyValue("TableFilter", TableFilter) ;
272 if (TableTypeFilter != null) props.setPropertyValue("TableTypeFilter", TableTypeFilter) ;
274 } catch (com.sun.star.beans.UnknownPropertyException e) {
275 return null ;
276 } catch (com.sun.star.beans.PropertyVetoException e) {
277 return null ;
278 } catch (com.sun.star.lang.WrappedTargetException e) {
279 return null ;
280 } catch (com.sun.star.lang.IllegalArgumentException e) {
281 return null ;
284 return src ;
289 * Creates class instance.
290 * @param xMSF <code>XMultiServiceFactory</code>.
292 public DBTools(XMultiServiceFactory xMSF) {
293 this.xMSF = xMSF ;
295 try {
296 Object cont = xMSF.createInstance("com.sun.star.sdb.DatabaseContext") ;
298 dbContext = (XNamingService) UnoRuntime.queryInterface
299 (XNamingService.class, cont) ;
301 } catch (com.sun.star.uno.Exception e) {}
305 * Returns new instance of <code>DataSourceInfo</code> class.
307 public DataSourceInfo newDataSourceInfo() { return new DataSourceInfo() ;}
310 * Returns new instance of <code>DataSourceInfo</code> class.
312 public DataSourceInfo newDataSourceInfo(Object dataSource) {
313 return new DataSourceInfo(dataSource);
317 * Registers the datasource on the specified name in
318 * <code>DatabaseContext</code> service.
319 * @param name Name which dataSource will have in global context.
320 * @param dataSource <code>DataSource</code> object which is to
321 * be registered.
323 public void registerDB(String name, Object dataSource)
324 throws com.sun.star.uno.Exception {
326 dbContext.registerObject(name, dataSource) ;
331 * First tries to revoke the datasource with the specified
332 * name and then registers a new one.
333 * @param name Name which dataSource will have in global context.
334 * @param dataSource <code>DataSource</code> object which is to
335 * be registered.
337 public void reRegisterDB(String name, Object dataSource)
338 throws com.sun.star.uno.Exception {
340 try {
341 revokeDB(name) ;
342 } catch (com.sun.star.uno.Exception e) {}
344 XDocumentDataSource xDDS = (XDocumentDataSource)
345 UnoRuntime.queryInterface(XDocumentDataSource.class, dataSource);
346 XStorable store = (XStorable) UnoRuntime.queryInterface(XStorable.class,
347 xDDS.getDatabaseDocument());
348 String aFile = utils.getOfficeTemp(xMSF) + name + ".odb";
349 store.storeAsURL(aFile, new PropertyValue[] { });
351 registerDB(name, dataSource) ;
355 * RESERVED. Not used.
357 public XConnection connectToTextDB(String contextName,
358 String dbDir, String fileExtension)
359 throws com.sun.star.uno.Exception {
361 try {
362 XInterface newSource = (XInterface) xMSF.createInstance
363 ("com.sun.star.sdb.DataSource") ;
365 XPropertySet xSrcProp = (XPropertySet)
366 UnoRuntime.queryInterface(XPropertySet.class, newSource);
368 xSrcProp.setPropertyValue("URL", "sdbc:text:" + dirToUrl(dbDir));
370 PropertyValue extParam = new PropertyValue() ;
371 extParam.Name = "EXT" ;
372 extParam.Value = fileExtension ;
374 xSrcProp.setPropertyValue("Info", new PropertyValue[] {extParam}) ;
376 dbContext.registerObject(contextName, newSource) ;
378 Object handler = xMSF.createInstance("com.sun.star.sdb.InteractionHandler");
379 XInteractionHandler xHandler = (XInteractionHandler)
380 UnoRuntime.queryInterface(XInteractionHandler.class, handler) ;
382 XCompletedConnection xSrcCon = (XCompletedConnection)
383 UnoRuntime.queryInterface(XCompletedConnection.class, newSource) ;
385 XConnection con = xSrcCon.connectWithCompletion(xHandler) ;
387 return con ;
388 } finally {
389 try {
390 dbContext.revokeObject(contextName) ;
391 } catch (Exception e) {}
396 * Registers DBase database (directory with DBF files) in the
397 * global DB context, then connects to it.
398 * @param contextName Name under which DB will be registered.
399 * @param dbDir The directory with DBF tables.
400 * @return Connection to the DB.
402 public XConnection connectToDBase(String contextName,
403 String dbDir)
404 throws com.sun.star.uno.Exception {
406 try {
407 XInterface newSource = (XInterface) xMSF.createInstance
408 ("com.sun.star.sdb.DataSource") ;
410 XPropertySet xSrcProp = (XPropertySet)
411 UnoRuntime.queryInterface(XPropertySet.class, newSource);
412 xSrcProp.setPropertyValue("URL", "sdbc:dbase:" + dirToUrl(dbDir));
414 dbContext.registerObject(contextName, newSource) ;
416 XConnection con = connectToSource(newSource) ;
418 return con ;
419 } catch(com.sun.star.uno.Exception e) {
420 try {
421 dbContext.revokeObject(contextName) ;
422 } catch (Exception ex) {}
424 throw e ;
429 * Performs connection to DataSource specified.
430 * @param dbSource <code>com.sun.star.sdb.DataSource</code> service
431 * specified data source which must be already registered in the
432 * <code>DatabaseContext</code> service.
433 * @param dbSource Data source to be connected to.
434 * @return Connection to the data source.
436 public XConnection connectToSource(Object dbSource)
437 throws com.sun.star.uno.Exception {
439 Object handler = xMSF.createInstance("com.sun.star.sdb.InteractionHandler");
440 XInteractionHandler xHandler = (XInteractionHandler)
441 UnoRuntime.queryInterface(XInteractionHandler.class, handler) ;
443 XCompletedConnection xSrcCon = (XCompletedConnection)
444 UnoRuntime.queryInterface(XCompletedConnection.class, dbSource) ;
446 return xSrcCon.connectWithCompletion(xHandler) ;
450 * Registers Test data source in the <code>DatabaseContext</code> service.
451 * This source always has name <code>'APITestDatabase'</code> and it
452 * is registered in subdirectory <code>TestDB</code> of directory
453 * <code>docPath</code> which is supposed to be a directory with test
454 * documents, but can be any other (it must have subdirectory with DBF
455 * tables). If such data source doesn't exists or exists with
456 * different URL it is recreated and reregistered.
457 * @param docPath Path to database <code>TestDB</code> directory.
458 * @return <code>com.sun.star.sdb.DataSource</code> service
459 * implementation which represents TestDB.
461 public Object registerTestDB(String docPath)
462 throws com.sun.star.uno.Exception {
464 String testURL = null ;
465 if (docPath.endsWith("/") || docPath.endsWith("\\"))
466 testURL = dirToUrl(docPath + "TestDB") ;
467 else
468 testURL = dirToUrl(docPath + "/" + "TestDB") ;
469 testURL = "sdbc:dbase:" + testURL ;
471 String existURL = null ;
473 XNameAccess na = (XNameAccess) UnoRuntime.queryInterface
474 (XNameAccess.class, dbContext) ;
476 Object src = null ;
477 if (na.hasByName("APITestDatabase")) {
478 src = dbContext.getRegisteredObject("APITestDatabase") ;
480 XPropertySet srcPs = (XPropertySet) UnoRuntime.queryInterface
481 (XPropertySet.class, src) ;
483 existURL = (String) srcPs.getPropertyValue("URL") ;
486 if (src == null || !testURL.equals(existURL)) {
487 // test data source must be reregistered.
488 DataSourceInfo info = new DataSourceInfo() ;
489 info.URL = testURL ;
490 src = info.getDataSourceService() ;
491 reRegisterDB("APITestDatabase", src) ;
492 src = dbContext.getRegisteredObject("APITestDatabase") ;
495 return src ;
499 * Connects to <code>DataSource</code> specially created for testing.
500 * This source always has name <code>'APITestDatabase'</code> and it
501 * is registered in subdirectory <code>TestDB</code> of directory
502 * <code>docPath</code> which is supposed to be a directory with test
503 * documents, but can be any other (it must have subdirectory with DBF
504 * tables). If such data source doesn't exists or exists with
505 * different URL it is recreated and reregistered. Finally connection
506 * performed.
507 * @param docPath Path to database <code>TestDB</code> directory.
508 * @return Connection to test database.
510 public XConnection connectToTestDB(String docPath)
511 throws com.sun.star.uno.Exception {
513 return connectToSource(registerTestDB(docPath)) ;
517 * Empties the table in the specified source.
518 * @param con Connection to the DataSource where appropriate
519 * table exists.
520 * @param table The name of the table where all rows will be deleted.
521 * @return Number of rows deleted.
524 // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
525 // Currently doesn't work because of bugs 85509, 85510
527 public int deleteAllRows(XConnection con, String table)
528 throws com.sun.star.sdbc.SQLException {
530 XStatement stat = con.createStatement() ;
532 XResultSet set = stat.executeQuery("SELECT * FROM " + table) ;
534 XResultSetUpdate updt = (XResultSetUpdate) UnoRuntime.queryInterface
535 (XResultSetUpdate.class, set) ;
537 int count = 0 ;
538 set.last() ;
539 int rowNum = set.getRow() ;
540 set.first() ;
542 for (int i = 0; i < rowNum; i++) {
543 updt.deleteRow() ;
544 set.next() ;
545 count ++ ;
548 XCloseable xClose = (XCloseable) UnoRuntime.queryInterface
549 (XCloseable.class, set) ;
550 xClose.close() ;
552 return count ;
556 * Inserts row into test table of the specified connection.
557 * Test table has some predefined format which includes as much
558 * field types as possible. For every column type constants
559 * {@link #TST_STRING TST_STRING}, {@link #TST_INT TST_INT}, etc.
560 * are declared for column index fast find.
561 * @param con Connection to data source where test table exists.
562 * @param table Test table name.
563 * @param values Values to be inserted into test table. Values of
564 * this array inserted into appropriate fields depending on their
565 * types. So <code>String</code> value of the array is inserted
566 * into the field of <code>CHARACTER</code> type, etc.
567 * @param streamLength Is optional. It is used only if in values
568 * list <code>XCharacterInputStream</code> or <code>XBinaryInputStream
569 * </code> types specified. In this case the parameter specifies
570 * the length of the stream for inserting.
572 public void addRowToTestTable(XConnection con, String table, Object[] values,
573 int streamLength)
574 throws com.sun.star.sdbc.SQLException {
576 XStatement stat = con.createStatement() ;
578 XResultSet set = stat.executeQuery("SELECT * FROM " + table) ;
580 XResultSetUpdate updt = (XResultSetUpdate) UnoRuntime.queryInterface
581 (XResultSetUpdate.class, set) ;
583 XRowUpdate rowUpdt = (XRowUpdate) UnoRuntime.queryInterface
584 (XRowUpdate.class, set) ;
586 updt.moveToInsertRow() ;
588 for (int i = 0; i < values.length; i++) {
589 if (values[i] instanceof String) {
590 rowUpdt.updateString(TST_STRING, (String) values[i]) ;
591 } else
592 if (values[i] instanceof Integer) {
593 rowUpdt.updateInt(TST_INT, ((Integer) values[i]).intValue()) ;
594 } else
595 if (values[i] instanceof Double) {
596 rowUpdt.updateDouble(TST_DOUBLE, ((Double) values[i]).doubleValue()) ;
597 } else
598 if (values[i] instanceof Date) {
599 rowUpdt.updateDate(TST_DATE, (Date) values[i]) ;
600 } else
601 if (values[i] instanceof Boolean) {
602 rowUpdt.updateBoolean(TST_BOOLEAN, ((Boolean) values[i]).booleanValue()) ;
603 } else
604 if (values[i] instanceof XTextInputStream) {
605 rowUpdt.updateCharacterStream(TST_CHARACTER_STREAM, (XInputStream) values[i],
606 streamLength) ;
607 } else
608 if (values[i] instanceof XDataInputStream) {
609 rowUpdt.updateBinaryStream(TST_BINARY_STREAM, (XInputStream) values[i],
610 streamLength) ;
614 updt.insertRow() ;
616 XCloseable xClose = (XCloseable) UnoRuntime.queryInterface
617 (XCloseable.class, set) ;
618 xClose.close() ;
622 * Initializes test table specified of the connection specified.
623 * Deletes all record from table, and then inserts data from
624 * <code>TST_TABLE_VALUES</code> constant array. <p>
625 * Test table has some predefined format which includes as much
626 * field types as possible. For every column type constants
627 * {@link #TST_STRING TST_STRING}, {@link #TST_INT TST_INT}, etc.
628 * are declared for column index fast find.
629 * @param con Connection to data source where test table exists.
630 * @param table Test table name.
632 public void initializeTestTable(XConnection con, String table)
633 throws com.sun.star.sdbc.SQLException {
635 deleteAllRows(con, table) ;
637 for (int i = 0; i < TST_TABLE_VALUES.length; i++) {
638 addRowToTestTable(con, table, TST_TABLE_VALUES[i], TST_STREAM_LENGTHS[i]) ;
643 * Prints full info about currently registered DataSource's.
645 public void printRegisteredDatabasesInfo(PrintWriter out) {
646 XEnumerationAccess dbContEA = (XEnumerationAccess)
647 UnoRuntime.queryInterface(XEnumerationAccess.class, dbContext) ;
649 XEnumeration xEnum = dbContEA.createEnumeration() ;
651 out.println("DatabaseContext registered DataSource's :") ;
652 while (xEnum.hasMoreElements()) {
653 try {
654 DataSourceInfo inf = new DataSourceInfo(xEnum.nextElement()) ;
655 inf.printInfo(out) ;
656 } catch (com.sun.star.container.NoSuchElementException e) {}
657 catch (com.sun.star.lang.WrappedTargetException e) {}
662 * Convert system pathname to SOffice URL string
663 * (for example 'C:\Temp\DBDir\' -> 'file:///C|/Temp/DBDir/').
664 * (for example '\\server\Temp\DBDir\' -> 'file://server/Temp/DBDir/').
665 * Already converted string retured unchanged.
667 public static String dirToUrl(String dir) {
668 String retVal = null;
669 if (dir.startsWith("file:/")) retVal = dir;
670 else {
671 retVal = dir.replace(':', '|').replace('\\', '/');
673 if (dir.startsWith("\\\\")) {
674 retVal = "file:" + retVal;
677 else retVal = "file:///" + retVal ;
679 return retVal;
683 * Revokes datasource from global DB context.
684 * @param name DataSource name to be revoked.
686 public void revokeDB(String name) throws com.sun.star.uno.Exception
688 dbContext.revokeObject(name) ;
692 * Initializes test table specified of the connection specified
693 * using JDBC driver. Drops table with the name <code>tbl_name</code>,
694 * creates new table with this name and then inserts data from
695 * <code>TST_TABLE_VALUES</code> constant array. <p>
696 * Test table has some predefined format which includes as much
697 * field types as possible. For every column type constants
698 * {@link #TST_STRING TST_STRING}, {@link #TST_INT TST_INT}, etc.
699 * are declared for column index fast find.
700 * @param tbl_name Test table name.
702 public void initTestTableUsingJDBC(String tbl_name, DataSourceInfo dsi)
703 throws java.sql.SQLException,
704 ClassNotFoundException {
705 //register jdbc driver
706 if ( dsi.Info[0].Name.equals("JavaDriverClass") ) {
707 Class.forName((String)dsi.Info[0].Value);
708 } else {
709 Class.forName(TST_JDBC_DRIVER);
712 //getting connection
713 Connection connection = null;
715 connection = DriverManager.getConnection(
716 dsi.URL, dsi.User, dsi.Password);
717 Statement statement = connection.createStatement();
719 //drop table
720 dropMySQLTable(statement, tbl_name);
722 //create table
723 createMySQLTable(statement, tbl_name);
725 //insert some content
726 insertContentMySQLTable(statement, tbl_name);
730 * Inserts data from <code>TST_TABLE_VALUES</code> constant array
731 * to test table <code>tbl_name</code>.
732 * @param statement object used for executing a static SQL
733 * statement and obtaining the results produced by it.
734 * @param tbl_name Test table name.
736 protected void insertContentMySQLTable(Statement statement, String tbl_name)
737 throws java.sql.SQLException {
740 for(int i = 0; i < DBTools.TST_TABLE_VALUES.length; i++) {
741 String query = "insert into " + tbl_name + " values (";
742 int j = 0;
743 while(j < DBTools.TST_TABLE_VALUES[i].length) {
744 if (j > 0) {
745 query += ", ";
747 Object value = DBTools.TST_TABLE_VALUES[i][j];
748 if (value instanceof String ||
749 value instanceof Date) {
750 query += "'";
752 if (value instanceof Date) {
753 Date date = (Date)value;
754 query += date.Year + "-" + date.Month +
755 "-" + date.Day;
756 } else if (value instanceof Boolean) {
757 query += (((Boolean)value).booleanValue())
758 ? "1" : "0";
759 } else {
760 query += value;
763 if (value instanceof String ||
764 value instanceof Date) {
765 query += "'";
767 j++;
769 query += ")";
770 statement.executeUpdate(query);
775 * Creates test table specified.
776 * Test table has some predefined format which includes as much
777 * field types as possible. For every column type constants
778 * {@link #TST_STRING TST_STRING}, {@link #TST_INT TST_INT}, etc.
779 * are declared for column index fast find.
780 * @param statement object used for executing a static SQL
781 * statement and obtaining the results produced by it.
782 * @param table Test table name.
784 protected void createMySQLTable(Statement statement, String tbl_name)
785 throws java.sql.SQLException {
787 final String empty_col_name = "Column";
788 int c = 0;
789 String query = "create table " + tbl_name + " (";
790 for (int i = 0; i < TST_TABLE_VALUES[0].length; i++) {
791 if (i > 0) query += ",";
793 switch(i + 1) {
794 case TST_BINARY_STREAM:
795 query += TST_BINARY_STREAM_F + " BLOB";
796 break;
797 case TST_BOOLEAN:
798 query += TST_BOOLEAN_F + " TINYINT";
799 break;
800 case TST_CHARACTER_STREAM:
801 query += TST_CHARACTER_STREAM_F + " TEXT";
802 break;
803 case TST_DATE:
804 query += TST_DATE_F + " DATE";
805 break;
806 case TST_DOUBLE:
807 query += TST_DOUBLE_F + " DOUBLE";
808 break;
809 case TST_INT:
810 query += TST_INT_F + " INT";
811 break;
812 case TST_STRING:
813 query += TST_STRING_F + " TEXT";
814 break;
815 default: query += empty_col_name + (c++) + " INT";
816 if (c == 1) {
817 query += " NOT NULL AUTO_INCREMENT";
821 query += ", PRIMARY KEY (" + empty_col_name + "0)";
822 query += ")";
823 statement.execute(query);
827 * Drops table.
828 * @param statement object used for executing a static SQL
829 * statement and obtaining the results produced by it.
830 * @param table Test table name.
832 protected void dropMySQLTable(Statement statement, String tbl_name)
833 throws java.sql.SQLException {
834 statement.executeUpdate("drop table if exists " + tbl_name);