View | Details | Raw Unified | Return to issue 120525
Collapse All | Expand All

(-)source/testcase/uno/db/utils/TestCase.java (+140 lines)
Line 0 Link Here
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 testcase.uno.db.utils;
24
25
import java.lang.reflect.InvocationTargetException;
26
import java.lang.reflect.Method;
27
import com.sun.star.beans.PropertyValue;
28
import com.sun.star.beans.XPropertySet;
29
import com.sun.star.bridge.UnoUrlResolver;
30
import com.sun.star.bridge.XUnoUrlResolver;
31
import com.sun.star.comp.helper.Bootstrap;
32
import com.sun.star.connection.NoConnectException;
33
import com.sun.star.frame.XComponentLoader;
34
import com.sun.star.frame.XModel;
35
import com.sun.star.lang.XMultiServiceFactory;
36
// import com.sun.star.uno.Exception;
37
import com.sun.star.uno.UnoRuntime;
38
import com.sun.star.uno.XComponentContext;
39
import java.io.File;
40
import java.io.IOException;
41
import java.net.URI;
42
import java.net.URISyntaxException;
43
44
// ---------- junit imports -----------------
45
import org.junit.AfterClass;
46
import org.junit.BeforeClass;
47
import org.openoffice.test.uno.UnoApp;
48
49
import static org.junit.Assert.*;
50
// ------------------------------------------
51
52
53
public abstract class TestCase
54
{
55
    // --------------------------------------------------------------------------------------------------------
56
    protected final XComponentContext getComponentContext()
57
    {
58
        XComponentContext context = null;
59
        try
60
        {
61
            final XPropertySet orbProps = UnoRuntime.queryInterface( XPropertySet.class, getMSF() );
62
            context = UnoRuntime.queryInterface( XComponentContext.class,
63
                orbProps.getPropertyValue( "DefaultContext" ) );
64
        }
65
        catch ( Exception ex )
66
        {
67
            fail( "could not retrieve the ComponentContext" );
68
        }
69
        return context;
70
    }
71
72
    // --------------------------------------------------------------------------------------------------------
73
    public void before() throws java.lang.Exception
74
    {
75
    }
76
77
    public void after() throws java.lang.Exception
78
    {
79
    }
80
81
    
82
	@BeforeClass
83
	public static void setUpConnection() throws Exception {
84
		app.start();
85
	}
86
87
	@AfterClass
88
	public static void tearDownConnection() throws Exception {
89
		app.close();
90
	}
91
92
	private static final UnoApp app = new UnoApp();
93
94
    // --------------------------------------------------------------------------------------------------------
95
    /** returns the URL of a temporary file which can be used during the test.
96
     * 
97
     *  The file will be deleted when the process exits
98
     *  @return the URL of a temporary file
99
     */
100
    protected final String createTempFileURL() throws IOException
101
    {
102
        final File documentFile = java.io.File.createTempFile( "dbaccess_test", ".odb" ).getAbsoluteFile();
103
        if ( documentFile.exists() )
104
        {
105
            documentFile.delete();
106
        }
107
        return getOOoCompatibleFileURL( documentFile.toURI().toURL().toString() );
108
    }
109
110
    public String getOOoCompatibleFileURL( String _javaFileURL )
111
    {
112
        String returnURL = _javaFileURL;
113
        if ( ( returnURL.indexOf( "file:/" ) == 0 ) && ( returnURL.indexOf( "file:///" ) == -1 ) )
114
        {
115
            // for some reason, the URLs here in Java start with "file:/" only, instead of "file:///"
116
            // Some of the office code doesn't like this ...
117
            returnURL = "file:///" + returnURL.substring( 6 );
118
        }
119
        return returnURL;
120
    }
121
122
123
    protected final XModel loadDocument( final String _docURL ) throws Exception
124
    {
125
        final XComponentLoader loader = UnoRuntime.queryInterface( XComponentLoader.class,
126
            getMSF().createInstance( "com.sun.star.frame.Desktop" ) );
127
        return UnoRuntime.queryInterface( XModel.class,
128
            loader.loadComponentFromURL( _docURL, "_blank", 0, new PropertyValue[] {} ) );
129
    }
130
131
 
132
    protected XMultiServiceFactory getMSF()
133
    {
134
        final XMultiServiceFactory xMSF1 = UnoRuntime.queryInterface(XMultiServiceFactory.class, app.getComponentContext().getServiceManager());
135
        return xMSF1;
136
    }
137
138
139
140
}
(-)source/testcase/uno/db/utils/Connection.java (+114 lines)
Line 0 Link Here
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
 * To change this template, choose Tools | Templates
24
 * and open the template in the editor.
25
 */
26
27
package testcase.uno.db.utils;
28
29
import com.sun.star.lang.XMultiServiceFactory;
30
import com.sun.star.sdb.XSingleSelectQueryComposer;
31
import com.sun.star.sdbc.SQLException;
32
import com.sun.star.sdbc.XConnection;
33
import com.sun.star.sdbc.XDatabaseMetaData;
34
import com.sun.star.sdbc.XPreparedStatement;
35
import com.sun.star.sdbc.XResultSet;
36
import com.sun.star.sdbc.XStatement;
37
import com.sun.star.sdbcx.XTablesSupplier;
38
import com.sun.star.uno.Exception;
39
import com.sun.star.uno.UnoRuntime;
40
import com.sun.star.util.XRefreshable;
41
42
/**
43
 * is a convenience wrapper around a SDB-level connection object
44
 */
45
public class Connection
46
{
47
    private final   XConnection m_connection;
48
49
    public Connection( final XConnection _connection )
50
    {
51
        m_connection = _connection;
52
    }
53
54
    public XConnection  getXConnection()
55
    {
56
        return m_connection;
57
    }
58
59
    public boolean execute( final String _sql ) throws SQLException
60
    {
61
        XStatement statement = createStatement();
62
        return statement.execute( _sql );
63
    }
64
65
    public XResultSet executeQuery( final String _sql ) throws SQLException
66
    {
67
        XStatement statement = createStatement();
68
        return statement.executeQuery( _sql );
69
    }
70
71
    public int executeUpdate( final String _sql ) throws SQLException
72
    {
73
        XStatement statement = createStatement();
74
        return statement.executeUpdate( _sql );
75
    }
76
77
    public void refreshTables()
78
    {
79
        final XTablesSupplier suppTables = UnoRuntime.queryInterface(XTablesSupplier.class, m_connection);
80
        final XRefreshable refresh = UnoRuntime.queryInterface( XRefreshable.class, suppTables.getTables() );
81
        refresh.refresh();
82
    }
83
84
    public XSingleSelectQueryComposer createSingleSelectQueryComposer() throws Exception
85
    {
86
        final XMultiServiceFactory connectionFactory = UnoRuntime.queryInterface( XMultiServiceFactory.class, m_connection );
87
        return UnoRuntime.queryInterface(
88
            XSingleSelectQueryComposer.class, connectionFactory.createInstance( "com.sun.star.sdb.SingleSelectQueryComposer" ) );
89
    }
90
91
    public
92
    XStatement createStatement() throws SQLException
93
    {
94
        return m_connection.createStatement();
95
    }
96
97
    public
98
    XPreparedStatement prepareStatement( String _sql ) throws SQLException
99
    {
100
        return m_connection.prepareStatement( _sql );
101
    }
102
103
    public
104
    XDatabaseMetaData getMetaData() throws SQLException
105
    {
106
        return m_connection.getMetaData();
107
    }
108
109
    public
110
    void close() throws SQLException
111
    {
112
        m_connection.close();
113
    }
114
}
(-)source/testcase/uno/db/utils/HsqlDatabase.java (+208 lines)
Line 0 Link Here
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 testcase.uno.db.utils;
24
25
import com.sun.star.beans.PropertyValue;
26
import com.sun.star.beans.PropertyState;
27
import com.sun.star.beans.XPropertySet;
28
import com.sun.star.container.ElementExistException;
29
import com.sun.star.frame.XStorable;
30
import com.sun.star.lang.XMultiServiceFactory;
31
import com.sun.star.sdb.XOfficeDatabaseDocument;
32
import com.sun.star.sdbc.SQLException;
33
import com.sun.star.sdbcx.XAppend;
34
import com.sun.star.sdbcx.XTablesSupplier;
35
import com.sun.star.uno.UnoRuntime;
36
37
import java.util.HashMap;
38
import java.util.Iterator;
39
import java.util.Set;
40
import java.io.File;
41
42
/**
43
 *
44
 * @author fs93730
45
 */
46
public class HsqlDatabase extends AbstractDatabase
47
{
48
49
    // --------------------------------------------------------------------------------------------------------
50
    public HsqlDatabase(final XMultiServiceFactory orb) throws Exception
51
    {
52
        super(orb);
53
        createDBDocument();
54
    }
55
56
    // --------------------------------------------------------------------------------------------------------
57
    public HsqlDatabase(final XMultiServiceFactory orb, final String _existingDocumentURL) throws Exception
58
    {
59
        super(orb, _existingDocumentURL);
60
    }
61
62
    /** creates an empty database document in a temporary location
63
     */
64
    private void createDBDocument() throws Exception
65
    {
66
        final File documentFile = File.createTempFile("testdb", ".odb");
67
        if ( documentFile.exists() )
68
            documentFile.delete();
69
        m_databaseDocumentFile = URLHelper.getFileURLFromSystemPath(documentFile);
70
71
        m_databaseDocument = (XOfficeDatabaseDocument) UnoRuntime.queryInterface(
72
                XOfficeDatabaseDocument.class, m_orb.createInstance("com.sun.star.sdb.OfficeDatabaseDocument"));
73
        m_dataSource = new DataSource(m_orb, m_databaseDocument.getDataSource());
74
75
        final XPropertySet dsProperties = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, m_databaseDocument.getDataSource());
76
        dsProperties.setPropertyValue("URL", "sdbc:embedded:hsqldb");
77
78
        final XStorable storable = (XStorable) UnoRuntime.queryInterface(XStorable.class, m_databaseDocument);
79
        storable.storeAsURL( m_databaseDocumentFile, new PropertyValue[]
80
			{	new PropertyValue( "PickListEntry", 0, false, PropertyState.DIRECT_VALUE )
81
			} );
82
    }
83
84
    /** drops the table with a given name
85
86
    @param _name
87
    the name of the table to drop
88
    @param _ifExists
89
    TRUE if it should be dropped only when it exists.
90
     */
91
    public void dropTable(final String _name, final boolean _ifExists) throws SQLException
92
    {
93
        final StringBuffer dropStatement = new StringBuffer("DROP TABLE \"");
94
        dropStatement.append(_name);
95
        if (_ifExists)
96
        {
97
            dropStatement.append("\" IF EXISTS");
98
        }
99
        executeSQL(dropStatement.toString());
100
    }
101
102
    public void createTable(final HsqlTableDescriptor _tableDesc, final boolean _dropIfExists) throws SQLException
103
    {
104
        if (_dropIfExists)
105
        {
106
            dropTable(_tableDesc.getName(), true);
107
        }
108
        createTable(_tableDesc);
109
    }
110
111
    /** creates a table
112
     */
113
    public void createTable(final HsqlTableDescriptor _tableDesc) throws SQLException
114
    {
115
        StringBuffer createStatement = new StringBuffer("CREATE CACHED TABLE \"");
116
        createStatement.append(_tableDesc.getName());
117
        createStatement.append("\" ( ");
118
119
        String primaryKeyList = "";
120
121
        final HashMap foreignKeys = new HashMap();
122
        final HashMap foreignKeyRefs = new HashMap();
123
124
        final HsqlColumnDescriptor[] columns = _tableDesc.getColumns();
125
        for (int i = 0; i < columns.length; ++i)
126
        {
127
            if (i > 0)
128
            {
129
                createStatement.append(", ");
130
            }
131
132
            createStatement.append("\"" + columns[i].getName());
133
            createStatement.append("\" " + columns[i].getTypeName());
134
135
            if (columns[i].isRequired())
136
            {
137
                createStatement.append(" NOT NULL");
138
            }
139
140
            if (columns[i].isPrimaryKey())
141
            {
142
                if (primaryKeyList.length() > 0)
143
                {
144
                    primaryKeyList += ", ";
145
                }
146
                primaryKeyList += "\"" + columns[i].getName() + "\"";
147
            }
148
149
            if (columns[i].isForeignKey())
150
            {
151
                final String foreignTable = columns[i].getForeignTable();
152
153
                String foreignKeysForTable = foreignKeys.containsKey(foreignTable) ? (String) foreignKeys.get(foreignTable) : "";
154
                if (foreignKeysForTable.length() > 0)
155
                {
156
                    foreignKeysForTable += ", ";
157
                }
158
                foreignKeysForTable += "\"" + columns[i].getName() + "\"";
159
                foreignKeys.put(foreignTable, foreignKeysForTable);
160
161
                final StringBuffer foreignKeyRefsForTable = new StringBuffer(foreignKeyRefs.containsKey(foreignTable) ? (String) foreignKeyRefs.get(foreignTable) : "");
162
                if (foreignKeyRefsForTable.length() > 0)
163
                {
164
                    foreignKeyRefsForTable.append(", ");
165
                }
166
                foreignKeyRefsForTable.append("\"" + columns[i].getForeignColumn() + "\"");
167
                foreignKeyRefs.put(foreignTable, foreignKeyRefsForTable.toString());
168
            }
169
        }
170
171
        if (primaryKeyList.length() > 0)
172
        {
173
            createStatement.append(", PRIMARY KEY (");
174
            createStatement.append(primaryKeyList);
175
            createStatement.append(')');
176
        }
177
178
        final Set foreignKeyTables = foreignKeys.keySet();
179
        for (final Iterator foreignKey = foreignKeyTables.iterator();
180
                foreignKey.hasNext();)
181
        {
182
            final String foreignTable = (String) foreignKey.next();
183
184
            createStatement.append(", FOREIGN KEY (");
185
            createStatement.append((String) foreignKeys.get(foreignTable));
186
            createStatement.append(") REFERENCES \"");
187
            createStatement.append(foreignTable);
188
            createStatement.append("\"(");
189
            createStatement.append((String) foreignKeyRefs.get(foreignTable));
190
            createStatement.append(')');
191
        }
192
193
        createStatement.append(')');
194
195
        //System.err.println( createStatement );
196
        executeSQL(createStatement.toString());
197
    }
198
199
    /** creates a table in the database. using the SDBCX-API
200
     */
201
    public void createTableInSDBCX(final HsqlTableDescriptor _tableDesc) throws SQLException, ElementExistException
202
    {
203
        final XPropertySet sdbcxDescriptor = _tableDesc.createSdbcxDescriptor(defaultConnection());
204
        final XTablesSupplier suppTables = UnoRuntime.queryInterface( XTablesSupplier.class, defaultConnection().getXConnection() );
205
        final XAppend appendTable = UnoRuntime.queryInterface( XAppend.class, suppTables.getTables() );
206
        appendTable.appendByDescriptor(sdbcxDescriptor);
207
    }
208
}
(-)source/testcase/uno/db/utils/QueryDefinition.java (+71 lines)
Line 0 Link Here
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
24
package testcase.uno.db.utils;
25
26
27
import com.sun.star.beans.PropertyVetoException;
28
import com.sun.star.beans.UnknownPropertyException;
29
import com.sun.star.beans.XPropertySet;
30
import com.sun.star.lang.WrappedTargetException;
31
import com.sun.star.lang.IllegalArgumentException;
32
33
public class QueryDefinition
34
{
35
    XPropertySet    m_queryDef;
36
37
    public QueryDefinition( XPropertySet _queryDef )
38
    {
39
        m_queryDef = _queryDef;
40
    }
41
42
    /** retrieves the command underlying the query definition
43
     *
44
     * This method is a mere wrapped around the <code>getPropertyValue( "Command" )</code> call
45
     */
46
    public final String getCommand() throws WrappedTargetException
47
    {
48
        String command = null;
49
        try {
50
            command = (String)m_queryDef.getPropertyValue( "Command" );
51
        }
52
        catch (UnknownPropertyException e) { }
53
54
        return command;
55
    }
56
57
    /** retrieves the command underlying the query definition
58
     *
59
     * This method is a mere wrapped around the <code>getPropertyValue( "Command" )</code> call
60
     */
61
    public void setCommand( String _command ) throws WrappedTargetException
62
    {
63
        try
64
        {
65
            m_queryDef.setPropertyValue( "Command", _command );
66
        }
67
        catch (UnknownPropertyException e) { }
68
        catch (PropertyVetoException e) { }
69
        catch (IllegalArgumentException e) { }
70
    }
71
};
(-)source/testcase/uno/db/utils/AbstractDatabase.java (+212 lines)
Line 0 Link Here
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 testcase.uno.db.utils;
24
25
import com.sun.star.container.XNameAccess;
26
import com.sun.star.frame.XModel;
27
import com.sun.star.frame.XStorable;
28
import com.sun.star.io.IOException;
29
import com.sun.star.lang.XMultiServiceFactory;
30
import com.sun.star.sdb.XDocumentDataSource;
31
import com.sun.star.sdb.XOfficeDatabaseDocument;
32
import com.sun.star.sdbc.SQLException;
33
import com.sun.star.sdbc.XCloseable;
34
import com.sun.star.sdbc.XStatement;
35
import com.sun.star.uno.UnoRuntime;
36
import com.sun.star.util.CloseVetoException;
37
import java.io.File;
38
39
40
public abstract class AbstractDatabase
41
{
42
    public AbstractDatabase(final XMultiServiceFactory orb) throws Exception
43
    {
44
        m_orb = orb;
45
    }
46
47
    // --------------------------------------------------------------------------------------------------------
48
    public AbstractDatabase(final XMultiServiceFactory orb, final String _existingDocumentURL ) throws Exception
49
    {
50
        m_orb = orb;
51
        createDBDocument( _existingDocumentURL );
52
    }
53
54
    /** returns a connection to the database
55
     *
56
     * Multiple calls to this method return the same connection. The DbaseDatabase object keeps
57
     * the ownership of the connection, so you don't need to (and should not) dispose/close it.
58
     */
59
    public Connection defaultConnection() throws SQLException
60
    {
61
        if ( m_connection == null )
62
            m_connection = new Connection( m_databaseDocument.getDataSource().getConnection("", "") );
63
        
64
        return m_connection;
65
    }
66
67
    /** executes the given SQL statement via the defaultConnection
68
     */
69
    public void executeSQL(final String statementString) throws SQLException
70
    {
71
        final XStatement statement = defaultConnection().createStatement();
72
        statement.execute(statementString);
73
    }
74
75
    /** stores the database document
76
     */
77
    public void store() throws IOException
78
    {
79
        if (m_databaseDocument != null)
80
        {
81
            final XStorable storeDoc = UnoRuntime.queryInterface(XStorable.class, m_databaseDocument);
82
            storeDoc.store();
83
        }
84
    }
85
86
    /** closes the database document
87
     *
88
     *  Any CloseVetoExceptions fired by third parties are ignored, and any reference to the
89
     *  database document is released.
90
     */
91
    public void close()
92
    {
93
        // close connection
94
        final XCloseable closeConn = UnoRuntime.queryInterface( XCloseable.class,
95
            m_connection != null ? m_connection.getXConnection() : null );
96
        if (closeConn != null)
97
        {
98
            try
99
            {
100
                closeConn.close();
101
            }
102
            catch (SQLException e)
103
            {
104
            }
105
        }
106
        m_connection = null;
107
108
        // close document
109
        final com.sun.star.util.XCloseable closeDoc = UnoRuntime.queryInterface( com.sun.star.util.XCloseable.class, m_databaseDocument );
110
        if (closeDoc != null)
111
        {
112
            try
113
            {
114
                closeDoc.close(true);
115
            }
116
            catch (CloseVetoException e)
117
            {
118
            }
119
        }
120
        m_databaseDocument = null;
121
    }
122
123
    /** closes the document, and deletes the underlying file
124
     */
125
    public void closeAndDelete()
126
    {
127
        close();
128
129
        if (m_databaseDocumentFile != null)
130
        {
131
            try
132
            {
133
                final File file = new File(m_databaseDocumentFile);
134
                file.delete();
135
            }
136
            catch (Exception e)
137
            {
138
            }
139
        }
140
    }
141
142
    /** returns the underlying database document
143
     */
144
    public XOfficeDatabaseDocument getDatabaseDocument()
145
    {
146
        return m_databaseDocument;
147
    }
148
149
    /** returns the model interface of the underlying database document
150
     */
151
    public XModel getModel()
152
    {
153
        return UnoRuntime.queryInterface( XModel.class, m_databaseDocument );
154
    }
155
156
    public XMultiServiceFactory getORB()
157
    {
158
        return m_orb;
159
    }
160
161
    // --------------------------------------------------------------------------------------------------------
162
    final protected void createDBDocument(final String _docURL) throws Exception
163
    {
164
        m_databaseDocumentFile = _docURL;
165
166
        final XNameAccess dbContext = UnoRuntime.queryInterface( XNameAccess.class,
167
            m_orb.createInstance( "com.sun.star.sdb.DatabaseContext" ) );
168
        final XDocumentDataSource dataSource = UnoRuntime.queryInterface( XDocumentDataSource.class, dbContext.getByName( _docURL ) );
169
170
        m_databaseDocument = dataSource.getDatabaseDocument();
171
        m_dataSource = new DataSource(m_orb, m_databaseDocument.getDataSource());
172
    }
173
174
    /** returns the URL of the ODB document represented by this instance
175
     */
176
    public String getDocumentURL()
177
    {
178
        return m_databaseDocumentFile;
179
    }
180
181
    /** returns the data source belonging to this database
182
     */
183
    public DataSource getDataSource()
184
    {
185
        return m_dataSource;
186
    }
187
188
    /** creates a row set operating the database, with a given command/type
189
     */
190
    public RowSet createRowSet(final int _commandType, final String _command)
191
    {
192
        return new RowSet(m_orb, getDocumentURL(), _commandType, _command);
193
    }
194
195
    @Override
196
    protected void finalize() throws Throwable
197
    {
198
        closeAndDelete();
199
        super.finalize();
200
    }
201
202
    // the service factory
203
    protected final XMultiServiceFactory m_orb;
204
    // the URL of the temporary file used for the database document
205
    protected String m_databaseDocumentFile;
206
    // the database document
207
    protected XOfficeDatabaseDocument m_databaseDocument;
208
    // the data source belonging to the database document
209
    protected DataSource m_dataSource;
210
    // the default connection
211
    protected Connection    m_connection;
212
}
(-)source/testcase/uno/db/utils/URLHelper.java (+288 lines)
Line 0 Link Here
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
24
package testcase.uno.db.utils;
25
26
// __________ Imports __________
27
28
// exceptions
29
import java.net.MalformedURLException;
30
31
// interfaces
32
import com.sun.star.util.XURLTransformer;
33
34
// others
35
import java.io.File;
36
import java.util.Vector;
37
import java.util.Enumeration;
38
39
40
/**
41
 * It collects some static helper functons to handle URLs.
42
 * Sometimes it's neccessary to convert URL from/to system pathes.
43
 * Or from string to strutural notations (e.g. com.sun.star.util.URL).
44
 * And sometimes java had another notation then the office it has.
45
 *
46
 */
47
public class URLHelper
48
{
49
    // ____________________
50
51
    /**
52
     * Because the office need URLs for loading/saving documents
53
     * we must convert used system pathes.
54
     * And java use another notation for file URLs ... correct it.
55
     *
56
     * @param aSystemPath
57
     *          represent the file in system notation
58
     *
59
     * @return [String]
60
     *          a file url which represent the given system path
61
     */
62
    public static String getFileURLFromSystemPath( File aSystemPath )
63
    {
64
        String sFileURL = null;
65
        try
66
        {
67
            //sFileURL = aSystemPath.toURI().toURL().toString();
68
            sFileURL = aSystemPath.toURL().toString();
69
        }
70
        catch( MalformedURLException exWrong )
71
        {
72
            sFileURL = null;
73
        }
74
75
        // problem of java: file URL's are coded with 1 slash instead of 2 or 3 ones!
76
        // => correct this problem first, otherwise office can't use these URL's
77
        if(
78
            (sFileURL                       != null ) &&
79
            (sFileURL.startsWith("file:/")  == true ) &&
80
            (sFileURL.startsWith("file://") == false)
81
          )
82
        {
83
            StringBuffer sWorkBuffer = new StringBuffer(sFileURL);
84
            sWorkBuffer.insert(6,"//");
85
            sFileURL = sWorkBuffer.toString();
86
        }
87
88
        return sFileURL;
89
    }
90
91
    // ____________________
92
93
    /**
94
     * The same as getFileURLFromSystemPath() before but uses string parameter instead
95
     * of a File type. It exist to supress converting of neccessary parameters in the
96
     * outside code. But of course getFileURLFromSystemPath(File) will be a little bit faster
97
     * then this method ...
98
     *
99
     * @param sSystemPath
100
     *          represent the file in system notation
101
     *
102
     * @return [String]
103
     *          a file url which represent the given system path
104
     */
105
    public static String getFileURLFromSystemPath( String sSystemPath )
106
    {
107
        return getFileURLFromSystemPath(new File(sSystemPath));
108
    }
109
110
    // ____________________
111
112
    /**
113
     * Does the same as getFileURLFromSystemPath() before ... but uses
114
     * the given protocol string (e.g."http://") insted of "file:///".
115
     *
116
     * @param aSystemPath
117
     *          represent the file in system notation
118
     *
119
     * @param aBasePath
120
     *          define the base path of the aSystemPath value,
121
     *          which must be replaced with the value of "sServerPath".
122
     *
123
     * @param sServerURL
124
     *          Will be used to replace sBasePath.
125
     *
126
     * @example
127
     *          System Path = "d:\test\file.txt"
128
     *          Base Path   = "d:\test"
129
     *          Server Path = "http://alaska:8000"
130
     *          => "http://alaska:8000/file.txt"
131
     *
132
     * @return [String]
133
     *          an url which represent the given system path
134
     *          and uses the given protocol
135
     */
136
    public static String getURLWithProtocolFromSystemPath( File aSystemPath, File aBasePath, String sServerURL )
137
    {
138
        String sFileURL = URLHelper.getFileURLFromSystemPath(aSystemPath);
139
        String sBaseURL = URLHelper.getFileURLFromSystemPath(aBasePath  );
140
141
        // cut last '/'!
142
        if (sBaseURL.lastIndexOf('/')==(sBaseURL.length()-1))
143
            sBaseURL = sBaseURL.substring(0,sBaseURL.length()-1);
144
145
        // cut last '/'!
146
        if (sServerURL.lastIndexOf('/')==(sServerURL.length()-1))
147
            sServerURL = sServerURL.substring(0,sServerURL.length()-1);
148
            
149
        int index = sFileURL.indexOf(sBaseURL);
150
        String sURL = sFileURL.substring(0,index) + sServerURL + 
151
                                sFileURL.substring(index+sBaseURL.length());
152
        //String sURL = sFileURL.replaceFirst(sBaseURL,sServerURL);
153
        return sURL;
154
    }
155
156
    // ____________________
157
158
    /**
159
     * The same as getURLWithProtocolFromSystemPath() before but uses string parameter instead
160
     * of a File types. It exist to supress converting of neccessary parameters in the
161
     * outside code. But of course getURLWithProtocolFromSystemPath(File,File,String) will be
162
     * a little bit faster then this method ...
163
     *
164
     * @param sSystemPath
165
     *          represent the file in system notation
166
     *
167
     * @param sBasePath
168
     *          define the base path of the aSystemPath value,
169
     *          which must be replaced with the value of "sServerPath".
170
     *
171
     * @param sServerPath
172
     *          Will be used to replace sBasePath.
173
     *
174
     * @example
175
     *          System Path = "d:\test\file.txt"
176
     *          Base Path   = "d:\test"
177
     *          Server Path = "http://alaska:8000"
178
     *          => "http://alaska:8000/file.txt"
179
     *
180
     * @return [String]
181
     *          an url which represent the given system path
182
     *          and uses the given protocol
183
     */
184
    public static String getURLWithProtocolFromSystemPath( String sSystemPath, String sBasePath, String sServerPath )
185
    {
186
        return getURLWithProtocolFromSystemPath(new File(sSystemPath), new File(sBasePath), sServerPath);
187
    }
188
189
    // ____________________
190
191
    /**
192
     * This convert an URL (formated as a string) to a struct com.sun.star.util.URL.
193
     * It use a special service to do that: the URLTransformer.
194
     * Because some API calls need it and it's not allowed to set "Complete"
195
     * part of the util struct only. The URL must be parsed.
196
     *
197
     * @param sURL
198
     *          URL for parsing in string notation
199
     *
200
     * @return [com.sun.star.util.URL]
201
     *              URL in UNO struct notation
202
     */
203
    public static com.sun.star.util.URL parseURL(XURLTransformer xParser, String sURL)
204
    {
205
        com.sun.star.util.URL aURL = null;
206
207
        if (sURL==null || sURL.equals(""))
208
            return null;
209
210
        try
211
        {
212
            // Create special service for parsing of given URL.
213
/*            com.sun.star.util.XURLTransformer xParser = (com.sun.star.util.XURLTransformer)OfficeConnect.createRemoteInstance(
214
                                                            com.sun.star.util.XURLTransformer.class,
215
                                                            "com.sun.star.util.URLTransformer");
216
*/
217
            // Because it's an in/out parameter we must use an array of URL objects.
218
            com.sun.star.util.URL[] aParseURL = new com.sun.star.util.URL[1];
219
            aParseURL[0]          = new com.sun.star.util.URL();
220
            aParseURL[0].Complete = sURL;
221
222
            // Parse the URL
223
            xParser.parseStrict(aParseURL);
224
225
            aURL = aParseURL[0];
226
        }
227
        catch(com.sun.star.uno.RuntimeException exRuntime)
228
        {
229
            // Any UNO method of this scope can throw this exception.
230
            // Reset the return value only.
231
            aURL = null;
232
        }
233
234
        return aURL;
235
    }
236
237
    //_________________________________
238
    /**
239
     * Return a name list of all available files of a directory.
240
     * We filter pure sub directories names. All other files
241
     * are returned as full qualified URL strings. So they can be
242
     * used for further purposes. One parameter define the start directory,
243
     * another one describe the url protocol, which the return URL names should have.
244
     *
245
     * @param   sDir
246
     *              the start directory, which should include all test files
247
     *
248
     * @return  [Vector]
249
     *              a filtered list of java File objects of all available files of the start dir
250
     *              and all accessable sub directories.
251
     */
252
    public static Vector getSystemFilesFromDir(String sStartDir)
253
    {
254
        File aRoot = new File(sStartDir);
255
256
        if (! aRoot.exists())
257
            return null;
258
259
        if (! aRoot.isDirectory())
260
            return null;
261
262
        File[] lAllFiles = aRoot.listFiles();
263
        if (lAllFiles == null )
264
            return null;
265
266
        Vector lFilteredFiles = new Vector(lAllFiles.length);
267
268
        for (int i=0; i<lAllFiles.length; ++i)
269
        {
270
            if (lAllFiles[i].isFile())
271
                lFilteredFiles.add(lAllFiles[i]);
272
            else
273
            if (lAllFiles[i].isDirectory())
274
            {
275
                // recursion!
276
                Vector lSubFiles = URLHelper.getSystemFilesFromDir(lAllFiles[i].getPath());
277
                if (lSubFiles != null)
278
                {
279
                    Enumeration aSnapshot = lSubFiles.elements();
280
                    while (aSnapshot.hasMoreElements())
281
                        lFilteredFiles.add(aSnapshot.nextElement());
282
                }
283
            }
284
        }
285
286
        return lFilteredFiles;
287
    }
288
}
(-)source/testcase/uno/db/utils/RowSet.java (+294 lines)
Line 0 Link Here
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 testcase.uno.db.utils;
24
25
import com.sun.star.beans.XPropertySet;
26
import com.sun.star.container.XIndexAccess;
27
import com.sun.star.container.XNameAccess;
28
import com.sun.star.io.XInputStream;
29
import com.sun.star.lang.XComponent;
30
import com.sun.star.lang.XMultiServiceFactory;
31
import com.sun.star.sdbc.SQLException;
32
import com.sun.star.sdbc.XArray;
33
import com.sun.star.sdbc.XBlob;
34
import com.sun.star.sdbc.XClob;
35
import com.sun.star.sdbc.XRef;
36
import com.sun.star.sdbc.XRow;
37
import com.sun.star.sdbc.XRowSet;
38
import com.sun.star.sdbc.XRowSetListener;
39
import com.sun.star.sdbcx.XColumnsSupplier;
40
import com.sun.star.uno.UnoRuntime;
41
import com.sun.star.util.Date;
42
import com.sun.star.util.DateTime;
43
import com.sun.star.util.Time;
44
45
public class RowSet implements XRowSet, XRow
46
{
47
    private XRowSet                 m_rowSet;
48
    private XRow                    m_row;
49
    private XPropertySet            m_rowSetProps;
50
51
    public RowSet( XMultiServiceFactory _orb, String _dataSource, int _commandType, String _command )
52
    {
53
        try
54
        {
55
            m_rowSetProps = UnoRuntime.queryInterface( XPropertySet.class, _orb.createInstance( "com.sun.star.sdb.RowSet" ) );
56
            m_rowSetProps.setPropertyValue( "DataSourceName", _dataSource );
57
            m_rowSetProps.setPropertyValue( "CommandType", new Integer( _commandType ) );
58
            m_rowSetProps.setPropertyValue( "Command", _command );
59
60
            m_rowSet = UnoRuntime.queryInterface( XRowSet.class, m_rowSetProps );
61
            m_row = UnoRuntime.queryInterface( XRow.class, m_rowSetProps );
62
        }
63
        catch ( Exception e )
64
        {
65
            e.printStackTrace(System.err);
66
            throw new java.lang.InstantiationError();
67
        }
68
    }
69
70
    // misc
71
    public int getColumnCount()
72
    {
73
        XColumnsSupplier suppCols = (XColumnsSupplier)UnoRuntime.queryInterface(
74
            XColumnsSupplier.class, m_rowSet );
75
        XIndexAccess columns = (XIndexAccess)UnoRuntime.queryInterface(
76
            XIndexAccess.class, suppCols.getColumns() );
77
        return columns.getCount();
78
    }
79
80
    // XRowSet
81
    public void execute() throws SQLException
82
    {
83
        m_rowSet.execute();
84
    }
85
86
    public void addRowSetListener( XRowSetListener _listener )
87
    {
88
        m_rowSet.addRowSetListener( _listener );
89
    }
90
91
    public void removeRowSetListener( XRowSetListener _listener )
92
    {
93
        m_rowSet.removeRowSetListener( _listener );
94
    }
95
96
    public boolean next() throws SQLException
97
    {
98
        return m_rowSet.next();
99
    }
100
101
    public boolean isBeforeFirst() throws SQLException
102
    {
103
        return m_rowSet.isBeforeFirst();
104
    }
105
106
    public boolean isAfterLast() throws SQLException
107
    {
108
        return m_rowSet.isAfterLast();
109
    }
110
111
    public boolean isFirst() throws SQLException
112
    {
113
        return m_rowSet.isFirst();
114
    }
115
116
    public boolean isLast() throws SQLException
117
    {
118
        return m_rowSet.isLast();
119
    }
120
121
    public void beforeFirst() throws SQLException
122
    {
123
        m_rowSet.beforeFirst();
124
    }
125
126
    public void afterLast() throws SQLException
127
    {
128
        m_rowSet.afterLast();
129
    }
130
131
    public boolean first() throws SQLException
132
    {
133
        return m_rowSet.first();
134
    }
135
136
    public boolean last() throws SQLException
137
    {
138
        return m_rowSet.last();
139
    }
140
141
    public int getRow() throws SQLException
142
    {
143
        return m_rowSet.getRow();
144
    }
145
146
    public boolean absolute(int i) throws SQLException
147
    {
148
        return m_rowSet.absolute(i);
149
    }
150
151
    public boolean relative(int i) throws SQLException
152
    {
153
        return m_rowSet.relative(i);
154
    }
155
156
    public boolean previous() throws SQLException
157
    {
158
        return m_rowSet.previous();
159
    }
160
161
    public void refreshRow() throws SQLException
162
    {
163
        m_rowSet.refreshRow();
164
    }
165
166
    public boolean rowUpdated() throws SQLException
167
    {
168
        return m_rowSet.rowUpdated();
169
    }
170
171
    public boolean rowInserted() throws SQLException
172
    {
173
        return m_rowSet.rowInserted();
174
    }
175
176
    public boolean rowDeleted() throws SQLException
177
    {
178
        return m_rowSet.rowDeleted();
179
    }
180
181
    // XRow
182
    public Object getStatement() throws SQLException
183
    {
184
        return m_rowSet.getStatement();
185
    }
186
187
    public boolean wasNull() throws SQLException
188
    {
189
        return m_row.wasNull();
190
    }
191
192
    public String getString(int i) throws SQLException
193
    {
194
        return m_row.getString(i);
195
    }
196
197
    public boolean getBoolean(int i) throws SQLException
198
    {
199
        return m_row.getBoolean(i);
200
    }
201
202
    public byte getByte(int i) throws SQLException
203
    {
204
        return m_row.getByte(i);
205
    }
206
207
    public short getShort(int i) throws SQLException
208
    {
209
        return m_row.getShort(i);
210
    }
211
212
    public int getInt(int i) throws SQLException
213
    {
214
        return m_row.getInt(i);
215
    }
216
217
    public long getLong(int i) throws SQLException
218
    {
219
        return m_row.getLong(i);
220
    }
221
222
    public float getFloat(int i) throws SQLException
223
    {
224
        return m_row.getFloat(i);
225
    }
226
227
    public double getDouble(int i) throws SQLException
228
    {
229
        return m_row.getDouble(i);
230
    }
231
232
    public byte[] getBytes(int i) throws SQLException
233
    {
234
        return m_row.getBytes(i);
235
    }
236
237
    public Date getDate(int i) throws SQLException
238
    {
239
        return m_row.getDate(i);
240
    }
241
242
    public Time getTime(int i) throws SQLException
243
    {
244
        return m_row.getTime(i);
245
    }
246
247
    public DateTime getTimestamp(int i) throws SQLException
248
    {
249
        return m_row.getTimestamp(i);
250
    }
251
252
    public XInputStream getBinaryStream(int i) throws SQLException
253
    {
254
        return m_row.getBinaryStream(i);
255
    }
256
257
    public XInputStream getCharacterStream(int i) throws SQLException
258
    {
259
        return m_row.getCharacterStream(i);
260
    }
261
262
    public Object getObject(int i, XNameAccess xNameAccess) throws SQLException
263
    {
264
        return m_row.getObject(i, xNameAccess);
265
    }
266
267
    public XRef getRef(int i) throws SQLException
268
    {
269
        return m_row.getRef(i);
270
    }
271
272
    public XBlob getBlob(int i) throws SQLException
273
    {
274
        return m_row.getBlob(i);
275
    }
276
277
    public XClob getClob(int i) throws SQLException
278
    {
279
        return m_row.getClob(i);
280
    }
281
282
    public XArray getArray(int i) throws SQLException
283
    {
284
        return m_row.getArray(i);
285
    }
286
287
    public void dispose()
288
    {
289
        if ( m_rowSet == null )
290
            return;
291
        XComponent rowSetComp = UnoRuntime.queryInterface( XComponent.class, m_rowSet );
292
        rowSetComp.dispose();
293
    }
294
};
(-)source/testcase/uno/db/utils/DataSource.java (+159 lines)
Line 0 Link Here
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 testcase.uno.db.utils;
24
25
import com.sun.star.container.ElementExistException;
26
import com.sun.star.container.NoSuchElementException;
27
import com.sun.star.container.XNameAccess;
28
import com.sun.star.container.XNameContainer;
29
import com.sun.star.lang.WrappedTargetException;
30
import com.sun.star.lang.XSingleServiceFactory;
31
import com.sun.star.lang.XMultiServiceFactory;
32
import com.sun.star.beans.XPropertySet;
33
import com.sun.star.sdb.XQueryDefinitionsSupplier;
34
import com.sun.star.sdbc.XDataSource;
35
import com.sun.star.uno.Exception;
36
import com.sun.star.uno.UnoRuntime;
37
import java.util.logging.Level;
38
import java.util.logging.Logger;
39
40
public class DataSource
41
{
42
    // the service factory
43
44
    private final XMultiServiceFactory m_orb;
45
    private XDataSource m_dataSource;
46
47
    public DataSource(final XMultiServiceFactory _orb, final String _registeredName) throws Exception
48
    {
49
        m_orb = _orb;
50
51
        final XNameAccess dbContext = UnoRuntime.queryInterface(
52
            XNameAccess.class, _orb.createInstance( "com.sun.star.sdb.DatabaseContext" ) );
53
54
        m_dataSource = UnoRuntime.queryInterface( XDataSource.class, dbContext.getByName( _registeredName ) );
55
    }
56
57
    public DataSource(final XMultiServiceFactory _orb,final XDataSource _dataSource)
58
    {
59
        m_orb = _orb;
60
        m_dataSource = _dataSource;
61
    }
62
63
    final public XDataSource getXDataSource()
64
    {
65
        return m_dataSource;
66
    }
67
68
    /**
69
     * retrieves the data source's settings
70
     */
71
    public XPropertySet geSettings()
72
    {
73
        return UnoRuntime.queryInterface( XPropertySet.class, impl_getPropertyValue( "Settings" ) );
74
    }
75
76
    /** creates a query with a given name and SQL command
77
     */
78
    public void createQuery(final String _name, final String _sqlCommand) throws ElementExistException, WrappedTargetException, com.sun.star.lang.IllegalArgumentException
79
    {
80
        createQuery(_name, _sqlCommand, true);
81
    }
82
83
    /** creates a query with a given name, SQL command, and EscapeProcessing flag
84
     */
85
    public void createQuery(final String _name, final String _sqlCommand, final boolean _escapeProcessing) throws ElementExistException, WrappedTargetException, com.sun.star.lang.IllegalArgumentException
86
    {
87
        final XSingleServiceFactory queryDefsFac = UnoRuntime.queryInterface( XSingleServiceFactory.class, getQueryDefinitions() );
88
        XPropertySet queryDef = null;
89
        try
90
        {
91
            queryDef = UnoRuntime.queryInterface( XPropertySet.class, queryDefsFac.createInstance() );
92
            queryDef.setPropertyValue("Command", _sqlCommand);
93
            queryDef.setPropertyValue("EscapeProcessing", Boolean.valueOf(_escapeProcessing));
94
        }
95
        catch (com.sun.star.uno.Exception e)
96
        {
97
            e.printStackTrace(System.err);
98
        }
99
100
        final XNameContainer queryDefsContainer = UnoRuntime.queryInterface( XNameContainer.class, getQueryDefinitions() );
101
        queryDefsContainer.insertByName(_name, queryDef);
102
    }
103
104
    /** provides the query definition with the given name
105
     */
106
    public QueryDefinition getQueryDefinition(final String _name) throws NoSuchElementException
107
    {
108
        final XNameAccess allDefs = getQueryDefinitions();
109
        try
110
        {
111
            return new QueryDefinition( UnoRuntime.queryInterface( XPropertySet.class, allDefs.getByName( _name) ) );
112
        }
113
        catch (WrappedTargetException e)
114
        {
115
        }
116
        throw new NoSuchElementException();
117
    }
118
119
    /** provides the container of query definitions of the data source
120
     */
121
    public XNameAccess getQueryDefinitions()
122
    {
123
        final XQueryDefinitionsSupplier suppQueries = UnoRuntime.queryInterface(
124
                XQueryDefinitionsSupplier.class, m_dataSource);
125
        return suppQueries.getQueryDefinitions();
126
    }
127
128
    /**
129
     * retrieves a property value from the data source
130
     * @param i_propertyName
131
     *      the name of the property whose value is to be returned.
132
     */
133
    private Object impl_getPropertyValue( final String i_propertyName )
134
    {
135
        Object propertyValue = null;
136
        try
137
        {
138
            final XPropertySet dataSourceProps = UnoRuntime.queryInterface( XPropertySet.class, m_dataSource );
139
            propertyValue = dataSourceProps.getPropertyValue( i_propertyName );
140
        }
141
        catch (Exception ex)
142
        {
143
            Logger.getLogger(DataSource.class.getName()).log(Level.SEVERE, null, ex);
144
        }
145
        return propertyValue;
146
    }
147
148
    /** returns the name of the data source
149
     * 
150
     * If a data source is registered at the database context, the name is the registration
151
     * name. Otherwise, its the URL which the respective database document is based on.
152
     * 
153
     * Note that the above definition is from the UNO API, not from this wrapper here.
154
     */
155
    public String getName()
156
    {
157
        return (String)impl_getPropertyValue( "Name" );
158
    }
159
};
(-)source/testcase/uno/db/utils/HsqlColumnDescriptor.java (+80 lines)
Line 0 Link Here
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
24
package testcase.uno.db.utils;
25
26
/** is a very simply and rudimentary descriptor of table columns, for creating HSQLDB tables
27
 */
28
public class HsqlColumnDescriptor
29
{
30
    private String Name;
31
    private String TypeName;
32
    private boolean Required;
33
    private boolean PrimaryKey;
34
    private String ForeignTable;
35
    private String ForeignColumn;
36
37
    public final String getName() { return Name; }
38
    public final String getTypeName() { return TypeName; }
39
    public final boolean isRequired() { return Required; }
40
    public final boolean isPrimaryKey() { return PrimaryKey; }
41
42
    public final boolean isForeignKey() { return ( ForeignTable.length() != 0 ) && ( ForeignColumn.length() != 0 ); }
43
    public final String getForeignTable() { return ForeignTable; }
44
    public final String getForeignColumn() { return ForeignColumn; }
45
46
    /// determines that a column is required, i.e. not nullable
47
    public final static int REQUIRED    = 1;
48
    /// determines that a column is part of the primary key of its table
49
    public final static int PRIMARY     = 2;
50
51
    public HsqlColumnDescriptor( String _Name, String _TypeName )
52
    {
53
        Name = _Name;
54
        TypeName = _TypeName;
55
        Required = false;
56
        PrimaryKey = false;
57
        ForeignTable = "";
58
        ForeignColumn = "";
59
    }
60
61
    public HsqlColumnDescriptor( String _Name, String _TypeName, int _Flags )
62
    {
63
        Name = _Name;
64
        TypeName = _TypeName;
65
        Required = ( _Flags & REQUIRED ) != 0;
66
        PrimaryKey = ( _Flags & PRIMARY ) != 0;
67
        ForeignTable = "";
68
        ForeignColumn = "";
69
    }
70
71
    public HsqlColumnDescriptor( String _Name, String _TypeName, int _Flags, String _ForeignTable, String _ForeignColumn )
72
    {
73
        Name = _Name;
74
        TypeName = _TypeName;
75
        Required = ( _Flags & REQUIRED ) != 0;
76
        PrimaryKey = ( _Flags & PRIMARY ) != 0;
77
        ForeignTable = _ForeignTable;
78
        ForeignColumn = _ForeignColumn;
79
    }
80
};
(-)source/testcase/uno/db/utils/HsqlTableDescriptor.java (+97 lines)
Line 0 Link Here
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
24
package testcase.uno.db.utils;
25
26
import com.sun.star.beans.XPropertySet;
27
import com.sun.star.container.XNameAccess;
28
import com.sun.star.sdbc.ColumnValue;
29
import com.sun.star.sdbcx.XColumnsSupplier;
30
import com.sun.star.sdbcx.XDataDescriptorFactory;
31
import com.sun.star.sdbcx.XTablesSupplier;
32
import com.sun.star.uno.UnoRuntime;
33
34
/** is a very simply descriptor of a HSQL table, to be used with a HsqlDatabase.createTable method
35
 */
36
public class HsqlTableDescriptor
37
{
38
    private String                  m_name;
39
    private HsqlColumnDescriptor[]  m_columns;
40
41
    /** Creates a new instance of HsqlTableDescriptor */
42
    public HsqlTableDescriptor( String _name, HsqlColumnDescriptor[] _columns )
43
    {
44
        m_name = _name;
45
        m_columns = _columns;
46
    }
47
48
    /** returns the name of the table
49
     */
50
    public String getName()
51
    {
52
        return m_name;
53
    }
54
55
    /** returns the set of column descriptors for the table
56
     */
57
    public HsqlColumnDescriptor[] getColumns()
58
    {
59
        return m_columns;
60
    }
61
62
    public XPropertySet createSdbcxDescriptor( Connection _forConnection )
63
    {
64
        XTablesSupplier suppTables = UnoRuntime.queryInterface( XTablesSupplier.class, _forConnection.getXConnection() );
65
        XDataDescriptorFactory tableDescFac = UnoRuntime.queryInterface( XDataDescriptorFactory.class, suppTables.getTables() );
66
        XPropertySet tableDesc = tableDescFac.createDataDescriptor();
67
68
        try
69
        {
70
            tableDesc.setPropertyValue( "Name", getName() );
71
        }
72
        catch ( Exception e ) { e.printStackTrace( System.err ); }
73
        
74
        XColumnsSupplier suppDescCols = UnoRuntime.queryInterface( XColumnsSupplier.class, tableDesc );
75
76
        XNameAccess descColumns = suppDescCols.getColumns();
77
        XDataDescriptorFactory columnDescFac = UnoRuntime.queryInterface( XDataDescriptorFactory.class, descColumns );
78
79
        HsqlColumnDescriptor[] myColumns = getColumns();
80
        for ( int i = 0; i < myColumns.length; ++i )
81
        {
82
            XPropertySet columnDesc = columnDescFac.createDataDescriptor();
83
            try
84
            {
85
                columnDesc.setPropertyValue( "Name", myColumns[i].getName() );
86
                columnDesc.setPropertyValue( "IsNullable", new Integer( myColumns[i].isRequired() ? ColumnValue.NO_NULLS : ColumnValue.NULLABLE) );
87
                columnDesc.setPropertyValue( "TypeName", myColumns[i].getTypeName() );
88
                if ( myColumns[i].isPrimaryKey() || myColumns[i].isForeignKey() )
89
                    // not yet implemented
90
                    throw new java.lang.UnsupportedOperationException("creating a primary or foreign key via SDBCX not yet implemented" );
91
            }
92
            catch( com.sun.star.uno.Exception e ) { e.printStackTrace( System.err ); }
93
        }
94
95
        return tableDesc;
96
    }
97
}
(-)source/testcase/uno/db/DBAccess.java (+152 lines)
Line 0 Link Here
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
package testcase.uno.db;
23
24
import com.sun.star.beans.PropertyValue;
25
import com.sun.star.container.XNameAccess;
26
import com.sun.star.frame.FrameSearchFlag;
27
import com.sun.star.frame.XComponentLoader;
28
import com.sun.star.frame.XModel;
29
import com.sun.star.frame.XStorable;
30
import com.sun.star.lang.XComponent;
31
import com.sun.star.sdb.XOfficeDatabaseDocument;
32
import com.sun.star.sdb.application.XDatabaseDocumentUI;
33
import com.sun.star.sdbcx.XTablesSupplier;
34
import com.sun.star.uno.Exception;
35
import com.sun.star.uno.UnoRuntime;
36
37
import testcase.uno.db.utils.HsqlColumnDescriptor;
38
import testcase.uno.db.utils.HsqlDatabase;
39
import testcase.uno.db.utils.HsqlTableDescriptor;
40
import testcase.uno.db.utils.TestCase;
41
import java.io.IOException;
42
43
// ---------- junit imports -----------------
44
import org.junit.After;
45
import org.junit.Before;
46
import org.junit.Test;
47
48
import static org.junit.Assert.*;
49
50
51
52
/**
53
 * test case for Base's application UI
54
 */
55
public class DBAccess extends TestCase {
56
57
	private HsqlDatabase m_database;
58
	private XOfficeDatabaseDocument m_databaseDocument;
59
	private XDatabaseDocumentUI m_documentUI;
60
61
	public DBAccess() {
62
		super();
63
	}
64
65
	private void closeDocument() {
66
		if (m_database != null) {
67
			m_database.close();
68
			m_database = null;
69
			m_databaseDocument = null;
70
			m_documentUI = null;
71
		}
72
	}
73
74
	private void switchToDocument(String _documentURL)
75
			throws java.lang.Exception {
76
		// close previous database document
77
		closeDocument();
78
79
		// create/load the new database document
80
		m_database = (_documentURL == null) ? new HsqlDatabase(getMSF())
81
				: new HsqlDatabase(getMSF(), _documentURL);
82
		m_databaseDocument = m_database.getDatabaseDocument();
83
84
		// load it into a frame
85
		final Object object = getMSF().createInstance(
86
				"com.sun.star.frame.Desktop");
87
		final XComponentLoader xComponentLoader = UnoRuntime.queryInterface(
88
				XComponentLoader.class, object);
89
		final XComponent loadedComponent = xComponentLoader
90
				.loadComponentFromURL(m_database.getDocumentURL(), "_blank",
91
						FrameSearchFlag.ALL, new PropertyValue[0]);
92
		Thread.sleep(10000);
93
94
		// get the controller, which provides access to various UI operations
95
		final XModel docModel = UnoRuntime.queryInterface(XModel.class,
96
				loadedComponent);
97
		m_documentUI = UnoRuntime.queryInterface(XDatabaseDocumentUI.class,
98
				docModel.getCurrentController());
99
	}
100
101
102
	@Before
103
	@Override
104
	public void before() throws java.lang.Exception {
105
		String a = null;
106
		super.before();
107
		switchToDocument(a);
108
	}
109
110
	@After
111
	@Override
112
	public void after() throws java.lang.Exception {
113
		closeDocument();
114
		super.after();
115
	}
116
117
	@Test
118
	public void testSaveAs() throws Exception, IOException, java.lang.Exception {
119
		final String newDocumentURL = createTempFileURL();
120
121
		// store the doc in a new location
122
		final XStorable storeDoc = UnoRuntime.queryInterface(XStorable.class,
123
				m_databaseDocument);
124
		storeDoc.storeAsURL(newDocumentURL, new PropertyValue[] {});
125
		// load doc from new location
126
		switchToDocument(newDocumentURL);
127
		m_documentUI.connect();
128
		assertTrue("could not connect to " + m_database.getDocumentURL(),
129
				m_documentUI.isConnected());
130
131
	}
132
133
	@Test
134
	public void testCreateTable() throws java.lang.Exception {
135
		switchToDocument(null);
136
		m_documentUI.connect();
137
		// create a table in the database
138
		m_database.createTable(new HsqlTableDescriptor("test",
139
				new HsqlColumnDescriptor[] {
140
						new HsqlColumnDescriptor("a", "VARCHAR(50)"),
141
						new HsqlColumnDescriptor("b", "VARCHAR(50)"),
142
						new HsqlColumnDescriptor("c", "VARCHAR(50)") }));
143
		switchToDocument(m_database.getDocumentURL());
144
		m_documentUI.connect();
145
		XTablesSupplier suppTables = UnoRuntime.queryInterface(
146
				XTablesSupplier.class, m_documentUI.getActiveConnection());
147
		XNameAccess tables = suppTables.getTables();
148
		assertTrue("the newly created table has not been written",
149
				tables.hasByName("test"));
150
	}
151
152
}

Return to issue 120525