1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 package com.sun.star.wizards.db;
24 
25 import com.sun.star.awt.XWindow;
26 import com.sun.star.lang.XInitialization;
27 import com.sun.star.ui.dialogs.XExecutableDialog;
28 
29 import com.sun.star.lang.IllegalArgumentException;
30 import com.sun.star.lang.WrappedTargetException;
31 import com.sun.star.lang.XMultiServiceFactory;
32 import com.sun.star.awt.VclWindowPeerAttribute;
33 import com.sun.star.awt.XWindowPeer;
34 import com.sun.star.beans.PropertyValue;
35 import com.sun.star.beans.UnknownPropertyException;
36 import com.sun.star.beans.XPropertySet;
37 import com.sun.star.container.XHierarchicalNameAccess;
38 import com.sun.star.container.XHierarchicalNameContainer;
39 import com.sun.star.container.XNameAccess;
40 import com.sun.star.container.XNameContainer;
41 import com.sun.star.frame.XModel;
42 import com.sun.star.frame.XStorable;
43 import com.sun.star.lang.XComponent;
44 import com.sun.star.sdbc.DataType;
45 import com.sun.star.sdb.XOfficeDatabaseDocument;
46 import com.sun.star.sdb.XDocumentDataSource;
47 import com.sun.star.sdb.tools.XConnectionTools;
48 import com.sun.star.sdbcx.XColumnsSupplier;
49 
50 import com.sun.star.ucb.XSimpleFileAccess;
51 import com.sun.star.uno.UnoRuntime;
52 import com.sun.star.uno.XInterface;
53 import com.sun.star.uno.AnyConverter;
54 import com.sun.star.util.XCloseable;
55 import com.sun.star.util.XNumberFormatsSupplier;
56 
57 import com.sun.star.task.XInteractionHandler;
58 import com.sun.star.sdb.XFormDocumentsSupplier;
59 import com.sun.star.sdb.XQueryDefinitionsSupplier;
60 import com.sun.star.sdb.XReportDocumentsSupplier;
61 import com.sun.star.sdbc.SQLException;
62 import com.sun.star.sdbc.XDatabaseMetaData;
63 import com.sun.star.sdbc.XDataSource;
64 import com.sun.star.sdbc.XResultSet;
65 import com.sun.star.sdbc.XRow;
66 import com.sun.star.sdb.XCompletedConnection;
67 import com.sun.star.lang.Locale;
68 import com.sun.star.lang.XSingleServiceFactory;
69 import com.sun.star.sdb.XQueriesSupplier;
70 import com.sun.star.sdbc.XConnection;
71 import com.sun.star.sdbcx.XTablesSupplier;
72 import com.sun.star.wizards.common.Configuration;
73 import com.sun.star.wizards.common.Desktop;
74 import com.sun.star.wizards.common.FileAccess;
75 import com.sun.star.wizards.common.JavaTools;
76 import com.sun.star.wizards.common.NamedValueCollection;
77 import com.sun.star.wizards.common.NumberFormatter;
78 import com.sun.star.wizards.common.Properties;
79 import com.sun.star.wizards.common.Resource;
80 import com.sun.star.wizards.common.SystemDialog;
81 import com.sun.star.uno.Any;
82 import com.sun.star.wizards.common.PropertyNames;
83 import java.util.Vector;
84 import java.util.logging.Level;
85 import java.util.logging.Logger;
86 
87 public class DBMetaData
88 {
89     private XNameAccess xQueryNames;
90     public XDatabaseMetaData xDBMetaData;
91     private XDataSource m_dataSource;
92     private XPropertySet m_dataSourceSettings;
93     private XOfficeDatabaseDocument xModel;
94     private XPropertySet xDataSourcePropertySet;
95     public String[] DataSourceNames;
96     public String[] CommandNames;
97     public java.util.Vector CommandObjects = new Vector(1);
98     public Locale aLocale;
99     public int[] CommandTypes;
100     public String DataSourceName;
101     public com.sun.star.sdbc.XConnection DBConnection;
102     private com.sun.star.sdb.tools.XConnectionTools m_connectionTools;
103     public com.sun.star.lang.XMultiServiceFactory xMSF;
104     public XComponent xConnectionComponent;
105 
106     private XNameAccess xNameAccess;
107     private XInterface xDatabaseContext;
108     private XWindowPeer xWindowPeer;
109     private String[] TableNames = new String[] {};
110     private String[] QueryNames = new String[] {};
111 
112     protected int[][] WidthList;
113     protected static final int[] NumericTypes = {
114             DataType.TINYINT, // ==  -6;
115             DataType.BIGINT, // ==  -5
116             DataType.NUMERIC, // ==  - 2
117             DataType.DECIMAL, // ==   3;
118             DataType.INTEGER, // ==   4;
119             DataType.SMALLINT, // ==   5;
120             DataType.FLOAT, // ==   6;
121             DataType.REAL, // ==   7;
122             DataType.DOUBLE, // ==   8;
123         };
124     protected static final int[] BinaryTypes = { //new int[12];
125             DataType.BINARY,
126             DataType.VARBINARY,
127             DataType.LONGVARBINARY,
128             DataType.BLOB,
129             DataType.SQLNULL,
130             DataType.OBJECT,
131             DataType.DISTINCT,
132             DataType.STRUCT,
133             DataType.ARRAY,
134             DataType.CLOB,
135             DataType.REF
136             /* DataType.OTHER, */
137         };
138 
139     private int iMaxColumnsInSelect;
140     private int iMaxColumnsInGroupBy;
141     private int iMaxColumnNameLength = -1;
142     private int iMaxTableNameLength = -1;
143     private boolean bPasswordIsRequired;
144     private final static int NOLIMIT = 9999999;
145     protected final static int RID_DB_COMMON = 1000;
146     private final static int INVALID = 9999999;
147     public TypeInspector oTypeInspector;
148     private NumberFormatter oNumberFormatter = null;
149     private long lDateCorrection = INVALID;
150     private boolean bdisposeConnection = false;
151 
getDataSourcePropertySet()152     public XPropertySet getDataSourcePropertySet()
153     {
154         return xDataSourcePropertySet;
155     }
156 
DBMetaData(XMultiServiceFactory xMSF)157     public DBMetaData(XMultiServiceFactory xMSF)
158     {
159         getInterfaces(xMSF);
160         InitializeWidthList();
161     }
162 
DBMetaData(XMultiServiceFactory xMSF, Locale _aLocale, NumberFormatter _oNumberFormatter)163     public DBMetaData(XMultiServiceFactory xMSF, Locale _aLocale, NumberFormatter _oNumberFormatter)
164     {
165         oNumberFormatter = _oNumberFormatter;
166         aLocale = _aLocale;
167         getInterfaces(xMSF);
168         InitializeWidthList();
169     }
170 
getNumberFormatter()171     public NumberFormatter getNumberFormatter()
172     {
173         if (oNumberFormatter == null)
174         {
175             try
176             {
177                 XNumberFormatsSupplier xNumberFormatsSupplier = (XNumberFormatsSupplier) AnyConverter.toObject(XNumberFormatsSupplier.class, xDataSourcePropertySet.getPropertyValue("NumberFormatsSupplier"));
178                 //TODO get the locale from the datasource
179                 aLocale = Configuration.getOfficeLocale(xMSF);
180                 oNumberFormatter = new NumberFormatter(xMSF, xNumberFormatsSupplier, aLocale);
181                 lDateCorrection = oNumberFormatter.getNullDateCorrection();
182             }
183             catch (Exception e)
184             {
185                 Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e );
186             }
187         }
188         return oNumberFormatter;
189     }
190 
getNullDateCorrection()191     public long getNullDateCorrection()
192     {
193         if (lDateCorrection == INVALID)
194         {
195             if (oNumberFormatter == null)
196             {
197                 oNumberFormatter = getNumberFormatter();
198             }
199             lDateCorrection = oNumberFormatter.getNullDateCorrection();
200         }
201         return lDateCorrection;
202     }
203 
getInterfaces(XMultiServiceFactory xMSF)204     private void getInterfaces(XMultiServiceFactory xMSF)
205     {
206         try
207         {
208             this.xMSF = xMSF;
209             xDatabaseContext = (XInterface) xMSF.createInstance("com.sun.star.sdb.DatabaseContext");
210             xNameAccess = UnoRuntime.queryInterface( XNameAccess.class, xDatabaseContext );
211             DataSourceNames = xNameAccess.getElementNames();
212         }
213         catch (Exception e)
214         {
215             Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e );
216         }
217     }
218 
setCommandTypes()219     public void setCommandTypes()
220     {
221         int TableCount;
222         int QueryCount;
223         int CommandCount;
224         int i;
225         int a;
226         TableCount = JavaTools.getArraylength(TableNames);
227         QueryCount = JavaTools.getArraylength(QueryNames);
228         CommandCount = TableCount + QueryCount;
229         CommandTypes = new int[CommandCount];
230         if (TableCount > 0)
231         {
232             for (i = 0; i < TableCount; i++)
233             {
234                 CommandTypes[i] = com.sun.star.sdb.CommandType.TABLE;
235             }
236             a = i;
237             for (i = 0; i < QueryCount; i++)
238             {
239                 CommandTypes[a] = com.sun.star.sdb.CommandType.QUERY;
240                 a += 1;
241             }
242         }
243     }
244 
hasTableByName(String _stablename)245     public boolean hasTableByName(String _stablename)
246     {
247         return getTableNamesAsNameAccess().hasByName(_stablename);
248     }
249 
250     @SuppressWarnings("unchecked")
setTableByName(String _tableName)251     public void setTableByName(String _tableName)
252     {
253         CommandObject oTableObject = new CommandObject(_tableName, com.sun.star.sdb.CommandType.TABLE);
254         this.CommandObjects.addElement(oTableObject);
255     }
256 
getTableByName(String _tablename)257     public CommandObject getTableByName(String _tablename)
258     {
259         return getCommandByName(_tablename, com.sun.star.sdb.CommandType.TABLE);
260     }
261 
getQueryByName(String _queryname)262     public CommandObject getQueryByName(String _queryname)
263     {
264         return getCommandByName(_queryname, com.sun.star.sdb.CommandType.QUERY);
265     }
266 
getCommandByName(String _commandname, int _commandtype)267     public CommandObject getCommandByName(String _commandname, int _commandtype)
268     {
269         CommandObject oCommand = null;
270         for (int i = 0; i < CommandObjects.size(); i++)
271         {
272             oCommand = (CommandObject) CommandObjects.elementAt(i);
273             if ((oCommand.Name.equals(_commandname)) && (oCommand.CommandType == _commandtype))
274             {
275                 return oCommand;
276             }
277         }
278         if (oCommand == null)
279         {
280             oCommand = new CommandObject(_commandname, _commandtype);
281             CommandObjects.addElement(oCommand);
282         }
283         return oCommand;
284     }
285 
setQueryByName(String _QueryName)286     public void setQueryByName(String _QueryName)
287     {
288         CommandObject oQueryObject = new CommandObject(_QueryName, com.sun.star.sdb.CommandType.QUERY);
289         this.CommandObjects.addElement(oQueryObject);
290     }
291 
292     public class CommandObject
293     {
294 
295         private XNameAccess xColumns;
296         private XPropertySet xPropertySet;
297         private String Name;
298         private int CommandType;
299 
CommandObject(String _CommandName, int _CommandType)300         public CommandObject(String _CommandName, int _CommandType)
301         {
302             try
303             {
304                 Object oCommand;
305                 this.Name = _CommandName;
306                 this.CommandType = _CommandType;
307                 // if (getTableNamesAsNameAccess() == null)
308                 // {
309                 //     initCommandNames();
310                 // }
311                 if (CommandType == com.sun.star.sdb.CommandType.TABLE)
312                 {
313                     oCommand = getTableNamesAsNameAccess().getByName(Name);
314                 }
315                 else
316                 {
317                     oCommand = getQueryNamesAsNameAccess().getByName(Name);
318                 }
319                 XColumnsSupplier xCommandCols = UnoRuntime.queryInterface( XColumnsSupplier.class, oCommand );
320                 xPropertySet = UnoRuntime.queryInterface( XPropertySet.class, oCommand );
321 // TODO: Performance leak getColumns() take very long.
322                 xColumns = UnoRuntime.queryInterface( XNameAccess.class, xCommandCols.getColumns() );
323             }
324             catch (Exception e)
325             {
326                 Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e );
327             }
328         }
getColumns()329         public XNameAccess getColumns()
330         {
331             return xColumns;
332         }
getName()333         public String getName()
334         {
335             return Name;
336         }
getPropertySet()337         public XPropertySet getPropertySet()
338         {
339             return xPropertySet;
340         }
341     }
342 
hasEscapeProcessing(XPropertySet _xQueryPropertySet)343     public boolean hasEscapeProcessing(XPropertySet _xQueryPropertySet)
344     {
345         boolean bHasEscapeProcessing = false;
346         try
347         {
348             if (_xQueryPropertySet.getPropertySetInfo().hasPropertyByName("EscapeProcessing"))
349             {
350                 bHasEscapeProcessing = AnyConverter.toBoolean(_xQueryPropertySet.getPropertyValue("EscapeProcessing"));
351             }
352         }
353         catch (Exception e)
354         {
355             Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e );
356         }
357         return bHasEscapeProcessing;
358     }
359 
getQueryNamesAsNameAccess()360     public XNameAccess getQueryNamesAsNameAccess()
361     {
362         XQueriesSupplier xDBQueries = UnoRuntime.queryInterface( XQueriesSupplier.class, DBConnection );
363         xQueryNames = xDBQueries.getQueries();
364         return xQueryNames;
365     }
366 
getTableNamesAsNameAccess()367     public XNameAccess getTableNamesAsNameAccess()
368     {
369         XTablesSupplier xDBTables = UnoRuntime.queryInterface( XTablesSupplier.class, DBConnection );
370         return xDBTables.getTables();
371     }
372 
getQueryNames()373     public String[] getQueryNames()
374     {
375         if (QueryNames != null)
376         {
377             if (QueryNames.length > 0)
378             {
379                 return QueryNames;
380             }
381         }
382         QueryNames = getQueryNamesAsNameAccess().getElementNames();
383         return QueryNames;
384     }
385 
getTableNames()386     public String[] getTableNames()
387     {
388         if (TableNames != null)
389         {
390             if (TableNames.length > 0)
391             {
392                 return TableNames;
393             }
394         }
395         TableNames = getTableNamesAsNameAccess().getElementNames();
396         return TableNames;
397     }
398 
InitializeWidthList()399     private void InitializeWidthList()
400     {
401         WidthList = new int[17][2];
402         WidthList[0][0] = DataType.BIT; // ==  -7;
403         WidthList[1][0] = DataType.BOOLEAN; // = 16
404         WidthList[2][0] = DataType.TINYINT; // ==  -6;
405         WidthList[3][0] = DataType.BIGINT; // ==  -5;
406         WidthList[4][0] = DataType.LONGVARCHAR; // ==  -1;
407         WidthList[5][0] = DataType.CHAR; // ==   1;
408         WidthList[6][0] = DataType.NUMERIC; // ==   2;
409         WidthList[7][0] = DataType.DECIMAL; // ==   3;  [mit Nachkommastellen]
410         WidthList[8][0] = DataType.INTEGER; // ==   4;
411         WidthList[9][0] = DataType.SMALLINT; // ==   5;
412         WidthList[10][0] = DataType.FLOAT; // ==   6;
413         WidthList[11][0] = DataType.REAL; // ==   7;
414         WidthList[12][0] = DataType.DOUBLE; // ==   8;
415         WidthList[13][0] = DataType.VARCHAR; // ==  12;
416         WidthList[14][0] = DataType.DATE; // ==  91;
417         WidthList[15][0] = DataType.TIME; // ==  92;
418         WidthList[16][0] = DataType.TIMESTAMP; // ==  93;
419         // NumericTypes are all types where aggregate functions can be performed on.
420         // Similarly to a major competitor date/time/timmestamp fields are not included
421 
422 
423     }
424 
isBinaryDataType(int _itype)425     public boolean isBinaryDataType(int _itype)
426     {
427         if (NumericTypes == null)
428         {
429             InitializeWidthList();
430         }
431         return (JavaTools.FieldInIntTable(BinaryTypes, _itype) > -1);
432     }
433 
getMaxTablesInSelect()434     public int getMaxTablesInSelect()
435     {
436         try
437         {
438             int itablecount = xDBMetaData.getMaxTablesInSelect();
439             if (itablecount == 0)
440             {
441                 return DBMetaData.NOLIMIT;
442             }
443             else
444             {
445                 return itablecount;
446             }
447         }
448         catch (SQLException e)
449         {
450             Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e );
451             return - 1;
452         }
453     }
454 
getMaxColumnsInSelect()455     public int getMaxColumnsInSelect()
456     {
457         return iMaxColumnsInSelect;
458     }
459 
getMaxColumnsInGroupBy()460     public int getMaxColumnsInGroupBy()
461     {
462         return iMaxColumnsInGroupBy;
463     }
464 
setMaxColumnsInSelect()465     private void setMaxColumnsInSelect() throws SQLException
466     {
467         iMaxColumnsInSelect = xDBMetaData.getMaxColumnsInSelect();
468         if (iMaxColumnsInSelect == 0)
469         {
470             iMaxColumnsInSelect = DBMetaData.NOLIMIT;
471         }
472     }
473 
setMaxColumnsInGroupBy()474     private void setMaxColumnsInGroupBy() throws SQLException
475     {
476         iMaxColumnsInGroupBy = xDBMetaData.getMaxColumnsInGroupBy();
477         if (iMaxColumnsInGroupBy == 0)
478         {
479             iMaxColumnsInGroupBy = DBMetaData.NOLIMIT;
480         }
481     }
482 
getMaxColumnsInTable()483     public int getMaxColumnsInTable() throws SQLException
484     {
485         int iMaxColumnsInTable = xDBMetaData.getMaxColumnsInTable();
486         if (iMaxColumnsInTable == 0)
487         {
488             iMaxColumnsInTable = DBMetaData.NOLIMIT;
489         }
490         return iMaxColumnsInTable;
491     }
492 
getDataSourceObjects()493     private void getDataSourceObjects() throws Exception
494     {
495         try
496         {
497             xDBMetaData = DBConnection.getMetaData();
498             getDataSourceInterfaces();
499             setMaxColumnsInGroupBy();
500             setMaxColumnsInSelect();
501         }
502         catch (SQLException e)
503         {
504             Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e );
505         }
506     }
507 
ensureDataSourceSettings()508     private void ensureDataSourceSettings() throws UnknownPropertyException, WrappedTargetException
509     {
510         if ( m_dataSourceSettings != null )
511             return;
512 
513         XPropertySet dataSourceProperties = UnoRuntime.queryInterface( XPropertySet.class, getDataSource() );
514         m_dataSourceSettings = UnoRuntime.queryInterface( XPropertySet.class, dataSourceProperties.getPropertyValue( "Settings" ) );
515     }
516 
isSQL92CheckEnabled()517     public boolean isSQL92CheckEnabled()
518     {
519         boolean isSQL92CheckEnabled = false;
520         try
521         {
522             ensureDataSourceSettings();
523             isSQL92CheckEnabled = AnyConverter.toBoolean( m_dataSourceSettings.getPropertyValue( "EnableSQL92Check" ) );
524         }
525         catch (Exception e)
526         {
527             Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e );
528         }
529         return isSQL92CheckEnabled;
530     }
531 
verifyName(String _sname, int _maxlen)532     public String verifyName(String _sname, int _maxlen)
533     {
534         if (_sname.length() > _maxlen)
535         {
536             return _sname.substring(0, _maxlen);
537         }
538         if (this.isSQL92CheckEnabled())
539         {
540             return Desktop.removeSpecialCharacters(xMSF, Configuration.getOfficeLocale(xMSF), _sname);
541         }
542         return _sname;
543     }
544 
getDataSource()545     public XDataSource getDataSource()
546     {
547         if (m_dataSource == null)
548         {
549             try
550             {
551                     Object oDataSource = xNameAccess.getByName(DataSourceName);
552                     m_dataSource = UnoRuntime.queryInterface( XDataSource.class, oDataSource );
553             }
554             catch (com.sun.star.container.NoSuchElementException e)
555             {
556             }
557             catch (com.sun.star.lang.WrappedTargetException e)
558             {
559             }
560         }
561         return m_dataSource;
562     }
563 
setDataSourceByName(String _DataSourceName)564     private void setDataSourceByName(String _DataSourceName)
565     {
566         try
567         {
568             this.DataSourceName = _DataSourceName;
569             getDataSourceInterfaces();
570             XDocumentDataSource xDocu = UnoRuntime.queryInterface( XDocumentDataSource.class, getDataSource() );
571             if (xDocu != null)
572             {
573                 xModel = xDocu.getDatabaseDocument();
574             }
575         }
576         catch (Exception e)
577         {
578             Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e );
579         }
580     }
581 
getDataSourceInterfaces()582     public void getDataSourceInterfaces() throws Exception
583     {
584         xDataSourcePropertySet = UnoRuntime.queryInterface( XPropertySet.class, getDataSource() );
585         bPasswordIsRequired = ((Boolean) xDataSourcePropertySet.getPropertyValue("IsPasswordRequired")).booleanValue();
586     }
587 
getConnection(PropertyValue[] curproperties)588     public boolean getConnection(PropertyValue[] curproperties)
589     {
590         try
591         {
592             XConnection xConnection = null;
593             if (Properties.hasPropertyValue(curproperties, PropertyNames.ACTIVE_CONNECTION))
594             {
595                 xConnection = UnoRuntime.queryInterface( XConnection.class, Properties.getPropertyValue( curproperties, PropertyNames.ACTIVE_CONNECTION ) );
596                 if (xConnection != null)
597                 {
598                     com.sun.star.container.XChild child = UnoRuntime.queryInterface( com.sun.star.container.XChild.class, xConnection );
599 
600                     m_dataSource = UnoRuntime.queryInterface( XDataSource.class, child.getParent() );
601                     XDocumentDataSource xDocu = UnoRuntime.queryInterface( XDocumentDataSource.class, m_dataSource );
602                     if (xDocu != null)
603                     {
604                         xModel = xDocu.getDatabaseDocument();
605                     }
606                     XPropertySet xPSet = UnoRuntime.queryInterface( XPropertySet.class, m_dataSource );
607                     if (xPSet != null)
608                     {
609                         DataSourceName = AnyConverter.toString(xPSet.getPropertyValue(PropertyNames.PROPERTY_NAME));
610                     }
611                     return getConnection(xConnection);
612                 }
613                 else
614                 {
615                     bdisposeConnection = true;
616                 }
617             }
618             else
619             {
620                 bdisposeConnection = true;
621             }
622             if (Properties.hasPropertyValue(curproperties, "DataSourceName"))
623             {
624                 String sDataSourceName = AnyConverter.toString(Properties.getPropertyValue(curproperties, "DataSourceName"));
625                 return getConnection(sDataSourceName);
626             }
627             else if (Properties.hasPropertyValue(curproperties, "DataSource"))
628             {
629                 m_dataSource = UnoRuntime.queryInterface( XDataSource.class, Properties.getPropertyValue( curproperties, "DataSource" ) );
630                 XDocumentDataSource xDocu = UnoRuntime.queryInterface( XDocumentDataSource.class, this.m_dataSource );
631                 if (xDocu != null)
632                 {
633                     xModel = xDocu.getDatabaseDocument();
634                 }
635                 return getConnection(m_dataSource);
636             }
637             if (Properties.hasPropertyValue(curproperties, "DatabaseLocation"))
638             {
639                 String sDataSourceName = AnyConverter.toString(Properties.getPropertyValue(curproperties, "DatabaseLocation"));
640                 return getConnection(sDataSourceName);
641             }
642         }
643         catch (IllegalArgumentException e)
644         {
645             Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e );
646         }
647         catch (UnknownPropertyException e)
648         {
649             Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e );
650         }
651         catch (WrappedTargetException e)
652         {
653             Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e );
654         }
655 
656         return false;
657     }
658 
getConnection(String _DataSourceName)659     private boolean getConnection(String _DataSourceName)
660     {
661         setDataSourceByName(_DataSourceName);
662          return getConnection( getDataSource() );
663     }
664 
getConnection(com.sun.star.sdbc.XConnection _DBConnection)665     private boolean getConnection(com.sun.star.sdbc.XConnection _DBConnection)
666     {
667         try
668         {
669             this.DBConnection = _DBConnection;
670             this.m_connectionTools = UnoRuntime.queryInterface( XConnectionTools.class, this.DBConnection );
671             getDataSourceObjects();
672             return true;
673         }
674         catch (Exception e)
675         {
676             Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e );
677             return false;
678         }
679     }
680 
getConnection(XDataSource _dataSource)681     private boolean getConnection(XDataSource _dataSource)
682     {
683         Resource oResource = new Resource(xMSF, "Database", "dbw");
684         try
685         {
686             int iMsg = 0;
687             boolean bgetConnection = false;
688             if (DBConnection != null)
689             {
690                 xConnectionComponent.dispose();
691             }
692             getDataSourceInterfaces();
693             if (!bPasswordIsRequired)
694             {
695                 DBConnection = _dataSource.getConnection(PropertyNames.EMPTY_STRING, PropertyNames.EMPTY_STRING);
696                 bgetConnection = true;
697             }
698             else
699             {
700                 XInteractionHandler xInteractionHandler = UnoRuntime.queryInterface( XInteractionHandler.class, xMSF.createInstance("com.sun.star.task.InteractionHandler") );
701                 boolean bExitLoop = true;
702                 do
703                 {
704                     XCompletedConnection xCompleted2 = UnoRuntime.queryInterface( XCompletedConnection.class, _dataSource );
705                     try
706                     {
707                         DBConnection = xCompleted2.connectWithCompletion( xInteractionHandler );
708                         bgetConnection = DBConnection != null;
709                         if (!bgetConnection)
710                         {
711                             bExitLoop = true;
712                         }
713                     }
714                     catch (Exception exception)
715                     {
716                         // Note:  WindowAttributes from toolkit/source/awt/vclxtoolkit.cxx
717                         String sMsgNoConnection = oResource.getResText(RID_DB_COMMON + 14);
718                         iMsg = showMessageBox("QueryBox", VclWindowPeerAttribute.RETRY_CANCEL, sMsgNoConnection);
719                         bExitLoop = iMsg == 0;
720                         bgetConnection = false;
721                     }
722                 }
723                 while (!bExitLoop);
724             }
725             if (!bgetConnection)
726             {
727                 String sMsgConnectionImpossible = oResource.getResText(RID_DB_COMMON + 35);
728                 showMessageBox("ErrorBox", VclWindowPeerAttribute.OK, sMsgConnectionImpossible);
729             }
730             else
731             {
732                 xConnectionComponent = UnoRuntime.queryInterface( XComponent.class, DBConnection );
733                 m_connectionTools = UnoRuntime.queryInterface( XConnectionTools.class, DBConnection );
734                 getDataSourceObjects();
735             }
736             return bgetConnection;
737         }
738         catch (Exception e)
739         {
740             String sMsgConnectionImpossible = oResource.getResText(RID_DB_COMMON + 35);
741             showMessageBox("ErrorBox", VclWindowPeerAttribute.OK, sMsgConnectionImpossible);
742             Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e );
743             return false;
744         }
745     }
746 
getMaxColumnNameLength()747     public int getMaxColumnNameLength()
748     {
749         try
750         {
751             if (iMaxColumnNameLength <= 0)
752             {
753                 iMaxColumnNameLength = xDBMetaData.getMaxColumnNameLength();
754             }
755             return iMaxColumnNameLength;
756         }
757         catch (SQLException e)
758         {
759             Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e );
760             return 0;
761         }
762     }
763 
getMaxTableNameLength()764     public int getMaxTableNameLength()
765     {
766         try
767         {
768             if (iMaxTableNameLength <= 0)
769             {
770                 iMaxTableNameLength = xDBMetaData.getMaxTableNameLength();
771             }
772             return iMaxTableNameLength;
773         }
774         catch (SQLException e)
775         {
776             Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e );
777             return 0;
778         }
779     }
780 
supportsPrimaryKeys()781     public boolean supportsPrimaryKeys()
782     {
783         boolean supportsPrimaryKeys = false;
784         try
785         {
786             ensureDataSourceSettings();
787             Any primaryKeySupport = (Any)m_dataSourceSettings.getPropertyValue( "PrimaryKeySupport" );
788             if ( AnyConverter.isVoid( primaryKeySupport ) )
789                 supportsPrimaryKeys = supportsCoreSQLGrammar();
790             else
791                 supportsPrimaryKeys = AnyConverter.toBoolean( primaryKeySupport );
792         }
793         catch ( Exception ex )
794         {
795             Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, ex );
796         }
797         return supportsPrimaryKeys;
798     }
799 
supportsCoreSQLGrammar()800     public boolean supportsCoreSQLGrammar()
801     {
802         try
803         {
804             return xDBMetaData.supportsCoreSQLGrammar();
805         }
806         catch (SQLException e)
807         {
808             Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e );
809             return false;
810         }
811     }
812 
supportsAutoIncrementation()813     public boolean supportsAutoIncrementation()
814     {
815         return false;
816     }
817 
supportsQueriesInFrom()818     public boolean supportsQueriesInFrom()
819     {
820         return m_connectionTools.getDataSourceMetaData().supportsQueriesInFrom();
821     }
822 
suggestName( final int i_objectType, final String i_baseName )823     public String suggestName( final int i_objectType, final String i_baseName ) throws IllegalArgumentException
824     {
825         return m_connectionTools.getObjectNames().suggestName( i_objectType, i_baseName );
826     }
827 
828     /**
829      * inserts a Query to a datasource; There is no validation if the queryname is already existing in the datasource
830      * @param oQuery
831      * @param QueryName
832      */
createQuery(SQLQueryComposer _oSQLQueryComposer, String _QueryName)833     public boolean createQuery(SQLQueryComposer _oSQLQueryComposer, String _QueryName)
834     {
835         try
836         {
837             XQueryDefinitionsSupplier xQueryDefinitionsSuppl = UnoRuntime.queryInterface( XQueryDefinitionsSupplier.class, m_dataSource );
838             XNameAccess xQueryDefs = xQueryDefinitionsSuppl.getQueryDefinitions();
839             XSingleServiceFactory xSSFQueryDefs = UnoRuntime.queryInterface( XSingleServiceFactory.class, xQueryDefs );
840             Object oQuery = xSSFQueryDefs.createInstance(); //"com.sun.star.sdb.QueryDefinition"
841             XPropertySet xPSet = UnoRuntime.queryInterface( XPropertySet.class, oQuery );
842 
843             String s = _oSQLQueryComposer.m_xQueryAnalyzer.getQuery();
844             xPSet.setPropertyValue(PropertyNames.COMMAND, s);
845 
846             XNameContainer xNameCont = UnoRuntime.queryInterface( XNameContainer.class, xQueryDefs );
847             m_connectionTools.getObjectNames().checkNameForCreate(com.sun.star.sdb.CommandType.QUERY, _QueryName);
848             xNameCont.insertByName(_QueryName, oQuery);
849             return true;
850         }
851         catch (WrappedTargetException exception)
852         {
853             SQLException sqlError = null;
854             try
855             {
856                 sqlError = (SQLException) exception.TargetException;
857             }
858             catch (ClassCastException castError)
859             {
860             }
861 
862             if (sqlError != null)
863             {
864                 callSQLErrorMessageDialog(sqlError, null);
865                 return false;
866             }
867             exception.printStackTrace(System.out);
868         }
869         catch (SQLException e)
870         {
871             Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e );
872         }
873         catch (Exception e)
874         {
875             Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e );
876         }
877         return false;
878     }
879 
dispose()880     public void dispose()
881     {
882         if ((DBConnection != null) && (this.bdisposeConnection))
883         {
884             xConnectionComponent.dispose();
885         }
886     }
887 
getReportDocuments()888     public XHierarchicalNameAccess getReportDocuments()
889     {
890         XReportDocumentsSupplier xReportDocumentSuppl = UnoRuntime.queryInterface( XReportDocumentsSupplier.class, this.xModel );
891         xReportDocumentSuppl.getReportDocuments();
892         return UnoRuntime.queryInterface( XHierarchicalNameAccess.class, xReportDocumentSuppl.getReportDocuments() );
893     }
894 
getFormDocuments()895     public XHierarchicalNameAccess getFormDocuments()
896     {
897         XFormDocumentsSupplier xFormDocumentSuppl = UnoRuntime.queryInterface( XFormDocumentsSupplier.class, xModel );
898         return UnoRuntime.queryInterface( XHierarchicalNameAccess.class, xFormDocumentSuppl.getFormDocuments() );
899     }
900 
hasFormDocumentByName(String _sFormName)901     public boolean hasFormDocumentByName(String _sFormName)
902     {
903         XFormDocumentsSupplier xFormDocumentSuppl = UnoRuntime.queryInterface( XFormDocumentsSupplier.class, xModel );
904         XNameAccess xFormNameAccess = UnoRuntime.queryInterface( XNameAccess.class, xFormDocumentSuppl.getFormDocuments() );
905         return xFormNameAccess.hasByName(_sFormName);
906     }
907 
addFormDocument(XComponent _xComponent)908     public void addFormDocument(XComponent _xComponent)
909     {
910         XHierarchicalNameAccess _xFormDocNameAccess = getFormDocuments();
911         addDatabaseDocument(_xComponent, _xFormDocNameAccess, false);
912     }
913 
addReportDocument(XComponent _xComponent, boolean _bcreatedynamicreport)914     public void addReportDocument(XComponent _xComponent, boolean _bcreatedynamicreport)
915     {
916         XHierarchicalNameAccess xReportDocNameAccess = getReportDocuments();
917         addDatabaseDocument(_xComponent, xReportDocNameAccess, _bcreatedynamicreport);
918     }
919 
920     /**
921      * adds the passed document as a report or a form to the database. Afterwards the document is deleted.
922      * the document may not be open
923      * @param _xComponent
924      * @param _xDocNameAccess
925      * @param _bcreateTemplate  describes the type of the document: "form" or "report"
926      */
addDatabaseDocument(XComponent _xComponent, XHierarchicalNameAccess _xDocNameAccess, boolean i_createTemplate)927     public void addDatabaseDocument(XComponent _xComponent, XHierarchicalNameAccess _xDocNameAccess, boolean i_createTemplate)
928     {
929         try
930         {
931             XModel xDocumentModel = UnoRuntime.queryInterface( XModel.class, _xComponent );
932             String documentURL = xDocumentModel.getURL();
933             String basename = FileAccess.getBasename(documentURL, "/");
934             XCloseable xCloseable = UnoRuntime.queryInterface( XCloseable.class, _xComponent );
935             xCloseable.close(false);
936 
937             NamedValueCollection creationArgs = new NamedValueCollection();
938             creationArgs.put( PropertyNames.PROPERTY_NAME, basename );
939             creationArgs.put( PropertyNames.URL, documentURL );
940             creationArgs.put( "AsTemplate", i_createTemplate );
941             XMultiServiceFactory xDocMSF = UnoRuntime.queryInterface( XMultiServiceFactory.class, _xDocNameAccess );
942             Object oDBDocument = xDocMSF.createInstanceWithArguments( "com.sun.star.sdb.DocumentDefinition", creationArgs.getPropertyValues() );
943             XHierarchicalNameContainer xHier = UnoRuntime.queryInterface( XHierarchicalNameContainer.class, _xDocNameAccess );
944             String sdocname = Desktop.getUniqueName(_xDocNameAccess, basename);
945             xHier.insertByHierarchicalName(sdocname, oDBDocument);
946             XInterface xInterface = (XInterface) xMSF.createInstance("com.sun.star.ucb.SimpleFileAccess");
947             XSimpleFileAccess xSimpleFileAccess = UnoRuntime.queryInterface( XSimpleFileAccess.class, xInterface );
948             xSimpleFileAccess.kill(documentURL);
949         }
950         catch (Exception e)
951         {
952             Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e );
953         }
954     }
955 
createTypeInspector()956     public void createTypeInspector() throws SQLException
957     {
958         oTypeInspector = new TypeInspector(xDBMetaData.getTypeInfo());
959     }
960 
getDBDataTypeInspector()961     public TypeInspector getDBDataTypeInspector()
962     {
963         return oTypeInspector;
964     }
965 
StringsFromResultSet(XResultSet _xResultSet, int _icol)966     private String[] StringsFromResultSet(XResultSet _xResultSet, int _icol)
967     {
968         String[] sColValues = null;
969         try
970         {
971             XRow xRow = UnoRuntime.queryInterface( XRow.class, _xResultSet );
972             Vector aColVector = new Vector();
973             while (_xResultSet.next())
974             {
975                 aColVector.addElement(xRow.getString(_icol));
976             }
977             sColValues = new String[aColVector.size()];
978             aColVector.toArray(sColValues);
979         }
980         catch (SQLException e)
981         {
982             Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e );
983         }
984         return sColValues;
985     }
986 
getCatalogNames()987     public String[] getCatalogNames()
988     {
989         try
990         {
991             XResultSet xResultSet = xDBMetaData.getCatalogs();
992             return StringsFromResultSet(xResultSet, 1);
993         }
994         catch (SQLException e)
995         {
996             Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e );
997             return null;
998         }
999     }
1000 
getSchemaNames()1001     public String[] getSchemaNames()
1002     {
1003         try
1004         {
1005             XResultSet xResultSet = xDBMetaData.getSchemas();
1006             return StringsFromResultSet(xResultSet, 1);
1007         }
1008         catch (SQLException e)
1009         {
1010             Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e );
1011             return null;
1012         }
1013     }
1014 
storeDatabaseDocumentToTempPath(XComponent _xcomponent, String _storename)1015     public boolean storeDatabaseDocumentToTempPath(XComponent _xcomponent, String _storename)
1016     {
1017         try
1018         {
1019             XInterface xInterface = (XInterface) xMSF.createInstance("com.sun.star.ucb.SimpleFileAccess");
1020             XSimpleFileAccess xSimpleFileAccess = UnoRuntime.queryInterface( XSimpleFileAccess.class, xInterface );
1021             String storepath = FileAccess.getOfficePath(xMSF, "Temp", xSimpleFileAccess) + "/" + _storename;
1022             XStorable xStoreable = UnoRuntime.queryInterface( XStorable.class, _xcomponent );
1023             PropertyValue[] oStoreProperties = new PropertyValue[1];
1024             oStoreProperties[0] = Properties.createProperty("FilterName", "writer8");
1025             storepath += ".odt";
1026             xStoreable.storeAsURL(storepath, oStoreProperties);
1027             return true;
1028         }
1029         catch (Exception e)
1030         {
1031             Logger.getLogger( DBMetaData.class.getName() ).log( Level.SEVERE, null, e );
1032             return false;
1033         }
1034     }
1035 
showMessageBox(String windowServiceName, int windowAttribute, String MessageText)1036     public int showMessageBox(String windowServiceName, int windowAttribute, String MessageText)
1037     {
1038         if (getWindowPeer() != null)
1039         {
1040             return SystemDialog.showMessageBox(xMSF, xWindowPeer, windowServiceName, windowAttribute, MessageText);
1041         }
1042         else
1043         {
1044             return SystemDialog.showMessageBox(xMSF, windowServiceName, windowAttribute, MessageText);
1045         }
1046     }
1047 
1048     /**
1049      * @return Returns the xWindowPeer.
1050      */
getWindowPeer()1051     public XWindowPeer getWindowPeer()
1052     {
1053         return xWindowPeer;
1054     }
1055 
1056     /**
1057      * @param windowPeer The xWindowPeer to set.
1058      * Should be called as soon as a Windowpeer of a wizard dialog is available
1059      * The windowpeer is needed to call a Messagebox
1060      */
setWindowPeer(XWindowPeer windowPeer)1061     public void setWindowPeer(XWindowPeer windowPeer)
1062     {
1063         xWindowPeer = windowPeer;
1064     }
1065 
callSQLErrorMessageDialog(SQLException oSQLException, XWindow _xWindow)1066     public void callSQLErrorMessageDialog(SQLException oSQLException, XWindow _xWindow)
1067     {
1068         try
1069         {
1070             Object oDialog = xMSF.createInstance("com.sun.star.sdb.ErrorMessageDialog");
1071             XInitialization xInitialization = UnoRuntime.queryInterface( XInitialization.class, oDialog );
1072             PropertyValue[] aPropertyValue = new PropertyValue[2];
1073             aPropertyValue[0] = Properties.createProperty("SQLException", oSQLException);
1074             aPropertyValue[1] = Properties.createProperty("ParentWindow", _xWindow);
1075             xInitialization.initialize(aPropertyValue);
1076             XExecutableDialog xExecutableDialog = UnoRuntime.queryInterface( XExecutableDialog.class, oDialog );
1077             xExecutableDialog.execute();
1078         }
1079         catch (com.sun.star.uno.Exception ex)
1080         {
1081             Logger.getLogger( getClass().getName() ).log( Level.SEVERE, "error calling the error dialog", ex );
1082         }
1083     }
1084 
finish()1085     public void finish()
1086     {
1087         xQueryNames = null;
1088         xNameAccess = null;
1089         xDatabaseContext = null;
1090         xDBMetaData = null;
1091         m_dataSource = null;
1092         xModel = null;
1093         xDataSourcePropertySet = null;
1094         xWindowPeer = null;
1095         DBConnection = null;
1096         m_connectionTools = null;
1097         xMSF = null;
1098         xConnectionComponent = null;
1099         CommandObjects = null;
1100     }
1101 }
1102