diff options
-rw-r--r-- | odk/examples/DevelopersGuide/Forms/ButtonOperator.java | 281 | ||||
-rw-r--r-- | odk/examples/DevelopersGuide/Forms/DataAwareness.java | 448 | ||||
-rw-r--r-- | odk/examples/DevelopersGuide/Forms/DocumentBasedExample.java | 34 | ||||
-rw-r--r-- | odk/examples/DevelopersGuide/Forms/DocumentViewHelper.java | 51 | ||||
-rw-r--r-- | odk/examples/DevelopersGuide/Forms/FormLayer.java | 2 | ||||
-rw-r--r-- | odk/examples/DevelopersGuide/Forms/HsqlDatabase.java | 256 | ||||
-rw-r--r-- | odk/examples/DevelopersGuide/Forms/Makefile | 5 | ||||
-rw-r--r-- | odk/examples/DevelopersGuide/Forms/RowSet.java | 290 | ||||
-rw-r--r-- | odk/examples/DevelopersGuide/Forms/SalesFilter.java | 2 | ||||
-rw-r--r-- | odk/examples/DevelopersGuide/Forms/URLHelper.java | 70 | ||||
-rw-r--r-- | odk/examples/DevelopersGuide/Forms/makefile.mk | 3 |
11 files changed, 860 insertions, 582 deletions
diff --git a/odk/examples/DevelopersGuide/Forms/ButtonOperator.java b/odk/examples/DevelopersGuide/Forms/ButtonOperator.java index 75e10cbe4485..08bf373f1819 100644 --- a/odk/examples/DevelopersGuide/Forms/ButtonOperator.java +++ b/odk/examples/DevelopersGuide/Forms/ButtonOperator.java @@ -37,131 +37,72 @@ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *************************************************************************/ +package org.openoffice.sdk.forms; -import com.sun.star.uno.*; -import com.sun.star.frame.*; -import com.sun.star.awt.*; -import com.sun.star.lang.*; -import com.sun.star.util.*; -import com.sun.star.container.*; -import com.sun.star.beans.*; -import com.sun.star.task.*; -import com.sun.star.sdbc.*; -import com.sun.star.sdbcx.*; -import com.sun.star.sdb.*; -import com.sun.star.form.*; // java base stuff +import com.sun.star.awt.ActionEvent; +import com.sun.star.awt.XActionListener; +import com.sun.star.awt.XButton; +import com.sun.star.beans.XPropertySet; +import com.sun.star.form.runtime.FormOperations; +import com.sun.star.form.runtime.XFeatureInvalidation; +import com.sun.star.form.runtime.XFormOperations; +import com.sun.star.lang.EventObject; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; import java.util.Vector; /**************************************************************************/ /** a helper class for operating the buttons */ -public class ButtonOperator implements XActionListener, XStatusListener +public class ButtonOperator implements XActionListener, XFeatureInvalidation { - private XComponentContext m_xCtx; + private XComponentContext m_componentContext; private DocumentHelper m_aDocument; + private XPropertySet m_form; + private XFormOperations m_formOperations; private Vector m_aButtons; - private Vector m_aDispatchers; /* ------------------------------------------------------------------ */ /** ctor */ - public ButtonOperator( XComponentContext xCtx, DocumentHelper aDocument ) + public ButtonOperator( XComponentContext xCtx, DocumentHelper aDocument, XPropertySet _form ) { - m_xCtx = xCtx; + m_componentContext = xCtx; m_aDocument = aDocument; + m_form = _form; m_aButtons = new Vector(); - m_aDispatchers = new Vector(); } /* ------------------------------------------------------------------ */ - /** shows a message that we can't do several things due to an implementation error - */ - private void showImplementationErrorMessage( XInterface xContext ) + private short getAssociatedFormFeature( XPropertySet _buttonModel ) { - SQLException aBaseError = new SQLException( - new String( "Due to a multi-threading issue, this method does not work correctly when invoked via remote java." ), - xContext, - new String( "S1000" ), - 0, - null - ); - SQLContext aError = new SQLContext( - new String( "Unable to perform request." ), - xContext, - new String( "S1000" ), - 0, - aBaseError, - new String( "This functionallity has been disabled due to an implementation bug." ) - ); - + short formFeature = -1; try { - // instantiate an interaction handler who can handle SQLExceptions - XInteractionHandler xHandler = (XInteractionHandler)UnoRuntime.queryInterface( - XInteractionHandler.class, - m_xCtx.getServiceManager().createInstanceWithContext( - "com.sun.star.sdb.InteractionHandler", m_xCtx ) ); - - // create a new request - InteractionRequest aRequest = new InteractionRequest( aError ); - xHandler.handle( aRequest ); + formFeature = Short.valueOf( (String)_buttonModel.getPropertyValue( "Tag" ) ); } catch( com.sun.star.uno.Exception e ) { } - } - - /* ------------------------------------------------------------------ */ - /** reloads the form the given button belongs too - */ - private void reload( Object aControlModel ) - { - // this came from the reload button, so reload the form if the user wishes this .... - com.sun.star.form.XLoadable xLoad = (com.sun.star.form.XLoadable)FLTools.getParent( - aControlModel, com.sun.star.form.XLoadable.class ); - // (note that this xLoad equals our m_xMasterForm) - - // produce an error saying that we can't really do this -// showImplementationErrorMessage( xLoad ); - - // If you did neither your office nor your jave program fit with the - // ForceSynchronous=1 parameter, the following line would result in a deadlock due - // to an implementation bug. - xLoad.reload(); - } - - /* ------------------------------------------------------------------ */ - private String getTag( Object aModel ) - { - String sReturn = new String(); - try - { - XPropertySet xModelProps = UNO.queryPropertySet( aModel ); - sReturn = (String)xModelProps.getPropertyValue( "Tag" ); - } - catch( com.sun.star.uno.Exception e ) - { - // though this is a serious error, we're not interested in - } - return sReturn; + return formFeature; } /* ------------------------------------------------------------------ */ /** get's the button which we operate and which is responsible for a given URL */ - private int getButton( String sActionURL ) + private XPropertySet getButton( short _formFeature ) { - int nPos = -1; - for ( int i=0; ( i < m_aButtons.size() ) && ( -1 == nPos ); ++i ) + for ( int i=0; i < m_aButtons.size(); ++i ) { - if ( sActionURL.equals( getTag( m_aButtons.elementAt( i ) ) ) ) - nPos = i; + XPropertySet button = (XPropertySet)m_aButtons.elementAt( i ); + if ( _formFeature == getAssociatedFormFeature( button ) ) + return button; } - return nPos; + return null; } /* ------------------------------------------------------------------ */ @@ -181,38 +122,20 @@ public class ButtonOperator implements XActionListener, XStatusListener /* ------------------------------------------------------------------ */ /** announces a button which the operator should be responsible for */ - public void addButton( XPropertySet xButtonModel, String sActionURL ) throws java.lang.Exception + public void addButton( XPropertySet _buttonModel, short _formFeature ) throws java.lang.Exception { // the current view to the document DocumentViewHelper aCurrentView = m_aDocument.getCurrentView(); // add a listener so we get noticed if the user presses the button - // get the control XButton xButtonControl = (XButton)UnoRuntime.queryInterface( XButton.class, - aCurrentView.getControl( xButtonModel ) ); - + aCurrentView.getFormControl( _buttonModel ) ); xButtonControl.addActionListener( this ); - // remember the action URL - xButtonModel.setPropertyValue( "Tag", sActionURL ); - // retrieve the dispatcher for the action URL - XDispatch xActionDispatch = null; - if ( 0 < sActionURL.length() ) - { - // query the current document view for a dispatcher for the action URL - URL[] aURL = new URL[] { new URL() }; - aURL[0].Complete = sActionURL; - xActionDispatch = aCurrentView.getDispatcher( aURL ); - // and if we found one, add ourself as status listener so we get notified whenever something changes - if ( null != xActionDispatch ) - { - xActionDispatch.addStatusListener( this, aURL[0] ); - } - } + _buttonModel.setPropertyValue( "Tag", String.valueOf( _formFeature ) ); - // remember the button and the dispatcher - m_aButtons.add( xButtonModel ); - m_aDispatchers.add( xActionDispatch ); + // remember the button + m_aButtons.add( _buttonModel ); } /* ------------------------------------------------------------------ */ @@ -222,29 +145,6 @@ public class ButtonOperator implements XActionListener, XStatusListener if ( -1 < nPos ) { m_aButtons.remove( nPos ); - m_aDispatchers.remove( nPos ); - } - } - - /* ------------------------------------------------------------------ */ - /** called when the status of an URL we operate on has changed - */ - public void statusChanged( FeatureStateEvent aEvent ) throws com.sun.star.uno.RuntimeException - { - // get the button which is responsible for URL - int nButtonPos = getButton( aEvent.FeatureURL.Complete ); - if ( -1 < nButtonPos ) - { - XPropertySet xButton = (XPropertySet)m_aButtons.elementAt( nButtonPos ); - try - { - xButton.setPropertyValue( "Enabled", new Boolean( aEvent.IsEnabled ) ); - } - catch( java.lang.Exception e ) - { - System.out.println(e); - e.printStackTrace(); - } } } @@ -257,64 +157,34 @@ public class ButtonOperator implements XActionListener, XStatusListener public void actionPerformed( ActionEvent aEvent ) throws com.sun.star.uno.RuntimeException { // get the model's name - XNamed xModel = (XNamed)FLTools.getModel( aEvent.Source, XNamed.class ); - String sName = xModel.getName(); - - if ( sName.equals( new String( "reload" ) ) ) - reload( xModel ); - else + XPropertySet buttonModel = (XPropertySet)FLTools.getModel( aEvent.Source, XPropertySet.class ); + try { - // get the action URL the button is bound to - String sActionURL = getTag( xModel ); - - // get the dispatcher responsible for this action URL - int nButtonPos = getButton( sActionURL ); - if ( -1 < nButtonPos ) - { - XDispatch xDispatcher = (XDispatch)m_aDispatchers.elementAt( nButtonPos ); - if ( null != xDispatcher ) - { - PropertyValue[] aDummyArgs = new PropertyValue[] { }; - try - { - xDispatcher.dispatch( FLTools.parseURL( sActionURL, m_xCtx ), aDummyArgs ); - } - catch( java.lang.Exception e ) - { - } - } - } - - // below is what we really would like to do - if we would not have these implementation - // bugs - // Though the current solution has one more advantage: we don't need to determine - // the button state ourself. We are told by the form layer framework when the buttons - // have to be enabled or disabled. - // Once Issuezilla bug #TODO# is fixed (means we have a chance to reach for the form - // controller from external components), we can get rid off the implementation specific - // part of the URLs we use (this "#0/0" mark), and then we would have a working solution - // which is not to be called hack ..... + short formFeature = getAssociatedFormFeature( buttonModel ); + if ( formFeature != -1 ) + m_formOperations.execute( formFeature ); + } + catch( final com.sun.star.uno.Exception e ) + { + } + } - // the result set to operate on -// XResultSet xSet = (XResultSet)FLTools.getParent( xModel, XResultSet.class ); -// -// try -// { -// // this is what we would have liked to do -// if ( sName.equals( new String( "first" ) ) ) -// xSet.first(); -// else if ( sName.equals( new String( "prev" ) ) ) -// xSet.previous(); -// else if ( sName.equals( new String( "next" ) ) ) -// xSet.next(); -// else if ( sName.equals( new String( "last" ) ) ) -// xSet.last(); -// } -// catch( SQLException e ) -// { -// System.err.println( e ); -// e.printStackTrace(); -// } + /* ------------------------------------------------------------------ */ + /* (to be) called when the form layer has been switched to alive mode + * @todo + * register as listener somewhere ... + */ + public void onFormsAlive() + { + try + { + m_formOperations = FormOperations.createWithFormController( + m_componentContext, m_aDocument.getCurrentView().getFormController( m_form ) ); + m_formOperations.setFeatureInvalidation( this ); + invalidateAllFeatures(); + } + catch( final com.sun.star.uno.Exception e ) + { } } @@ -325,5 +195,38 @@ public class ButtonOperator implements XActionListener, XStatusListener { // not interested in } + + /* ================================================================== + = XFeatureInvalidation + ================================================================== */ + private void updateButtonState( XPropertySet _buttonModel, short _formFeature ) + { + try + { + _buttonModel.setPropertyValue( "Enabled", m_formOperations.isEnabled( _formFeature ) ); + } + catch( com.sun.star.uno.Exception e ) + { + } + } + + public void invalidateFeatures( short[] _features ) throws com.sun.star.uno.RuntimeException + { + for ( int i=0; i<_features.length; ++i ) + { + XPropertySet buttonModel = getButton( _features[i] ); + if ( buttonModel != null ) + updateButtonState( buttonModel, _features[i] ); + } + } + + public void invalidateAllFeatures() throws com.sun.star.uno.RuntimeException + { + for ( int i=0; i < m_aButtons.size(); ++i ) + { + XPropertySet buttonModel = (XPropertySet)m_aButtons.elementAt( i ); + updateButtonState( buttonModel, getAssociatedFormFeature( buttonModel ) ); + } + } }; diff --git a/odk/examples/DevelopersGuide/Forms/DataAwareness.java b/odk/examples/DevelopersGuide/Forms/DataAwareness.java index 784f0ed9c8de..9ac1f6e55ac4 100644 --- a/odk/examples/DevelopersGuide/Forms/DataAwareness.java +++ b/odk/examples/DevelopersGuide/Forms/DataAwareness.java @@ -37,46 +37,37 @@ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *************************************************************************/ +package org.openoffice.sdk.forms; -// __________ Imports __________ - -// base classes -import com.sun.star.uno.*; -import com.sun.star.lang.*; - -// factory for creating components -import com.sun.star.bridge.XUnoUrlResolver; -import com.sun.star.frame.XComponentLoader; - -// container handling -import com.sun.star.container.*; - -// property access -import com.sun.star.beans.*; - -// toolkit specific stuff -import com.sun.star.awt.*; - -// drawing layer -import com.sun.star.drawing.*; +import com.sun.star.beans.PropertyChangeEvent; +import com.sun.star.beans.XPropertyChangeListener; +import com.sun.star.beans.XPropertySet; -// text documents -import com.sun.star.text.*; -// form layer -import com.sun.star.form.*; - -// data access -import com.sun.star.sdbc.*; -import com.sun.star.sdbcx.*; -import com.sun.star.sdb.*; - -// document framework -import com.sun.star.frame.*; -import com.sun.star.view.*; +// __________ Imports __________ +import com.sun.star.beans.XPropertySetInfo; -// miscellaneous -import com.sun.star.util.*; +// base classes +import com.sun.star.container.XIndexContainer; +import com.sun.star.container.XNameAccess; +import com.sun.star.container.XNamed; +import com.sun.star.form.FormComponentType; +import com.sun.star.form.ListSourceType; +import com.sun.star.form.XGridColumnFactory; +import com.sun.star.form.XReset; +import com.sun.star.form.XResetListener; +import com.sun.star.form.runtime.FormFeature; +import com.sun.star.lang.EventObject; +import com.sun.star.lang.XComponent; +import com.sun.star.sdb.CommandType; +import com.sun.star.sdb.XColumnUpdate; +import com.sun.star.sdbc.ResultSetConcurrency; +import com.sun.star.sdbc.XConnection; +import com.sun.star.sdbc.XDataSource; +import com.sun.star.sdbc.XStatement; +import com.sun.star.sdbcx.XColumnsSupplier; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XInterface; /**************************************************************************/ /** a class for enumerating a form component tree @@ -160,25 +151,11 @@ class RevokeButtons extends ComponentTreeTraversal public class DataAwareness extends DocumentBasedExample implements XPropertyChangeListener, XResetListener { /* ================================================================== */ - private class Parameters - { - public String sDataSourceName; - public String sUser; - public String sPassword; - public String sTablePrefix; + private HsqlDatabase m_database; - public String addTablePrefix( String sBaseName ) - { - String sReturn = new String( sTablePrefix ); - if ( 0 < sTablePrefix.length() ) - sReturn += "."; - sReturn += sBaseName; - return sReturn; - } - }; - - /* ================================================================== */ - private Parameters m_aParameters; + private static final String s_tableNameSalesmen = "SALESMEN"; + private static final String s_tableNameCustomers = "CUSTOMERS"; + private static final String s_tableNameSales = "SALES"; private XPropertySet m_xMasterForm; private ButtonOperator m_aOperator; @@ -197,7 +174,7 @@ public class DataAwareness extends DocumentBasedExample implements XPropertyChan /* ------------------------------------------------------------------ */ public DataAwareness() { - super( DocumentType.CALC ); + super( DocumentType.WRITER ); m_bDefaultSalesDate = false; m_bProtectKeyFields = false; m_bAllowEmptySales = false; @@ -444,23 +421,16 @@ public class DataAwareness extends DocumentBasedExample implements XPropertyChan String[] aCurrentFilter = (String[])xDSP.getPropertyValue( "TableFilter" ); // check if the table name is already part of it - String sPureTableName = sTableName; // the pure name, e.g. SALESMAN - String sPrefixedTableName = m_aParameters.addTablePrefix( sTableName ); // the prefixed name, e.g. SCHEMA.SALESMAN String sAllTables = "*"; // all tables - String sPrefixWildcard = m_aParameters.addTablePrefix( sAllTables ); // all tables in this schema, e.g. SCHEMA.* for ( int i=0; i<aCurrentFilter.length; ++i ) { String sCurrentTableFilter = aCurrentFilter[i]; - if ( sCurrentTableFilter.equals( sPureTableName ) ) - return; - if ( sCurrentTableFilter.equals( sPrefixedTableName ) ) + if ( sCurrentTableFilter.equals( sTableName ) ) return; if ( sCurrentTableFilter.equals( sAllTables ) ) return; - if ( sCurrentTableFilter.equals( sPrefixWildcard ) ) - return; } // if we are here, we have to add our table to the filter sequence @@ -469,8 +439,7 @@ public class DataAwareness extends DocumentBasedExample implements XPropertyChan for ( int i=0; i<aCurrentFilter.length; ++i ) aNewFilter[i] = aCurrentFilter[i]; // add our table - aNewFilter[ aCurrentFilter.length ] = sPrefixedTableName; - // note that sPrefixedTableName equals sTableName in case there is no prefix + aNewFilter[ aCurrentFilter.length ] = sTableName; xDSP.setPropertyValue( "TableFilter", aNewFilter ); } @@ -510,16 +479,14 @@ public class DataAwareness extends DocumentBasedExample implements XPropertyChan } /* ------------------------------------------------------------------ */ - /** creates the table SALESMAN + /** creates the table SALESMEN @return <TRUE/> if and only if the creation succeeded */ - protected boolean createTableSalesman( XConnection xConn, String[] out_sTableName ) throws java.lang.Exception + protected boolean createTableSalesman( XConnection xConn ) throws java.lang.Exception { - out_sTableName[0] = "SALESMAN"; - - String sCreateStatement = "CREATE TABLE SALESMAN "; + String sCreateStatement = "CREATE TABLE " + s_tableNameSalesmen + " "; sCreateStatement += "(SNR INTEGER NOT NULL, "; sCreateStatement += "FIRSTNAME VARCHAR(50), "; sCreateStatement += "LASTNAME VARCHAR(100), "; @@ -529,9 +496,9 @@ public class DataAwareness extends DocumentBasedExample implements XPropertyChan sCreateStatement += "BIRTHDATE DATE, "; sCreateStatement += "PRIMARY KEY(SNR))"; - if ( implCreateTable( xConn, sCreateStatement, out_sTableName[0] ) ) + if ( implCreateTable( xConn, sCreateStatement, s_tableNameSalesmen) ) { - String sInsertionPrefix = "INSERT INTO SALESMAN VALUES "; + String sInsertionPrefix = "INSERT INTO " + s_tableNameSalesmen + " VALUES "; implExecuteStatement( xConn, sInsertionPrefix + "(1, 'Joseph', 'Smith', 'Bond Street', 'CA', 95460, '1946-07-02')" ); implExecuteStatement( xConn, sInsertionPrefix + "(2, 'Frank', 'Jones', 'Lake silver', 'CA', 95460, '1963-12-24')" ); @@ -543,16 +510,14 @@ public class DataAwareness extends DocumentBasedExample implements XPropertyChan } /* ------------------------------------------------------------------ */ - /** creates the table CUSTOMER + /** creates the table CUSTOMERS @return <TRUE/> if and only if the creation succeeded */ - protected boolean createTableCustomer( XConnection xConn, String[] out_sTableName ) throws java.lang.Exception + protected boolean createTableCustomer( XConnection xConn ) throws java.lang.Exception { - out_sTableName[0] = "CUSTOMER"; - - String sCreateStatement = "CREATE TABLE CUSTOMER "; + String sCreateStatement = "CREATE TABLE " + s_tableNameCustomers + " "; sCreateStatement += "(COS_NR INTEGER NOT NULL, "; sCreateStatement += "LASTNAME VARCHAR(100), "; sCreateStatement += "STREET VARCHAR(50), "; @@ -561,9 +526,9 @@ public class DataAwareness extends DocumentBasedExample implements XPropertyChan sCreateStatement += "ZIP INTEGER, "; sCreateStatement += "PRIMARY KEY(COS_NR))"; - if ( implCreateTable( xConn, sCreateStatement, out_sTableName[0] ) ) + if ( implCreateTable( xConn, sCreateStatement, s_tableNameCustomers ) ) { - String sInsertionPrefix = "INSERT INTO CUSTOMER VALUES "; + String sInsertionPrefix = "INSERT INTO " + s_tableNameCustomers + " VALUES "; implExecuteStatement( xConn, sInsertionPrefix + "(100, 'Acme, Inc.', '99 Market Street', 'Groundsville', 'CA', 95199)" ); implExecuteStatement( xConn, sInsertionPrefix + "(101, 'Superior BugSoft', '1 Party Place', 'Mendocino', 'CA', 95460)"); @@ -580,11 +545,9 @@ public class DataAwareness extends DocumentBasedExample implements XPropertyChan @return <TRUE/> if and only if the creation succeeded */ - protected boolean createTableSales( XConnection xConn, String[] out_sTableName ) throws java.lang.Exception + protected boolean createTableSales( XConnection xConn ) throws java.lang.Exception { - out_sTableName[0] = "SALES"; - - String sCreateStatement = "CREATE TABLE SALES "; + String sCreateStatement = "CREATE TABLE " + s_tableNameSales + " "; sCreateStatement += "(SALENR INTEGER NOT NULL, "; sCreateStatement += "COS_NR INTEGER NOT NULL, "; sCreateStatement += "SNR INTEGER NOT NULL, "; @@ -593,9 +556,9 @@ public class DataAwareness extends DocumentBasedExample implements XPropertyChan sCreateStatement += "PRICE DECIMAL(8,2), "; sCreateStatement += "PRIMARY KEY(SALENR))"; - if ( implCreateTable( xConn, sCreateStatement, out_sTableName[0] ) ) + if ( implCreateTable( xConn, sCreateStatement, s_tableNameSales ) ) { - String sInsertionPrefix = "INSERT INTO SALES VALUES "; + String sInsertionPrefix = "INSERT INTO " + s_tableNameSales + " VALUES "; implExecuteStatement( xConn, sInsertionPrefix + "(1, 100, 1, 'Fruits', '2005-02-12', 39.99)" ); implExecuteStatement( xConn, sInsertionPrefix + "(2, 101, 3, 'Beef', '2005-10-18', 15.78)" ); @@ -613,194 +576,17 @@ public class DataAwareness extends DocumentBasedExample implements XPropertyChan */ protected void ensureTables() throws java.lang.Exception { - XNameAccess aDSContext = (XNameAccess)UnoRuntime.queryInterface( XNameAccess.class, - m_xCtx.getServiceManager().createInstanceWithContext( - "com.sun.star.sdb.DatabaseContext", m_xCtx ) ); - - if ( !aDSContext.hasByName( m_aParameters.sDataSourceName ) ) - { - String sError = new String( "There is no data source named '" ); - sError += m_aParameters.sDataSourceName; - sError += new String( "'!" ); - System.out.println( sError ); - System.exit( 2 ); - } - // get the data source - XDataSource xDS = (XDataSource)UnoRuntime.queryInterface( XDataSource.class, - aDSContext.getByName( m_aParameters.sDataSourceName ) ); + XDataSource xDS = m_database.getDataSource(); XPropertySet xDSProps = UNO.queryPropertySet( xDS ); - - if ( ( 0 == m_aParameters.sUser.length() ) && ( 0 < m_aParameters.sPassword.length() ) ) - { // the user gave us a password, but no user name - m_aParameters.sUser = (String)xDSProps.getPropertyValue( "User" ); - } - - // connect to this data source - XConnection xConn = xDS.getConnection( m_aParameters.sUser, m_aParameters.sPassword ); + XConnection xConn = xDS.getConnection( "", "" ); XComponent xConnComp = UNO.queryComponent( xConn ); - // do we need do remember the password? - if ( null != xConn ) - { // connecting was a success - if ( 0 != m_aParameters.sPassword.length() ) - { // and we (resp. the user) supplied a password to establish the connection - String sOldPassword = (String)xDSProps.getPropertyValue( "Password" ); - if ( 0 == sOldPassword.length() ) - { // and the data source did not have a password before - String sOldUser = (String)xDSProps.getPropertyValue( "User" ); - if ( sOldUser.equals( m_aParameters.sUser ) ) - { // and the user name is the same - // => remember the password for this session - xDSProps.setPropertyValue( "Password", m_aParameters.sPassword ); - } - } - } - } - - // get the tables of the data source - XTablesSupplier xSuppTables = UNO.queryTablesSupplier( xConn ); - XNameAccess xTables = xSuppTables.getTables(); - - boolean bFakedTablePrefix = false; - // this will track if we faked the table prefix of our parameters - - boolean bHasAll = false; - while ( !bHasAll ) - { - // okay, check if there is a table for the salesmen ... - String sSalesmanTable = m_aParameters.addTablePrefix( "SALESMAN" ); - boolean bHasSalesman = xTables.hasByName( sSalesmanTable ); - - // ... and the customers - String sCustomerTable = m_aParameters.addTablePrefix( "CUSTOMER" ); - boolean bHasCustomer = xTables.hasByName( sCustomerTable ); - - // ... and the customers - String sSalesTable = m_aParameters.addTablePrefix( "SALES" ); - boolean bHasSales = xTables.hasByName( sSalesTable ); - - boolean bHasAny = bHasSalesman || bHasCustomer || bHasSales; - bHasAll = bHasSalesman && bHasCustomer && bHasSales; - - if ( !bHasAll ) - { - // perhaps the user just didn't give us a table prefix - if ( !bHasAny // we do not have any of the tables - && ( 0 == m_aParameters.sTablePrefix.length() ) // we do not have a table prefix - && !bFakedTablePrefix // and we did not yet try to fake a prefix - ) - { - if ( 0 != m_aParameters.sUser.length() ) - { - // assume the user name as table prefix - m_aParameters.sTablePrefix = m_aParameters.sUser; - bFakedTablePrefix = true; - } - else - { - String sDataSourceUserName = (String)xDSProps.getPropertyValue( "User" ); - m_aParameters.sTablePrefix = sDataSourceUserName; - bFakedTablePrefix = true; - } - if ( 0 != m_aParameters.sTablePrefix.length() ) - { - // normalize the prefix which we are assuming from now on - XDatabaseMetaData xMeta = xConn.getMetaData(); - if ( xMeta.storesUpperCaseIdentifiers() ) - m_aParameters.sTablePrefix = m_aParameters.sTablePrefix.toUpperCase(); - else if ( xMeta.storesLowerCaseIdentifiers() ) - m_aParameters.sTablePrefix = m_aParameters.sTablePrefix.toLowerCase(); - - // we have another thing we can try - System.out.println( "none of the required tables found - assuming table prefix \"" + m_aParameters.sTablePrefix + "\"" ); - System.out.println(); - continue; - } - } - - // error message and outta here - String sError = new String( "missing table " ); - if ( !bHasSalesman ) - sError += sSalesmanTable; - else if ( !bHasCustomer ) - sError += sCustomerTable; - else if ( !bHasSales ) - sError += sSalesTable; - else - sError += "<unknown>"; - sError += " in data source "; - sError += m_aParameters.sDataSourceName; - - System.out.println( sError ); - - // create the table (if we are allowed to by the user) - boolean bCreationSuccess = false; - - System.out.print( "shall we create the table (Y)? " ); - int nShouldCreate = skipLineFeeds( System.in ); - - if ( ( 'Y' == nShouldCreate ) || ( 'y' == nShouldCreate ) ) - { - String[] sTable = new String[] { new String() }; - - if ( !bHasSalesman ) - bCreationSuccess = createTableSalesman( xConn, sTable ); - else if ( !bHasCustomer ) - bCreationSuccess = createTableCustomer( xConn, sTable ); - else - bCreationSuccess = createTableSales( xConn, sTable ); - - if ( !bHasAny // we did not have any of the tables - && bFakedTablePrefix // the user did not give us a table prefix, but we faked one - && bCreationSuccess // we succeeded to create the table - ) - { - // check if we really need to use this table prefix - // Above, we set the table prefix to the user name, and we did not find all of our tables - // neither without nor with this prefix. - // Thus, at the moment, it may still be possible that we do not need the table - // prefix at all - if ( !existsInvisibleTable( xConn, m_aParameters.addTablePrefix( sTable[0] ) ) ) - { - m_aParameters.sTablePrefix = new String(); - } - } - - if ( bCreationSuccess ) - { - System.out.println( " successfully created table " + m_aParameters.addTablePrefix( sTable[0] ) ); - System.out.println( ); - } - - // now that we created the table, make sure that it is in the table filter of the - // data source - makeTableVisible( xDS, xConn, sTable[0] ); - - // we added a table and changed the table filter, so we need to refresh the tables - // Normally, we would just call XRefreshable::refresh on the tables container. - XRefreshable xRefresh = (XRefreshable)UnoRuntime.queryInterface( XRefreshable.class, xTables ); - xRefresh.refresh(); - - // Unfortunately, there is a bug that this does not work currently - simply nothing happens. - // So we dispose and re-open the connection. - xConnComp.dispose(); - - xConn = xDS.getConnection( m_aParameters.sUser, m_aParameters.sPassword ); - xConnComp = UNO.queryComponent( xConn ); - xSuppTables = UNO.queryTablesSupplier( xConn ); - xTables = xSuppTables.getTables(); - } - - if ( !bCreationSuccess ) - { - xConnComp.dispose(); - System.exit( 3 ); - } - } - } + createTableSalesman( xConn ); + createTableCustomer( xConn ); + createTableSales( xConn ); // free the resources acquired by the connection xConnComp.dispose(); @@ -827,7 +613,7 @@ public class DataAwareness extends DocumentBasedExample implements XPropertyChan @return the model of the newly created button */ - protected XPropertySet createButton( int nXPos, int nYPos, int nXSize, String sName, String sLabel, String sActionURL ) throws java.lang.Exception + protected XPropertySet createButton( int nXPos, int nYPos, int nXSize, String sName, String sLabel, short _formFeature ) throws java.lang.Exception { XPropertySet xButton = m_formLayer.createControlAndShape( "CommandButton", nXPos, nYPos, nXSize, 6 ); // the name for referring to it later: @@ -839,12 +625,10 @@ public class DataAwareness extends DocumentBasedExample implements XPropertyChan // don't want buttons to be accessible by the "tab" key - this would be uncomfortable when traveling // with records with "tab" xButton.setPropertyValue( "Tabstop", new Boolean( false ) ); + // similar, they should not steal the focus when clicked + xButton.setPropertyValue( "FocusOnClick", new Boolean( false ) ); - // create our button operator, if necessary - if ( null == m_aOperator ) - m_aOperator = new ButtonOperator( m_xCtx, m_document ); - - m_aOperator.addButton( xButton, sActionURL ); + m_aOperator.addButton( xButton, _formFeature ); return xButton; } @@ -909,6 +693,8 @@ public class DataAwareness extends DocumentBasedExample implements XPropertyChan { super.prepareDocument(); + m_database = new HsqlDatabase( m_xCtx ); + // ensure that we have the tables needed for our example ensureTables(); @@ -938,26 +724,21 @@ public class DataAwareness extends DocumentBasedExample implements XPropertyChan m_xMasterForm = FLTools.getParent( xZipField ); // set the data source signature at the form - m_xMasterForm.setPropertyValue( "DataSourceName", m_aParameters.sDataSourceName ); + m_xMasterForm.setPropertyValue( "DataSourceName", m_database.getDocumentURL() ); m_xMasterForm.setPropertyValue( "CommandType", new Integer( CommandType.TABLE ) ); - m_xMasterForm.setPropertyValue( "Command", m_aParameters.addTablePrefix( "SALESMAN" ) ); + m_xMasterForm.setPropertyValue( "Command", "SALESMEN" ); // -------------------------------------------------------------- // insert the buttons - createButton( 2, 63, 8, "first", "<<", ".uno:FormSlots/moveToFirst#0\\0" ); - createButton( 12, 63, 8, "prev", "<", ".uno:FormSlots/moveToPrev#0\\0" ); - createButton( 22, 63, 8, "next", ">", ".uno:FormSlots/moveToNext#0\\0" ); - createButton( 32, 63, 8, "last", ">>", ".uno:FormSlots/moveToLast#0\\0" ); - createButton( 42, 63, 8, "new", ">*", ".uno:FormSlots/moveToNew#0\\0" ); - - // NOTE: - // The URLs above imply knowledge about the current implementation. - // The part before the '#' is an official URL, the part after that means that we refer - // to a functionallity in Form 1 of DrawPage 1 of the document. - // If we would not have these implementation bugs which prevent us from calling "XResultSet::first" - // and friends from Java, we would not need this implementation details. + // create our button operator, if necessary + m_aOperator = new ButtonOperator( m_xCtx, m_document, m_xMasterForm ); - createButton( 58, 63, 13, "reload", "reload", "" ); + createButton( 2, 63, 8, "first", "<<", FormFeature.MoveToFirst ); + createButton( 12, 63, 8, "prev", "<", FormFeature.MoveToPrevious ); + createButton( 22, 63, 8, "next", ">", FormFeature.MoveToNext ); + createButton( 32, 63, 8, "last", ">>", FormFeature.MoveToLast ); + createButton( 42, 63, 8, "new", ">*", FormFeature.MoveToInsertRow ); + createButton( 58, 63, 13, "reload", "reload", FormFeature.ReloadForm ); // -------------------------------------------------------------- // create a sub for for the sales @@ -966,12 +747,12 @@ public class DataAwareness extends DocumentBasedExample implements XPropertyChan XIndexContainer xSalesForm = m_document.createSubForm( m_xMasterForm, "Sales" ); XPropertySet xSalesFormProps = UNO.queryPropertySet( xSalesForm ); - xSalesFormProps.setPropertyValue( "DataSourceName", m_aParameters.sDataSourceName ); + xSalesFormProps.setPropertyValue( "DataSourceName", m_database.getDocumentURL() ); xSalesFormProps.setPropertyValue( "CommandType", new Integer( CommandType.COMMAND ) ); String sCommand = new String( "SELECT * FROM " ); - sCommand += m_aParameters.addTablePrefix( "SALES" ); - sCommand += " AS SALES WHERE SALES.SNR = :salesmen"; + sCommand += s_tableNameSales; + sCommand += " WHERE " + s_tableNameSales + ".SNR = :salesmen"; xSalesFormProps.setPropertyValue( "Command", sCommand ); // the master-details connection @@ -1003,7 +784,7 @@ public class DataAwareness extends DocumentBasedExample implements XPropertyChan xCustomerColumn.setPropertyValue( "ListSourceType", ListSourceType.SQL ); String sListSource = "SELECT LASTNAME, COS_NR FROM "; - sListSource += m_aParameters.addTablePrefix( "CUSTOMER" ); + sListSource += s_tableNameCustomers; String[] aListSource = new String[] { sListSource }; xCustomerColumn.setPropertyValue( "ListSource", aListSource ); @@ -1114,6 +895,12 @@ public class DataAwareness extends DocumentBasedExample implements XPropertyChan } /* ------------------------------------------------------------------ */ + protected void onFormsAlive() + { + m_aOperator.onFormsAlive(); + } + + /* ------------------------------------------------------------------ */ /** performs any cleanup before exiting the program */ protected void cleanUp( ) throws java.lang.Exception @@ -1143,83 +930,6 @@ public class DataAwareness extends DocumentBasedExample implements XPropertyChan } /* ------------------------------------------------------------------ */ - /** explains how to use this class - */ - protected void explainUsage() - { - System.err.println( "usage: DataAwareness -d <data source name>" ); - System.err.println( " [-u <data source user name>]" ); - System.err.println( " [-p <data source password>]" ); - System.err.println( " [-t <alternate table prefix>]\n" ); - System.err.println( " -d - specifies the name of the data source" ); - System.err.println( " registered in OpenOffice.org where the sample tables" ); - System.err.println( " can be found." ); - System.err.println( " -u - specifies a user name to use when logging on to the data source" ); - System.err.println( " -p - specifies a password to use when logging on to the data source" ); - System.err.println( " -t - specifies a prefix to use for the table names" ); - } - - /* ------------------------------------------------------------------ */ - /** collect the RuntimeArguments - */ - protected void collectParameters(String argv[]) - { - m_aParameters = new Parameters(); - - System.out.println( ); - - // ........................................ - // mandatory: the -d and a data source name - if ( ( argv.length < 2 ) || ( !argv[0].equals( "-d" ) ) ) - { - explainUsage(); - System.exit( 1 ); - } - - m_aParameters.sDataSourceName = new String( argv[1] ); - m_aParameters.sUser = new String(); - m_aParameters.sPassword = new String(); - m_aParameters.sTablePrefix = new String(); - - // ........................................ - // optional arguments - if ( argv.length >= 3 ) - { - // must be a even number of arguments (switch-value pair) - if ( 0 != ( argv.length % 2 ) ) - { - explainUsage(); - System.exit( 1 ); - } - - int nArgPos = 2; - while ( argv.length > nArgPos ) - { - String sValue = new String( argv[ nArgPos + 1 ] ); - // try to recognize the switch - if ( argv[ nArgPos ].equals( "-t" ) ) - { - m_aParameters.sTablePrefix = sValue; - } - else if ( argv[ nArgPos ].equals( "-p" ) ) - { - m_aParameters.sPassword = sValue; - } - else if ( argv[ nArgPos ].equals( "-u" ) ) - { - m_aParameters.sUser = sValue; - } - else - { - explainUsage(); - System.exit( 1 ); - } - nArgPos += 2; - } - } - } - - /* ------------------------------------------------------------------ */ /** class entry point */ public static void main(String argv[]) throws java.lang.Exception diff --git a/odk/examples/DevelopersGuide/Forms/DocumentBasedExample.java b/odk/examples/DevelopersGuide/Forms/DocumentBasedExample.java index 4ee8d3a34fcd..1cc52fd546c1 100644 --- a/odk/examples/DevelopersGuide/Forms/DocumentBasedExample.java +++ b/odk/examples/DevelopersGuide/Forms/DocumentBasedExample.java @@ -27,11 +27,13 @@ * for a copy of the LGPLv3 License. * ************************************************************************/ +package org.openoffice.sdk.forms; + +import com.sun.star.bridge.XUnoUrlResolver; +import com.sun.star.lang.XMultiComponentFactory; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XComponentContext; -import com.sun.star.bridge.XUnoUrlResolver; -import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.util.XCloseable; public abstract class DocumentBasedExample implements com.sun.star.lang.XEventListener @@ -55,13 +57,29 @@ public abstract class DocumentBasedExample implements com.sun.star.lang.XEventLi { try { + /* + final XComponentContext componentContext = com.sun.star.comp.helper.Bootstrap. + createInitialComponentContext( null ); + final XMultiComponentFactory localServiceManager = componentContext.getServiceManager(); + + final XUnoUrlResolver urlResolver = (XUnoUrlResolver) UnoRuntime.queryInterface( + XUnoUrlResolver.class, localServiceManager.createInstanceWithContext( + "com.sun.star.bridge.UnoUrlResolver", componentContext) ); + + final String connectStr = "uno:pipe,name=<pipename>;urp;StarOffice.ComponentContext"; + final Object initialObject = urlResolver.resolve( connectStr ); + + m_xCtx = (XComponentContext)UnoRuntime.queryInterface( XComponentContext.class, + initialObject ); + */ + // get the remote office component context m_xCtx = com.sun.star.comp.helper.Bootstrap.bootstrap(); System.out.println("Connected to a running office ..."); } catch (java.lang.Exception e) { - e.printStackTrace(); + e.printStackTrace( System.err ); System.exit(1); } } @@ -73,7 +91,7 @@ public abstract class DocumentBasedExample implements com.sun.star.lang.XEventLi { try { - // collect whatever parameters where given + // collect whatever parameters were given collectParameters( argv ); // prepare our sample document @@ -81,6 +99,7 @@ public abstract class DocumentBasedExample implements com.sun.star.lang.XEventLi // switch the document view's form layer to alive mode m_document.getCurrentView().toggleFormDesignMode(); + onFormsAlive(); // grab the focus to the first control m_document.getCurrentView().grabControlFocus(); @@ -129,6 +148,13 @@ public abstract class DocumentBasedExample implements com.sun.star.lang.XEventLi } /* ------------------------------------------------------------------ */ + /** called when the form layer has been switched to alive mode + */ + protected void onFormsAlive() + { + } + + /* ------------------------------------------------------------------ */ /** performs any cleanup before exiting the program */ protected void cleanUp( ) throws java.lang.Exception diff --git a/odk/examples/DevelopersGuide/Forms/DocumentViewHelper.java b/odk/examples/DevelopersGuide/Forms/DocumentViewHelper.java index 037ebd421bd7..cf7739cb3263 100644 --- a/odk/examples/DevelopersGuide/Forms/DocumentViewHelper.java +++ b/odk/examples/DevelopersGuide/Forms/DocumentViewHelper.java @@ -27,17 +27,27 @@ * for a copy of the LGPLv3 License. * ************************************************************************/ +package org.openoffice.sdk.forms; + +import com.sun.star.awt.XControl; +import com.sun.star.awt.XControlModel; +import com.sun.star.awt.XWindow; +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XPropertySet; +import com.sun.star.container.XIndexContainer; +import com.sun.star.form.FormComponentType; +import com.sun.star.form.XForm; +import com.sun.star.form.XFormController; +import com.sun.star.frame.XController; +import com.sun.star.frame.XDispatch; +import com.sun.star.frame.XDispatchProvider; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.util.URL; +import com.sun.star.util.XURLTransformer; +import com.sun.star.view.XControlAccess; +import com.sun.star.view.XFormLayerAccess; -/**************************************************************************/ -import com.sun.star.uno.*; -import com.sun.star.frame.*; -import com.sun.star.lang.*; -import com.sun.star.util.*; -import com.sun.star.awt.*; -import com.sun.star.view.*; -import com.sun.star.beans.*; -import com.sun.star.container.*; -import com.sun.star.form.*; /**************************************************************************/ /** provides a small wrapper around a document view @@ -119,13 +129,22 @@ class DocumentViewHelper } /* ------------------------------------------------------------------ */ + /* retrieves the form controller belonging to a given logical form + */ + public XFormController getFormController( Object _form ) + { + XFormLayerAccess formLayer = (XFormLayerAccess)get( XFormLayerAccess.class ); + return formLayer.getFormController( (XForm)UnoRuntime.queryInterface( XForm.class, _form ) ); + } + + /* ------------------------------------------------------------------ */ /** retrieves a control within the current view of a document @param xModel specifies the control model whose control should be located @return the control tied to the model */ - public XControl getControl( XControlModel xModel ) throws com.sun.star.uno.Exception + public XControl getFormControl( XControlModel xModel ) throws com.sun.star.uno.Exception { // the current view of the document XControlAccess xCtrlAcc = (XControlAccess)get( XControlAccess.class ); @@ -134,17 +153,17 @@ class DocumentViewHelper } /* ------------------------------------------------------------------ */ - public XControl getControl( Object aModel ) throws com.sun.star.uno.Exception + public XControl getFormControl( Object aModel ) throws com.sun.star.uno.Exception { XControlModel xModel = (XControlModel)UnoRuntime.queryInterface( XControlModel.class, aModel ); - return getControl( xModel ); + return getFormControl( xModel ); } /* ------------------------------------------------------------------ */ - public Object getControl( Object aModel, Class aInterfaceClass ) throws com.sun.star.uno.Exception + public Object getFormControl( Object aModel, Class aInterfaceClass ) throws com.sun.star.uno.Exception { XControlModel xModel = (XControlModel)UnoRuntime.queryInterface( XControlModel.class, aModel ); - return UnoRuntime.queryInterface( aInterfaceClass, getControl( xModel ) ); + return UnoRuntime.queryInterface( aInterfaceClass, getFormControl( xModel ) ); } /* ------------------------------------------------------------------ */ @@ -171,7 +190,7 @@ class DocumentViewHelper public void grabControlFocus( Object xModel ) throws com.sun.star.uno.Exception { // look for the control from the current view which belongs to the model - XControl xControl = getControl( xModel ); + XControl xControl = getFormControl( xModel ); // the focus can be set to an XWindow only XWindow xControlWindow = (XWindow)UnoRuntime.queryInterface( XWindow.class, diff --git a/odk/examples/DevelopersGuide/Forms/FormLayer.java b/odk/examples/DevelopersGuide/Forms/FormLayer.java index 7b673d2d5be0..b3c52858d78f 100644 --- a/odk/examples/DevelopersGuide/Forms/FormLayer.java +++ b/odk/examples/DevelopersGuide/Forms/FormLayer.java @@ -39,8 +39,6 @@ import com.sun.star.drawing.XShapes; import com.sun.star.awt.Size; import com.sun.star.awt.Point; import com.sun.star.awt.XControlModel; -import com.sun.star.awt.XControl; -import com.sun.star.awt.XWindow; import com.sun.star.text.TextContentAnchorType; import com.sun.star.drawing.XDrawPage; diff --git a/odk/examples/DevelopersGuide/Forms/HsqlDatabase.java b/odk/examples/DevelopersGuide/Forms/HsqlDatabase.java new file mode 100644 index 000000000000..2aa1737e59c4 --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/HsqlDatabase.java @@ -0,0 +1,256 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XPropertySet; +import com.sun.star.container.XNameAccess; +import com.sun.star.frame.XStorable; +import com.sun.star.frame.XModel; +import com.sun.star.sdb.XOfficeDatabaseDocument; +import com.sun.star.sdbc.SQLException; +import com.sun.star.sdbc.XCloseable; +import com.sun.star.sdbc.XConnection; +import com.sun.star.sdbc.XStatement; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.io.IOException; +import com.sun.star.sdb.XDocumentDataSource; +import com.sun.star.sdbc.XDataSource; +import com.sun.star.uno.XComponentContext; +import java.io.File; + +import com.sun.star.util.CloseVetoException; +import java.io.File; + +/** + * + * @author fs93730 + */ +public class HsqlDatabase +{ + XComponentContext m_context; + // the URL of the temporary file used for the database document + String m_databaseDocumentFile; + // the database document + XOfficeDatabaseDocument m_databaseDocument; + // the data source belonging to the database document + // the default connection + XConnection m_connection; + + // -------------------------------------------------------------------------------------------------------- + public HsqlDatabase( XComponentContext _context ) throws Exception + { + m_context = _context; + createDBDocument(); + } + + // -------------------------------------------------------------------------------------------------------- + public HsqlDatabase( XComponentContext _context, String _existingDocumentURL ) throws Exception + { + m_context = _context; + createDBDocument( _existingDocumentURL ); + } + + // -------------------------------------------------------------------------------------------------------- + private void createDBDocument( String _docURL ) throws Exception + { + m_databaseDocumentFile = _docURL; + + XNameAccess dbContext = (XNameAccess)UnoRuntime.queryInterface( XNameAccess.class, + m_context.getServiceManager().createInstanceWithContext( "com.sun.star.sdb.DatabaseContext", m_context ) ); + XDocumentDataSource dataSource = (XDocumentDataSource)UnoRuntime.queryInterface( XDocumentDataSource.class, + dbContext.getByName( _docURL ) ); + + m_databaseDocument = dataSource.getDatabaseDocument(); + } + + /** creates an empty database document in a temporary location + */ + private void createDBDocument() throws Exception + { + File documentFile = File.createTempFile("testdb",".odb"); + documentFile.deleteOnExit(); + m_databaseDocumentFile = URLHelper.getFileURLFromSystemPath( documentFile ); + + m_databaseDocument = (XOfficeDatabaseDocument)UnoRuntime.queryInterface( + XOfficeDatabaseDocument.class, m_context.getServiceManager().createInstanceWithContext( + "com.sun.star.sdb.OfficeDatabaseDocument", m_context ) ); + + XPropertySet dsProperties = (XPropertySet)UnoRuntime.queryInterface( XPropertySet.class, m_databaseDocument.getDataSource() ); + dsProperties.setPropertyValue("URL", "sdbc:embedded:hsqldb"); + + XStorable storable = (XStorable)UnoRuntime.queryInterface( XStorable.class, m_databaseDocument ); + storable.storeAsURL( m_databaseDocumentFile, new PropertyValue[]{} ); + } + + /** returns a connection to the database + * + * Multiple calls to this method return the same connection. The HsqlDatabase object keeps + * the ownership of the connection, so you don't need to (and should not) dispose/close it. + * + */ + public XConnection defaultConnection() throws SQLException + { + if ( m_connection != null ) + return m_connection; + m_connection = m_databaseDocument.getDataSource().getConnection(new String(),new String()); + return m_connection; + } + + /** executes the given SQL statement via the defaultConnection + */ + public void executeSQL( String statementString ) throws SQLException + { + XStatement statement = defaultConnection().createStatement(); + statement.execute( statementString ); + } + + /** stores the database document + */ + public void store() throws IOException + { + if ( m_databaseDocument != null ) + { + XStorable storeDoc = (XStorable)UnoRuntime.queryInterface( XStorable.class, + m_databaseDocument ); + storeDoc.store(); + } + } + + /** closes the database document + * + * Any CloseVetoExceptions fired by third parties are ignored, and any reference to the + * database document is released. + */ + public void close() + { + // close connection + XCloseable closeConn = (XCloseable)UnoRuntime.queryInterface( XCloseable.class, + m_connection ); + if ( closeConn != null ) + { + try + { + closeConn.close(); + } + catch( SQLException e ) + { + } + } + m_connection = null; + + // close document + com.sun.star.util.XCloseable closeDoc = (com.sun.star.util.XCloseable)UnoRuntime.queryInterface( + com.sun.star.util.XCloseable.class, m_databaseDocument ); + if ( closeDoc != null ) + { + try + { + closeDoc.close( true ); + } + catch( CloseVetoException e ) + { + } + } + m_databaseDocument = null; + } + + /** closes the document, and deletes the underlying file + */ + public void closeAndDelete() + { + close(); + + if ( m_databaseDocumentFile != null ) + { + try + { + File file = new File(m_databaseDocumentFile); + file.delete(); + } + catch(Exception e) + { + } + m_databaseDocumentFile = null; + } + } + + /** returns the underlying database document + */ + public XOfficeDatabaseDocument getDatabaseDocument() + { + return m_databaseDocument; + } + + /** returns the associated data source + */ + public XDataSource getDataSource() + { + return m_databaseDocument.getDataSource(); + } + + /** returns the model interface of the underlying database document + */ + XModel getModel() + { + return (XModel)UnoRuntime.queryInterface( XModel.class, m_databaseDocument ); + } + + /** drops the table with a given name + + @param _name + the name of the table to drop + @param _ifExists + TRUE if it should be dropped only when it exists. + */ + public void dropTable( String _name, boolean _ifExists ) throws SQLException + { + String dropStatement = "DROP TABLE \"" + _name; + if ( _ifExists ) + dropStatement += "\" IF EXISTS"; + executeSQL( dropStatement ); + } + + /** returns the URL of the ODB document represented by this instance + */ + public String getDocumentURL() + { + return m_databaseDocumentFile; + } + + /** creates a row set operating the database, with a given command/type + */ + public RowSet createRowSet( int _commandType, String _command ) + { + return new RowSet( m_context, getDocumentURL(), _commandType, _command ); + } + + protected void finalize() throws Throwable + { + closeAndDelete(); + super.finalize(); + } +} diff --git a/odk/examples/DevelopersGuide/Forms/Makefile b/odk/examples/DevelopersGuide/Forms/Makefile index b559e38f9487..37b1fa60134d 100644 --- a/odk/examples/DevelopersGuide/Forms/Makefile +++ b/odk/examples/DevelopersGuide/Forms/Makefile @@ -92,7 +92,10 @@ COMMON_JAVAFILES = \ DateValidator.java \ TimeValidator.java \ ControlValidator.java \ - SingleControlValidation.java + SingleControlValidation.java \ + HsqlDatabase.java \ + RowSet.java \ + URLHelper.java COMMON_CLASSFILES = $(patsubst %.java,$(COMMON_CLASS_OUT)/%.class,$(COMMON_JAVAFILES)) diff --git a/odk/examples/DevelopersGuide/Forms/RowSet.java b/odk/examples/DevelopersGuide/Forms/RowSet.java new file mode 100644 index 000000000000..76d65873c9d8 --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/RowSet.java @@ -0,0 +1,290 @@ +/************************************************************************* + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2008 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + * + ************************************************************************/ + +import com.sun.star.beans.XPropertySet; +import com.sun.star.container.XIndexAccess; +import com.sun.star.container.XNameAccess; +import com.sun.star.io.XInputStream; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.sdbc.SQLException; +import com.sun.star.sdbc.XArray; +import com.sun.star.sdbc.XBlob; +import com.sun.star.sdbc.XClob; +import com.sun.star.sdbc.XRef; +import com.sun.star.sdbc.XRow; +import com.sun.star.sdbc.XRowSet; +import com.sun.star.sdbc.XRowSetListener; +import com.sun.star.sdbcx.XColumnsSupplier; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; +import com.sun.star.util.Date; +import com.sun.star.util.DateTime; +import com.sun.star.util.Time; + +public class RowSet implements XRowSet, XRow +{ + private XRowSet m_rowSet; + private XRow m_row; + private XPropertySet m_rowSetProps; + + public RowSet( XComponentContext _context, String _dataSource, int _commandType, String _command ) + { + try + { + m_rowSetProps = (XPropertySet)UnoRuntime.queryInterface( + XPropertySet.class, _context.getServiceManager().createInstanceWithContext( "com.sun.star.sdb.RowSet", _context ) ); + m_rowSetProps.setPropertyValue( "DataSourceName", _dataSource ); + m_rowSetProps.setPropertyValue( "CommandType", new Integer( _commandType ) ); + m_rowSetProps.setPropertyValue( "Command", _command ); + + m_rowSet = (XRowSet)UnoRuntime.queryInterface( XRowSet.class, m_rowSetProps ); + m_row = (XRow)UnoRuntime.queryInterface( XRow.class, m_rowSetProps ); + } + catch ( Exception e ) + { + e.printStackTrace(System.err); + throw new java.lang.InstantiationError(); + } + } + + // misc + public int getColumnCount() + { + XColumnsSupplier suppCols = (XColumnsSupplier)UnoRuntime.queryInterface( + XColumnsSupplier.class, m_rowSet ); + XIndexAccess columns = (XIndexAccess)UnoRuntime.queryInterface( + XIndexAccess.class, suppCols.getColumns() ); + return columns.getCount(); + } + + // XRowSet + public void execute() throws SQLException + { + m_rowSet.execute(); + } + + public void addRowSetListener( XRowSetListener _listener ) + { + m_rowSet.addRowSetListener( _listener ); + } + + public void removeRowSetListener( XRowSetListener _listener ) + { + m_rowSet.removeRowSetListener( _listener ); + } + + public boolean next() throws SQLException + { + return m_rowSet.next(); + } + + public boolean isBeforeFirst() throws SQLException + { + return m_rowSet.isBeforeFirst(); + } + + public boolean isAfterLast() throws SQLException + { + return m_rowSet.isAfterLast(); + } + + public boolean isFirst() throws SQLException + { + return m_rowSet.isFirst(); + } + + public boolean isLast() throws SQLException + { + return m_rowSet.isLast(); + } + + public void beforeFirst() throws SQLException + { + m_rowSet.beforeFirst(); + } + + public void afterLast() throws SQLException + { + m_rowSet.afterLast(); + } + + public boolean first() throws SQLException + { + return m_rowSet.first(); + } + + public boolean last() throws SQLException + { + return m_rowSet.last(); + } + + public int getRow() throws SQLException + { + return m_rowSet.getRow(); + } + + public boolean absolute(int i) throws SQLException + { + return m_rowSet.absolute(i); + } + + public boolean relative(int i) throws SQLException + { + return m_rowSet.relative(i); + } + + public boolean previous() throws SQLException + { + return m_rowSet.previous(); + } + + public void refreshRow() throws SQLException + { + m_rowSet.refreshRow(); + } + + public boolean rowUpdated() throws SQLException + { + return m_rowSet.rowUpdated(); + } + + public boolean rowInserted() throws SQLException + { + return m_rowSet.rowInserted(); + } + + public boolean rowDeleted() throws SQLException + { + return m_rowSet.rowDeleted(); + } + + // XRow + public Object getStatement() throws SQLException + { + return m_rowSet.getStatement(); + } + + public boolean wasNull() throws SQLException + { + return m_row.wasNull(); + } + + public String getString(int i) throws SQLException + { + return m_row.getString(i); + } + + public boolean getBoolean(int i) throws SQLException + { + return m_row.getBoolean(i); + } + + public byte getByte(int i) throws SQLException + { + return m_row.getByte(i); + } + + public short getShort(int i) throws SQLException + { + return m_row.getShort(i); + } + + public int getInt(int i) throws SQLException + { + return m_row.getInt(i); + } + + public long getLong(int i) throws SQLException + { + return m_row.getLong(i); + } + + public float getFloat(int i) throws SQLException + { + return m_row.getFloat(i); + } + + public double getDouble(int i) throws SQLException + { + return m_row.getDouble(i); + } + + public byte[] getBytes(int i) throws SQLException + { + return m_row.getBytes(i); + } + + public Date getDate(int i) throws SQLException + { + return m_row.getDate(i); + } + + public Time getTime(int i) throws SQLException + { + return m_row.getTime(i); + } + + public DateTime getTimestamp(int i) throws SQLException + { + return m_row.getTimestamp(i); + } + + public XInputStream getBinaryStream(int i) throws SQLException + { + return m_row.getBinaryStream(i); + } + + public XInputStream getCharacterStream(int i) throws SQLException + { + return m_row.getCharacterStream(i); + } + + public Object getObject(int i, XNameAccess xNameAccess) throws SQLException + { + return m_row.getObject(i, xNameAccess); + } + + public XRef getRef(int i) throws SQLException + { + return m_row.getRef(i); + } + + public XBlob getBlob(int i) throws SQLException + { + return m_row.getBlob(i); + } + + public XClob getClob(int i) throws SQLException + { + return m_row.getClob(i); + } + + public XArray getArray(int i) throws SQLException + { + return m_row.getArray(i); + } +}; diff --git a/odk/examples/DevelopersGuide/Forms/SalesFilter.java b/odk/examples/DevelopersGuide/Forms/SalesFilter.java index 3449a6f7b483..a61d152d2ff9 100644 --- a/odk/examples/DevelopersGuide/Forms/SalesFilter.java +++ b/odk/examples/DevelopersGuide/Forms/SalesFilter.java @@ -118,7 +118,7 @@ class SalesFilter implements XActionListener, XPropertyChangeListener, XResetLis // for the button, we can add to the control only, not to the model // - clicking a button is something which happens on the _control_. DocumentViewHelper aView = m_aDocument.getCurrentView(); - XButton xButton = (XButton)aView.getControl( m_xApplyFilter, XButton.class ); + XButton xButton = (XButton)aView.getFormControl( m_xApplyFilter, XButton.class ); xButton.addActionListener( this ); } catch ( com.sun.star.uno.Exception e ) diff --git a/odk/examples/DevelopersGuide/Forms/URLHelper.java b/odk/examples/DevelopersGuide/Forms/URLHelper.java new file mode 100644 index 000000000000..c3d4ecfad5a9 --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/URLHelper.java @@ -0,0 +1,70 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * Copyright 2009 by Sun Microsystems, Inc. + * + * OpenOffice.org - a multi-platform office productivity suite + * + * This file is part of OpenOffice.org. + * + * OpenOffice.org is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License version 3 + * only, as published by the Free Software Foundation. + * + * OpenOffice.org is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License version 3 for more details + * (a copy is included in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU Lesser General Public License + * version 3 along with OpenOffice.org. If not, see + * <http://www.openoffice.org/license.html> + * for a copy of the LGPLv3 License. + */ + +import java.io.File; +import java.net.MalformedURLException; + +public class URLHelper +{ + /** + * Because the office need URLs for loading/saving documents + * we must convert used system pathes. + * And java use another notation for file URLs ... correct it. + * + * @param aSystemPath + * represent the file in system notation + * + * @return [String] + * a file url which represent the given system path + */ + @SuppressWarnings("deprecation") + public static String getFileURLFromSystemPath( File aSystemPath ) + { + String sFileURL = null; + try + { + sFileURL = aSystemPath.toURL().toString(); + } + catch( MalformedURLException exWrong ) + { + sFileURL = null; + } + + // problem of java: file URL's are coded with 1 slash instead of 2 or 3 ones! + // => correct this problem first, otherwise office can't use these URL's + if( + (sFileURL != null ) && + (sFileURL.startsWith("file:/") == true ) && + (sFileURL.startsWith("file://") == false) + ) + { + StringBuffer sWorkBuffer = new StringBuffer(sFileURL); + sWorkBuffer.insert(6,"//"); + sFileURL = sWorkBuffer.toString(); + } + + return sFileURL; + } +} diff --git a/odk/examples/DevelopersGuide/Forms/makefile.mk b/odk/examples/DevelopersGuide/Forms/makefile.mk index 016bce5dec0b..3e022d6763a0 100644 --- a/odk/examples/DevelopersGuide/Forms/makefile.mk +++ b/odk/examples/DevelopersGuide/Forms/makefile.mk @@ -75,6 +75,9 @@ FORMS_FILES=\ $(DESTDIRDEVGUIDEEXAMPLES)$/Forms$/TimeValidator.java \ $(DESTDIRDEVGUIDEEXAMPLES)$/Forms$/UNO.java \ $(DESTDIRDEVGUIDEEXAMPLES)$/Forms$/ValueBinding.java \ + $(DESTDIRDEVGUIDEEXAMPLES)$/Forms$/URLHelper.java \ + $(DESTDIRDEVGUIDEEXAMPLES)$/Forms$/HsqlDatabase.java \ + $(DESTDIRDEVGUIDEEXAMPLES)$/Forms$/RowSet.java \ $(DESTDIRDEVGUIDEEXAMPLES)$/Forms$/WaitForInput.java DIR_FILE_LIST= \ |