### Eclipse Workspace Patch 1.0 #P testuno Index: source/testcase/uno/db/utils/TestCase.java =================================================================== --- source/testcase/uno/db/utils/TestCase.java (revision 0) +++ source/testcase/uno/db/utils/TestCase.java (revision 0) @@ -0,0 +1,140 @@ +/************************************************************** + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + *************************************************************/ + + +package testcase.uno.db.utils; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XPropertySet; +import com.sun.star.bridge.UnoUrlResolver; +import com.sun.star.bridge.XUnoUrlResolver; +import com.sun.star.comp.helper.Bootstrap; +import com.sun.star.connection.NoConnectException; +import com.sun.star.frame.XComponentLoader; +import com.sun.star.frame.XModel; +import com.sun.star.lang.XMultiServiceFactory; +// import com.sun.star.uno.Exception; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; + +// ---------- junit imports ----------------- +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.openoffice.test.uno.UnoApp; + +import static org.junit.Assert.*; +// ------------------------------------------ + + +public abstract class TestCase +{ + // -------------------------------------------------------------------------------------------------------- + protected final XComponentContext getComponentContext() + { + XComponentContext context = null; + try + { + final XPropertySet orbProps = UnoRuntime.queryInterface( XPropertySet.class, getMSF() ); + context = UnoRuntime.queryInterface( XComponentContext.class, + orbProps.getPropertyValue( "DefaultContext" ) ); + } + catch ( Exception ex ) + { + fail( "could not retrieve the ComponentContext" ); + } + return context; + } + + // -------------------------------------------------------------------------------------------------------- + public void before() throws java.lang.Exception + { + } + + public void after() throws java.lang.Exception + { + } + + + @BeforeClass + public static void setUpConnection() throws Exception { + app.start(); + } + + @AfterClass + public static void tearDownConnection() throws Exception { + app.close(); + } + + private static final UnoApp app = new UnoApp(); + + // -------------------------------------------------------------------------------------------------------- + /** returns the URL of a temporary file which can be used during the test. + * + * The file will be deleted when the process exits + * @return the URL of a temporary file + */ + protected final String createTempFileURL() throws IOException + { + final File documentFile = java.io.File.createTempFile( "dbaccess_test", ".odb" ).getAbsoluteFile(); + if ( documentFile.exists() ) + { + documentFile.delete(); + } + return getOOoCompatibleFileURL( documentFile.toURI().toURL().toString() ); + } + + public String getOOoCompatibleFileURL( String _javaFileURL ) + { + String returnURL = _javaFileURL; + if ( ( returnURL.indexOf( "file:/" ) == 0 ) && ( returnURL.indexOf( "file:///" ) == -1 ) ) + { + // for some reason, the URLs here in Java start with "file:/" only, instead of "file:///" + // Some of the office code doesn't like this ... + returnURL = "file:///" + returnURL.substring( 6 ); + } + return returnURL; + } + + + protected final XModel loadDocument( final String _docURL ) throws Exception + { + final XComponentLoader loader = UnoRuntime.queryInterface( XComponentLoader.class, + getMSF().createInstance( "com.sun.star.frame.Desktop" ) ); + return UnoRuntime.queryInterface( XModel.class, + loader.loadComponentFromURL( _docURL, "_blank", 0, new PropertyValue[] {} ) ); + } + + + protected XMultiServiceFactory getMSF() + { + final XMultiServiceFactory xMSF1 = UnoRuntime.queryInterface(XMultiServiceFactory.class, app.getComponentContext().getServiceManager()); + return xMSF1; + } + + + +} Index: source/testcase/uno/db/utils/Connection.java =================================================================== --- source/testcase/uno/db/utils/Connection.java (revision 0) +++ source/testcase/uno/db/utils/Connection.java (revision 0) @@ -0,0 +1,114 @@ +/************************************************************** + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + *************************************************************/ + +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ + +package testcase.uno.db.utils; + +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.sdb.XSingleSelectQueryComposer; +import com.sun.star.sdbc.SQLException; +import com.sun.star.sdbc.XConnection; +import com.sun.star.sdbc.XDatabaseMetaData; +import com.sun.star.sdbc.XPreparedStatement; +import com.sun.star.sdbc.XResultSet; +import com.sun.star.sdbc.XStatement; +import com.sun.star.sdbcx.XTablesSupplier; +import com.sun.star.uno.Exception; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.util.XRefreshable; + +/** + * is a convenience wrapper around a SDB-level connection object + */ +public class Connection +{ + private final XConnection m_connection; + + public Connection( final XConnection _connection ) + { + m_connection = _connection; + } + + public XConnection getXConnection() + { + return m_connection; + } + + public boolean execute( final String _sql ) throws SQLException + { + XStatement statement = createStatement(); + return statement.execute( _sql ); + } + + public XResultSet executeQuery( final String _sql ) throws SQLException + { + XStatement statement = createStatement(); + return statement.executeQuery( _sql ); + } + + public int executeUpdate( final String _sql ) throws SQLException + { + XStatement statement = createStatement(); + return statement.executeUpdate( _sql ); + } + + public void refreshTables() + { + final XTablesSupplier suppTables = UnoRuntime.queryInterface(XTablesSupplier.class, m_connection); + final XRefreshable refresh = UnoRuntime.queryInterface( XRefreshable.class, suppTables.getTables() ); + refresh.refresh(); + } + + public XSingleSelectQueryComposer createSingleSelectQueryComposer() throws Exception + { + final XMultiServiceFactory connectionFactory = UnoRuntime.queryInterface( XMultiServiceFactory.class, m_connection ); + return UnoRuntime.queryInterface( + XSingleSelectQueryComposer.class, connectionFactory.createInstance( "com.sun.star.sdb.SingleSelectQueryComposer" ) ); + } + + public + XStatement createStatement() throws SQLException + { + return m_connection.createStatement(); + } + + public + XPreparedStatement prepareStatement( String _sql ) throws SQLException + { + return m_connection.prepareStatement( _sql ); + } + + public + XDatabaseMetaData getMetaData() throws SQLException + { + return m_connection.getMetaData(); + } + + public + void close() throws SQLException + { + m_connection.close(); + } +} Index: source/testcase/uno/db/utils/HsqlDatabase.java =================================================================== --- source/testcase/uno/db/utils/HsqlDatabase.java (revision 0) +++ source/testcase/uno/db/utils/HsqlDatabase.java (revision 0) @@ -0,0 +1,208 @@ +/************************************************************** + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + *************************************************************/ + + +package testcase.uno.db.utils; + +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.PropertyState; +import com.sun.star.beans.XPropertySet; +import com.sun.star.container.ElementExistException; +import com.sun.star.frame.XStorable; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.sdb.XOfficeDatabaseDocument; +import com.sun.star.sdbc.SQLException; +import com.sun.star.sdbcx.XAppend; +import com.sun.star.sdbcx.XTablesSupplier; +import com.sun.star.uno.UnoRuntime; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Set; +import java.io.File; + +/** + * + * @author fs93730 + */ +public class HsqlDatabase extends AbstractDatabase +{ + + // -------------------------------------------------------------------------------------------------------- + public HsqlDatabase(final XMultiServiceFactory orb) throws Exception + { + super(orb); + createDBDocument(); + } + + // -------------------------------------------------------------------------------------------------------- + public HsqlDatabase(final XMultiServiceFactory orb, final String _existingDocumentURL) throws Exception + { + super(orb, _existingDocumentURL); + } + + /** creates an empty database document in a temporary location + */ + private void createDBDocument() throws Exception + { + final File documentFile = File.createTempFile("testdb", ".odb"); + if ( documentFile.exists() ) + documentFile.delete(); + m_databaseDocumentFile = URLHelper.getFileURLFromSystemPath(documentFile); + + m_databaseDocument = (XOfficeDatabaseDocument) UnoRuntime.queryInterface( + XOfficeDatabaseDocument.class, m_orb.createInstance("com.sun.star.sdb.OfficeDatabaseDocument")); + m_dataSource = new DataSource(m_orb, m_databaseDocument.getDataSource()); + + final XPropertySet dsProperties = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, m_databaseDocument.getDataSource()); + dsProperties.setPropertyValue("URL", "sdbc:embedded:hsqldb"); + + final XStorable storable = (XStorable) UnoRuntime.queryInterface(XStorable.class, m_databaseDocument); + storable.storeAsURL( m_databaseDocumentFile, new PropertyValue[] + { new PropertyValue( "PickListEntry", 0, false, PropertyState.DIRECT_VALUE ) + } ); + } + + /** 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(final String _name, final boolean _ifExists) throws SQLException + { + final StringBuffer dropStatement = new StringBuffer("DROP TABLE \""); + dropStatement.append(_name); + if (_ifExists) + { + dropStatement.append("\" IF EXISTS"); + } + executeSQL(dropStatement.toString()); + } + + public void createTable(final HsqlTableDescriptor _tableDesc, final boolean _dropIfExists) throws SQLException + { + if (_dropIfExists) + { + dropTable(_tableDesc.getName(), true); + } + createTable(_tableDesc); + } + + /** creates a table + */ + public void createTable(final HsqlTableDescriptor _tableDesc) throws SQLException + { + StringBuffer createStatement = new StringBuffer("CREATE CACHED TABLE \""); + createStatement.append(_tableDesc.getName()); + createStatement.append("\" ( "); + + String primaryKeyList = ""; + + final HashMap foreignKeys = new HashMap(); + final HashMap foreignKeyRefs = new HashMap(); + + final HsqlColumnDescriptor[] columns = _tableDesc.getColumns(); + for (int i = 0; i < columns.length; ++i) + { + if (i > 0) + { + createStatement.append(", "); + } + + createStatement.append("\"" + columns[i].getName()); + createStatement.append("\" " + columns[i].getTypeName()); + + if (columns[i].isRequired()) + { + createStatement.append(" NOT NULL"); + } + + if (columns[i].isPrimaryKey()) + { + if (primaryKeyList.length() > 0) + { + primaryKeyList += ", "; + } + primaryKeyList += "\"" + columns[i].getName() + "\""; + } + + if (columns[i].isForeignKey()) + { + final String foreignTable = columns[i].getForeignTable(); + + String foreignKeysForTable = foreignKeys.containsKey(foreignTable) ? (String) foreignKeys.get(foreignTable) : ""; + if (foreignKeysForTable.length() > 0) + { + foreignKeysForTable += ", "; + } + foreignKeysForTable += "\"" + columns[i].getName() + "\""; + foreignKeys.put(foreignTable, foreignKeysForTable); + + final StringBuffer foreignKeyRefsForTable = new StringBuffer(foreignKeyRefs.containsKey(foreignTable) ? (String) foreignKeyRefs.get(foreignTable) : ""); + if (foreignKeyRefsForTable.length() > 0) + { + foreignKeyRefsForTable.append(", "); + } + foreignKeyRefsForTable.append("\"" + columns[i].getForeignColumn() + "\""); + foreignKeyRefs.put(foreignTable, foreignKeyRefsForTable.toString()); + } + } + + if (primaryKeyList.length() > 0) + { + createStatement.append(", PRIMARY KEY ("); + createStatement.append(primaryKeyList); + createStatement.append(')'); + } + + final Set foreignKeyTables = foreignKeys.keySet(); + for (final Iterator foreignKey = foreignKeyTables.iterator(); + foreignKey.hasNext();) + { + final String foreignTable = (String) foreignKey.next(); + + createStatement.append(", FOREIGN KEY ("); + createStatement.append((String) foreignKeys.get(foreignTable)); + createStatement.append(") REFERENCES \""); + createStatement.append(foreignTable); + createStatement.append("\"("); + createStatement.append((String) foreignKeyRefs.get(foreignTable)); + createStatement.append(')'); + } + + createStatement.append(')'); + + //System.err.println( createStatement ); + executeSQL(createStatement.toString()); + } + + /** creates a table in the database. using the SDBCX-API + */ + public void createTableInSDBCX(final HsqlTableDescriptor _tableDesc) throws SQLException, ElementExistException + { + final XPropertySet sdbcxDescriptor = _tableDesc.createSdbcxDescriptor(defaultConnection()); + final XTablesSupplier suppTables = UnoRuntime.queryInterface( XTablesSupplier.class, defaultConnection().getXConnection() ); + final XAppend appendTable = UnoRuntime.queryInterface( XAppend.class, suppTables.getTables() ); + appendTable.appendByDescriptor(sdbcxDescriptor); + } +} Index: source/testcase/uno/db/utils/QueryDefinition.java =================================================================== --- source/testcase/uno/db/utils/QueryDefinition.java (revision 0) +++ source/testcase/uno/db/utils/QueryDefinition.java (revision 0) @@ -0,0 +1,71 @@ +/************************************************************** + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + *************************************************************/ + + + +package testcase.uno.db.utils; + + +import com.sun.star.beans.PropertyVetoException; +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.beans.XPropertySet; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.lang.IllegalArgumentException; + +public class QueryDefinition +{ + XPropertySet m_queryDef; + + public QueryDefinition( XPropertySet _queryDef ) + { + m_queryDef = _queryDef; + } + + /** retrieves the command underlying the query definition + * + * This method is a mere wrapped around the getPropertyValue( "Command" ) call + */ + public final String getCommand() throws WrappedTargetException + { + String command = null; + try { + command = (String)m_queryDef.getPropertyValue( "Command" ); + } + catch (UnknownPropertyException e) { } + + return command; + } + + /** retrieves the command underlying the query definition + * + * This method is a mere wrapped around the getPropertyValue( "Command" ) call + */ + public void setCommand( String _command ) throws WrappedTargetException + { + try + { + m_queryDef.setPropertyValue( "Command", _command ); + } + catch (UnknownPropertyException e) { } + catch (PropertyVetoException e) { } + catch (IllegalArgumentException e) { } + } +}; Index: source/testcase/uno/db/utils/AbstractDatabase.java =================================================================== --- source/testcase/uno/db/utils/AbstractDatabase.java (revision 0) +++ source/testcase/uno/db/utils/AbstractDatabase.java (revision 0) @@ -0,0 +1,212 @@ +/************************************************************** + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + *************************************************************/ + + +package testcase.uno.db.utils; + +import com.sun.star.container.XNameAccess; +import com.sun.star.frame.XModel; +import com.sun.star.frame.XStorable; +import com.sun.star.io.IOException; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.sdb.XDocumentDataSource; +import com.sun.star.sdb.XOfficeDatabaseDocument; +import com.sun.star.sdbc.SQLException; +import com.sun.star.sdbc.XCloseable; +import com.sun.star.sdbc.XStatement; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.util.CloseVetoException; +import java.io.File; + + +public abstract class AbstractDatabase +{ + public AbstractDatabase(final XMultiServiceFactory orb) throws Exception + { + m_orb = orb; + } + + // -------------------------------------------------------------------------------------------------------- + public AbstractDatabase(final XMultiServiceFactory orb, final String _existingDocumentURL ) throws Exception + { + m_orb = orb; + createDBDocument( _existingDocumentURL ); + } + + /** returns a connection to the database + * + * Multiple calls to this method return the same connection. The DbaseDatabase object keeps + * the ownership of the connection, so you don't need to (and should not) dispose/close it. + */ + public Connection defaultConnection() throws SQLException + { + if ( m_connection == null ) + m_connection = new Connection( m_databaseDocument.getDataSource().getConnection("", "") ); + + return m_connection; + } + + /** executes the given SQL statement via the defaultConnection + */ + public void executeSQL(final String statementString) throws SQLException + { + final XStatement statement = defaultConnection().createStatement(); + statement.execute(statementString); + } + + /** stores the database document + */ + public void store() throws IOException + { + if (m_databaseDocument != null) + { + final XStorable storeDoc = 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 + final XCloseable closeConn = UnoRuntime.queryInterface( XCloseable.class, + m_connection != null ? m_connection.getXConnection() : null ); + if (closeConn != null) + { + try + { + closeConn.close(); + } + catch (SQLException e) + { + } + } + m_connection = null; + + // close document + final com.sun.star.util.XCloseable closeDoc = 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 + { + final File file = new File(m_databaseDocumentFile); + file.delete(); + } + catch (Exception e) + { + } + } + } + + /** returns the underlying database document + */ + public XOfficeDatabaseDocument getDatabaseDocument() + { + return m_databaseDocument; + } + + /** returns the model interface of the underlying database document + */ + public XModel getModel() + { + return UnoRuntime.queryInterface( XModel.class, m_databaseDocument ); + } + + public XMultiServiceFactory getORB() + { + return m_orb; + } + + // -------------------------------------------------------------------------------------------------------- + final protected void createDBDocument(final String _docURL) throws Exception + { + m_databaseDocumentFile = _docURL; + + final XNameAccess dbContext = UnoRuntime.queryInterface( XNameAccess.class, + m_orb.createInstance( "com.sun.star.sdb.DatabaseContext" ) ); + final XDocumentDataSource dataSource = UnoRuntime.queryInterface( XDocumentDataSource.class, dbContext.getByName( _docURL ) ); + + m_databaseDocument = dataSource.getDatabaseDocument(); + m_dataSource = new DataSource(m_orb, m_databaseDocument.getDataSource()); + } + + /** returns the URL of the ODB document represented by this instance + */ + public String getDocumentURL() + { + return m_databaseDocumentFile; + } + + /** returns the data source belonging to this database + */ + public DataSource getDataSource() + { + return m_dataSource; + } + + /** creates a row set operating the database, with a given command/type + */ + public RowSet createRowSet(final int _commandType, final String _command) + { + return new RowSet(m_orb, getDocumentURL(), _commandType, _command); + } + + @Override + protected void finalize() throws Throwable + { + closeAndDelete(); + super.finalize(); + } + + // the service factory + protected final XMultiServiceFactory m_orb; + // the URL of the temporary file used for the database document + protected String m_databaseDocumentFile; + // the database document + protected XOfficeDatabaseDocument m_databaseDocument; + // the data source belonging to the database document + protected DataSource m_dataSource; + // the default connection + protected Connection m_connection; +} Index: source/testcase/uno/db/utils/URLHelper.java =================================================================== --- source/testcase/uno/db/utils/URLHelper.java (revision 0) +++ source/testcase/uno/db/utils/URLHelper.java (revision 0) @@ -0,0 +1,288 @@ +/************************************************************** + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + *************************************************************/ + + + +package testcase.uno.db.utils; + +// __________ Imports __________ + +// exceptions +import java.net.MalformedURLException; + +// interfaces +import com.sun.star.util.XURLTransformer; + +// others +import java.io.File; +import java.util.Vector; +import java.util.Enumeration; + + +/** + * It collects some static helper functons to handle URLs. + * Sometimes it's neccessary to convert URL from/to system pathes. + * Or from string to strutural notations (e.g. com.sun.star.util.URL). + * And sometimes java had another notation then the office it has. + * + */ +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 + */ + public static String getFileURLFromSystemPath( File aSystemPath ) + { + String sFileURL = null; + try + { + //sFileURL = aSystemPath.toURI().toURL().toString(); + 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; + } + + // ____________________ + + /** + * The same as getFileURLFromSystemPath() before but uses string parameter instead + * of a File type. It exist to supress converting of neccessary parameters in the + * outside code. But of course getFileURLFromSystemPath(File) will be a little bit faster + * then this method ... + * + * @param sSystemPath + * represent the file in system notation + * + * @return [String] + * a file url which represent the given system path + */ + public static String getFileURLFromSystemPath( String sSystemPath ) + { + return getFileURLFromSystemPath(new File(sSystemPath)); + } + + // ____________________ + + /** + * Does the same as getFileURLFromSystemPath() before ... but uses + * the given protocol string (e.g."http://") insted of "file:///". + * + * @param aSystemPath + * represent the file in system notation + * + * @param aBasePath + * define the base path of the aSystemPath value, + * which must be replaced with the value of "sServerPath". + * + * @param sServerURL + * Will be used to replace sBasePath. + * + * @example + * System Path = "d:\test\file.txt" + * Base Path = "d:\test" + * Server Path = "http://alaska:8000" + * => "http://alaska:8000/file.txt" + * + * @return [String] + * an url which represent the given system path + * and uses the given protocol + */ + public static String getURLWithProtocolFromSystemPath( File aSystemPath, File aBasePath, String sServerURL ) + { + String sFileURL = URLHelper.getFileURLFromSystemPath(aSystemPath); + String sBaseURL = URLHelper.getFileURLFromSystemPath(aBasePath ); + + // cut last '/'! + if (sBaseURL.lastIndexOf('/')==(sBaseURL.length()-1)) + sBaseURL = sBaseURL.substring(0,sBaseURL.length()-1); + + // cut last '/'! + if (sServerURL.lastIndexOf('/')==(sServerURL.length()-1)) + sServerURL = sServerURL.substring(0,sServerURL.length()-1); + + int index = sFileURL.indexOf(sBaseURL); + String sURL = sFileURL.substring(0,index) + sServerURL + + sFileURL.substring(index+sBaseURL.length()); + //String sURL = sFileURL.replaceFirst(sBaseURL,sServerURL); + return sURL; + } + + // ____________________ + + /** + * The same as getURLWithProtocolFromSystemPath() before but uses string parameter instead + * of a File types. It exist to supress converting of neccessary parameters in the + * outside code. But of course getURLWithProtocolFromSystemPath(File,File,String) will be + * a little bit faster then this method ... + * + * @param sSystemPath + * represent the file in system notation + * + * @param sBasePath + * define the base path of the aSystemPath value, + * which must be replaced with the value of "sServerPath". + * + * @param sServerPath + * Will be used to replace sBasePath. + * + * @example + * System Path = "d:\test\file.txt" + * Base Path = "d:\test" + * Server Path = "http://alaska:8000" + * => "http://alaska:8000/file.txt" + * + * @return [String] + * an url which represent the given system path + * and uses the given protocol + */ + public static String getURLWithProtocolFromSystemPath( String sSystemPath, String sBasePath, String sServerPath ) + { + return getURLWithProtocolFromSystemPath(new File(sSystemPath), new File(sBasePath), sServerPath); + } + + // ____________________ + + /** + * This convert an URL (formated as a string) to a struct com.sun.star.util.URL. + * It use a special service to do that: the URLTransformer. + * Because some API calls need it and it's not allowed to set "Complete" + * part of the util struct only. The URL must be parsed. + * + * @param sURL + * URL for parsing in string notation + * + * @return [com.sun.star.util.URL] + * URL in UNO struct notation + */ + public static com.sun.star.util.URL parseURL(XURLTransformer xParser, String sURL) + { + com.sun.star.util.URL aURL = null; + + if (sURL==null || sURL.equals("")) + return null; + + try + { + // Create special service for parsing of given URL. +/* com.sun.star.util.XURLTransformer xParser = (com.sun.star.util.XURLTransformer)OfficeConnect.createRemoteInstance( + com.sun.star.util.XURLTransformer.class, + "com.sun.star.util.URLTransformer"); +*/ + // Because it's an in/out parameter we must use an array of URL objects. + com.sun.star.util.URL[] aParseURL = new com.sun.star.util.URL[1]; + aParseURL[0] = new com.sun.star.util.URL(); + aParseURL[0].Complete = sURL; + + // Parse the URL + xParser.parseStrict(aParseURL); + + aURL = aParseURL[0]; + } + catch(com.sun.star.uno.RuntimeException exRuntime) + { + // Any UNO method of this scope can throw this exception. + // Reset the return value only. + aURL = null; + } + + return aURL; + } + + //_________________________________ + /** + * Return a name list of all available files of a directory. + * We filter pure sub directories names. All other files + * are returned as full qualified URL strings. So they can be + * used for further purposes. One parameter define the start directory, + * another one describe the url protocol, which the return URL names should have. + * + * @param sDir + * the start directory, which should include all test files + * + * @return [Vector] + * a filtered list of java File objects of all available files of the start dir + * and all accessable sub directories. + */ + public static Vector getSystemFilesFromDir(String sStartDir) + { + File aRoot = new File(sStartDir); + + if (! aRoot.exists()) + return null; + + if (! aRoot.isDirectory()) + return null; + + File[] lAllFiles = aRoot.listFiles(); + if (lAllFiles == null ) + return null; + + Vector lFilteredFiles = new Vector(lAllFiles.length); + + for (int i=0; i