diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 09:06:44 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 09:06:44 +0000 |
commit | ed5640d8b587fbcfed7dd7967f3de04b37a76f26 (patch) | |
tree | 7a5f7c6c9d02226d7471cb3cc8fbbf631b415303 /qadevOOo/runner/util | |
parent | Initial commit. (diff) | |
download | libreoffice-upstream.tar.xz libreoffice-upstream.zip |
Adding upstream version 4:7.4.7.upstream/4%7.4.7upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'qadevOOo/runner/util')
36 files changed, 7862 insertions, 0 deletions
diff --git a/qadevOOo/runner/util/AccessibilityTools.java b/qadevOOo/runner/util/AccessibilityTools.java new file mode 100644 index 000000000..4426af496 --- /dev/null +++ b/qadevOOo/runner/util/AccessibilityTools.java @@ -0,0 +1,383 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ +package util; + +import com.sun.star.accessibility.XAccessible; +import com.sun.star.accessibility.XAccessibleComponent; +import com.sun.star.accessibility.XAccessibleContext; +import com.sun.star.awt.XWindow; +import com.sun.star.frame.XController; +import com.sun.star.frame.XFrame; +import com.sun.star.frame.XModel; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XInterface; + +import java.io.PrintWriter; + + +public class AccessibilityTools { + public static XAccessible SearchedAccessible = null; + private static boolean debug = false; + + private AccessibilityTools() {} + + public static XAccessible getAccessibleObject(XInterface xObject) { + return UnoRuntime.queryInterface(XAccessible.class, xObject); + } + + public static XWindow getCurrentContainerWindow(XModel xModel) { + return getWindow(xModel, true); + } + + public static XWindow getCurrentWindow(XModel xModel) { + return getWindow(xModel, false); + } + + private static XWindow getWindow(XModel xModel, + boolean containerWindow) { + XWindow xWindow = null; + + try { + XController xController = xModel.getCurrentController(); + XFrame xFrame = xController.getFrame(); + + if (xFrame == null) { + System.out.println("can't get frame from controller"); + } else { + if (containerWindow) + xWindow = xFrame.getContainerWindow(); + else + xWindow = xFrame.getComponentWindow(); + } + + if (xWindow == null) { + System.out.println("can't get window from frame"); + } + } catch (Exception e) { + System.out.println("caught exception while getting current window" + e); + } + + return xWindow; + } + + public static XAccessibleContext getAccessibleObjectForRole(XAccessible xacc, + short role) { + SearchedAccessible = null; + return getAccessibleObjectForRole_(xacc, role); + } + + public static XAccessibleContext getAccessibleObjectForRole(XAccessible xacc, + short role, + boolean ignoreShowing) { + SearchedAccessible = null; + + if (ignoreShowing) { + return getAccessibleObjectForRoleIgnoreShowing_(xacc, role); + } else { + return getAccessibleObjectForRole_(xacc, role); + } + } + + private static XAccessibleContext getAccessibleObjectForRoleIgnoreShowing_(XAccessible xacc, + short role) { + XAccessibleContext ac = xacc.getAccessibleContext(); + if (ac == null) { + return null; + } + if (ac.getAccessibleRole() == role) { + SearchedAccessible = xacc; + return ac; + } else { + int k = ac.getAccessibleChildCount(); + + if (ac.getAccessibleChildCount() > 100) { + k = 50; + } + + for (int i = 0; i < k; i++) { + try { + XAccessibleContext ac2 = getAccessibleObjectForRoleIgnoreShowing_( + ac.getAccessibleChild(i), role); + + if (ac2 != null) { + return ac2; + } + } catch (com.sun.star.lang.IndexOutOfBoundsException e) { + System.out.println("Couldn't get Child"); + } + } + return null; + } + } + + private static XAccessibleContext getAccessibleObjectForRole_(XAccessible xacc, + short role) { + XAccessibleContext ac = xacc.getAccessibleContext(); + boolean isShowing = ac.getAccessibleStateSet() + .contains(com.sun.star.accessibility.AccessibleStateType.SHOWING); + + if ((ac.getAccessibleRole() == role) && isShowing) { + SearchedAccessible = xacc; + return ac; + } else { + int k = ac.getAccessibleChildCount(); + + if (ac.getAccessibleChildCount() > 100) { + k = 50; + } + + for (int i = 0; i < k; i++) { + try { + XAccessibleContext ac2 = getAccessibleObjectForRole_(ac.getAccessibleChild(i), role); + + if (ac2 != null) { + return ac2; + } + } catch (com.sun.star.lang.IndexOutOfBoundsException e) { + System.out.println("Couldn't get Child"); + } + } + return null; + } + } + + public static XAccessibleContext getAccessibleObjectForRole(XAccessible xacc, + short role, + String name) { + return getAccessibleObjectForRole(xacc, role, name, ""); + } + + public static XAccessibleContext getAccessibleObjectForRole(XAccessible xacc, + short role, + String name, + boolean ignoreShowing) { + if (ignoreShowing) { + return getAccessibleObjectForRoleIgnoreShowing(xacc, role, name, + ""); + } else { + return getAccessibleObjectForRole(xacc, role, name, ""); + } + } + + public static XAccessibleContext getAccessibleObjectForRoleIgnoreShowing(XAccessible xacc, + short role, + String name, + String implName) { + XAccessibleContext ac = xacc.getAccessibleContext(); + if ((ac.getAccessibleRole() == role) && + (ac.getAccessibleName().indexOf(name) > -1) && + (utils.getImplName(ac).indexOf(implName) > -1)) { + SearchedAccessible = xacc; + + return ac; + } else { + int k = ac.getAccessibleChildCount(); + + if (ac.getAccessibleChildCount() > 100) { + k = 50; + } + + for (int i = 0; i < k; i++) { + try { + XAccessibleContext ac1 = getAccessibleObjectForRoleIgnoreShowing( + ac.getAccessibleChild(i), + role, name, implName); + + if (ac1 != null) { + return ac1; + } + } catch (com.sun.star.lang.IndexOutOfBoundsException e) { + System.out.println("Couldn't get Child"); + } + } + } + + return null; + } + + public static XAccessibleContext getAccessibleObjectForRole(XAccessible xacc, + short role, + String name, + String implName) { + XAccessibleContext ac = xacc.getAccessibleContext(); + boolean isShowing = ac.getAccessibleStateSet() + .contains(com.sun.star.accessibility.AccessibleStateType.SHOWING); + + // hotfix for i91828: + // if role to search is 0 then ignore the role. + if ( (role == 0 || ac.getAccessibleRole() == role) && + (ac.getAccessibleName().indexOf(name) > -1) && + (utils.getImplName(ac).indexOf(implName) > -1) && + isShowing) { + SearchedAccessible = xacc; + return ac; + } else { + int k = ac.getAccessibleChildCount(); + + if (ac.getAccessibleChildCount() > 100) { + k = 50; + } + + for (int i = 0; i < k; i++) { + try { + XAccessibleContext ac1 = getAccessibleObjectForRole( + ac.getAccessibleChild(i), + role, name, implName); + + if (ac1 != null) { + return ac1; + } + } catch (com.sun.star.lang.IndexOutOfBoundsException e) { + System.out.println("Couldn't get Child"); + } + } + } + + return null; + } + + public static void printAccessibleTree(PrintWriter log, XAccessible xacc, boolean debugIsActive) { + debug = debugIsActive; + if (debug) printAccessibleTree(log, xacc, ""); + } + + public static void printAccessibleTree(PrintWriter log, XAccessible xacc) { + printAccessibleTree(log, xacc, ""); + } + + private static void printAccessibleTree(PrintWriter log, + XAccessible xacc, String indent) { + + XAccessibleContext ac = xacc.getAccessibleContext(); + + logging(log,indent + ac.getAccessibleRole() + "," + + ac.getAccessibleName() + "(" + + ac.getAccessibleDescription() + "):" + + utils.getImplName(ac)); + + XAccessibleComponent aComp = UnoRuntime.queryInterface( + XAccessibleComponent.class, xacc); + + if (aComp != null) { + String bounds = "(" + aComp.getBounds().X + "," + + aComp.getBounds().Y + ")" + " (" + + aComp.getBounds().Width + "," + + aComp.getBounds().Height + ")"; + bounds = "The boundary Rectangle is " + bounds; + logging(log,indent + indent + bounds); + } + + boolean isShowing = ac.getAccessibleStateSet() + .contains(com.sun.star.accessibility.AccessibleStateType.SHOWING); + logging(log,indent + indent + "StateType contains SHOWING: " + + isShowing); + + int k = ac.getAccessibleChildCount(); + + if (ac.getAccessibleChildCount() > 100) { + k = 50; + } + + for (int i = 0; i < k; i++) { + try { + printAccessibleTree(log, ac.getAccessibleChild(i), + indent + " "); + } catch (com.sun.star.lang.IndexOutOfBoundsException e) { + System.out.println("Couldn't get Child"); + } + } + + if (ac.getAccessibleChildCount() > 100) { + k = ac.getAccessibleChildCount(); + + int st = ac.getAccessibleChildCount() - 50; + logging(log,indent + " " + " ...... [skipped] ......"); + + for (int i = st; i < k; i++) { + try { + printAccessibleTree(log, ac.getAccessibleChild(i), + indent + " "); + } catch (com.sun.star.lang.IndexOutOfBoundsException e) { + System.out.println("Couldn't get Child"); + } + } + } + } + + public static String accessibleToString(Object AC) { + XAccessibleContext xAC = UnoRuntime.queryInterface( + XAccessibleContext.class, AC); + + if (xAC != null) { + return xAC.getAccessibleRole() + "," + + xAC.getAccessibleName() + "(" + + xAC.getAccessibleDescription() + "):"; + } + + XAccessible xA = UnoRuntime.queryInterface( + XAccessible.class, AC); + + if (xA == null) { + return "(Not supported)"; + } + + xAC = xA.getAccessibleContext(); + + return xAC.getAccessibleRole() + "," + xAC.getAccessibleName() + + "(" + xAC.getAccessibleDescription() + ")"; + } + + public static boolean equals(XAccessible c1, XAccessible c2) { + if ((c1 == null) || (c2 == null)) { + return c1 == c2; + } + + return AccessibilityTools.equals(c1.getAccessibleContext(), + c2.getAccessibleContext()); + } + + public static boolean equals(XAccessibleContext c1, XAccessibleContext c2) { + if ((c1 == null) || (c2 == null)) { + return c1 == c2; + } + + if (c1.getAccessibleRole() != c2.getAccessibleRole()) { + return false; + } + + if (!c1.getAccessibleName().equals(c2.getAccessibleName())) { + return false; + } + + if (!c1.getAccessibleDescription() + .equals(c2.getAccessibleDescription())) { + return false; + } + + if (c1.getAccessibleChildCount() != c2.getAccessibleChildCount()) { + return false; + } + + return AccessibilityTools.equals(c1.getAccessibleParent(), + c2.getAccessibleParent()); + } + + private static void logging(PrintWriter log, String content){ + if (debug) log.println(content); + } +} diff --git a/qadevOOo/runner/util/BookmarkDsc.java b/qadevOOo/runner/util/BookmarkDsc.java new file mode 100644 index 000000000..02736c9ba --- /dev/null +++ b/qadevOOo/runner/util/BookmarkDsc.java @@ -0,0 +1,73 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ + +package util; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.uno.XInterface; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.text.XTextContent; + +/** + * describes a Bookmark to be inserted in a container + */ +public class BookmarkDsc extends InstDescr { + + private static final String service = "com.sun.star.text.Bookmark"; + private static final String ifcName = "com.sun.star.text.XTextContent"; + + + public BookmarkDsc() { + initBookmark(); + } + + @Override + public String getName() { + return null; + } + + @Override + public String getIfcName() { + return ifcName; + } + + @Override + public String getService() { + return service; + } + + private void initBookmark() { + try { + ifcClass = Class.forName( ifcName ); + } + catch( ClassNotFoundException cnfE ) { + } + } + @Override + public XInterface createInstance( XMultiServiceFactory docMSF ) { + Object ServiceObj = null; + + try { + ServiceObj = docMSF.createInstance( service ); + } + catch( com.sun.star.uno.Exception cssuE ){ + } + XTextContent BM = (XTextContent)UnoRuntime.queryInterface( ifcClass, + ServiceObj ); + return BM; + } +} diff --git a/qadevOOo/runner/util/CalcTools.java b/qadevOOo/runner/util/CalcTools.java new file mode 100644 index 000000000..e9a84cdbc --- /dev/null +++ b/qadevOOo/runner/util/CalcTools.java @@ -0,0 +1,127 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ + +package util; + +import com.sun.star.container.XIndexAccess; +import com.sun.star.lang.IllegalArgumentException; +import com.sun.star.lang.IndexOutOfBoundsException; +import com.sun.star.lang.WrappedTargetException; +import com.sun.star.lang.XComponent; +import com.sun.star.sheet.XCellRangeData; +import com.sun.star.sheet.XSpreadsheet; +import com.sun.star.sheet.XSpreadsheetDocument; +import com.sun.star.sheet.XSpreadsheets; +import com.sun.star.table.XCellRange; +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.Exception; +import com.sun.star.uno.Type; +import com.sun.star.uno.UnoRuntime; + +/** + * This class contains some useful methods to handle Calc documents + * and its sheets. + */ +public class CalcTools { + + /** + * fills a range of a calc sheet with computed data of type + * <CODE>Double</CODE>. + * @param xSheetDoc the Calc documents which should be filled + * @param sheetNumber the number of the sheet of <CODE>xSheetDoc</CODE> + * @param startCellX the cell number of the X start point (row) of the range to fill + * @param startCellY the cell number of the Y start point (column) of the range to fill + * @param rangeLengthX the size of the range expansion in X-direction + * @param rangeLengthY the size of the range expansion in Y-direction + * @throws java.lang.Exception on any error an <CODE>java.lang.Exception</CODE> was thrown + */ + public static void fillCalcSheetWithContent(XComponent xSheetDoc, int sheetNumber, + int startCellX, int startCellY, int rangeLengthX, int rangeLengthY) + throws java.lang.Exception { + XSpreadsheet xSheet = getSpreadSheetFromSheetDoc(xSheetDoc, sheetNumber); + + fillCalcSheetWithContent(xSheet, startCellX, startCellY, rangeLengthX, rangeLengthY); + } + + /** + * fills a range of a calc sheet with computed data of type + * <CODE>Double</CODE>. + * @param xSheet the sheet to fill with content + * @param startCellX the cell number of the X start point (row) of the range to fill + * @param startCellY the cell number of the Y start point (column) of the range to fill + * @param rangeLengthX the size of the range expansion in X-direction + * @param rangeLengthY the size of the range expansion in Y-direction + * @throws java.lang.Exception on any error an <CODE>java.lang.Exception</CODE> was thrown + */ + public static void fillCalcSheetWithContent(XSpreadsheet xSheet, + int startCellX, int startCellY, int rangeLengthX, int rangeLengthY) + throws java.lang.Exception { + // create a range with content + Object[][] newData = new Object[rangeLengthY][rangeLengthX]; + for (int i=0; i<rangeLengthY; i++) { + for (int j=0; j<rangeLengthX; j++) { + newData[i][j] = new Double(10*i +j); + } + } + XCellRange xRange = null; + try { + xRange = xSheet.getCellRangeByPosition(startCellX, startCellY, + startCellX+rangeLengthX-1, startCellY+rangeLengthY-1); + } catch ( IndexOutOfBoundsException ex){ + throw new Exception(ex, "Couldn't get CellRange from sheet"); + } + + XCellRangeData xRangeData = UnoRuntime.queryInterface(XCellRangeData.class, xRange); + + xRangeData.setDataArray(newData); + } + + /** + * + * returns an <CODE>XSpreadsheet</CODE> from a Calc document. + * @param xSheetDoc the Calc document which contains the sheet + * @param sheetNumber the number of the sheet to return + * @throws java.lang.Exception on any error an <CODE>java.lang.Exception</CODE> was thrown + * @return calc sheet + * @see com.sun.star.sheet.XSpreadsheet + */ + private static XSpreadsheet getSpreadSheetFromSheetDoc(XComponent xSheetDoc, int sheetNumber) + throws java.lang.Exception { + + XSpreadsheet xSheet = null; + + try{ + XSpreadsheetDocument xSpreadsheetDoc = UnoRuntime.queryInterface(XSpreadsheetDocument.class, xSheetDoc); + + XSpreadsheets xSpreadsheets = xSpreadsheetDoc.getSheets(); + + XIndexAccess xSheetsIndexArray = UnoRuntime.queryInterface(XIndexAccess.class, xSpreadsheets); + + xSheet = (XSpreadsheet) AnyConverter.toObject( + new Type(XSpreadsheet.class),xSheetsIndexArray.getByIndex(sheetNumber)); + + } catch (IllegalArgumentException ex){ + throw new Exception(ex, "Couldn't get sheet '" +sheetNumber + "'"); + } catch (IndexOutOfBoundsException ex){ + throw new Exception(ex, "Couldn't get sheet '" +sheetNumber + "'"); + } catch (WrappedTargetException ex) { + throw new Exception(ex, "Couldn't get sheet '" +sheetNumber + "'"); + } + return xSheet; + } +} diff --git a/qadevOOo/runner/util/DBTools.java b/qadevOOo/runner/util/DBTools.java new file mode 100644 index 000000000..387ba57e8 --- /dev/null +++ b/qadevOOo/runner/util/DBTools.java @@ -0,0 +1,409 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ + +package util; + +import com.sun.star.uno.Exception; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.uno.UnoRuntime; + +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XPropertySet; +import com.sun.star.sdbc.XConnection ; +import com.sun.star.util.Date ; +import com.sun.star.uno.XNamingService ; +import com.sun.star.task.XInteractionHandler ; +import com.sun.star.sdb.XCompletedConnection ; +import com.sun.star.frame.XStorable; +import com.sun.star.sdb.XDocumentDataSource; +import java.sql.Statement; +import java.sql.Connection; +import java.sql.DriverManager; + +/** +* Provides useful methods for working with SOffice databases. +* Database creation, data transferring, outputting information. +*/ +public class DBTools { + + private final XMultiServiceFactory xMSF; + private XNamingService dbContext; + //JDBC driver + public static final String TST_JDBC_DRIVER = "org.gjt.mm.mysql.Driver"; + + // constants for TestDB table column indexes + public static final int TST_STRING = 1 ; + public static final int TST_INT = 2 ; + private static final int TST_DOUBLE = 5 ; + private static final int TST_DATE = 6 ; + private static final int TST_BOOLEAN = 10 ; + private static final int TST_CHARACTER_STREAM = 11 ; + private static final int TST_BINARY_STREAM = 12 ; + + // constants for TestDB columns names + public static final String TST_STRING_F = "_TEXT" ; + public static final String TST_INT_F = "_INT" ; + public static final String TST_DOUBLE_F = "_DOUBLE" ; + public static final String TST_DATE_F = "_DATE" ; + private static final String TST_BOOLEAN_F = "_BOOL" ; + private static final String TST_CHARACTER_STREAM_F = "_MEMO1" ; + public static final String TST_BINARY_STREAM_F = "_MEMO2" ; + + /** + * Values for filling test table. + */ + public static final Object[][] TST_TABLE_VALUES = new Object[][] { + {"String1", Integer.valueOf(1), null, null, new Double(1.1), + new Date((short) 1,(short) 1, (short) 2001), null, null, null, + Boolean.TRUE, null, null}, + {"String2", Integer.valueOf(2), null, null, new Double(1.2), + new Date((short) 2, (short) 1,(short) 2001), null, null, null, + Boolean.FALSE, null, null}, + {null, null, null, null, null, + null, null, null, null, + null, null, null} + } ; + + /** + * It's just a structure with some useful methods for representing + * <code>com.sun.star.sdb.DataSource</code> service. All this + * service's properties are stored in appropriate class fields. + * Class also allows to construct its instances using service + * information, and create new service instance upon class + * fields. + * @see com.sun.star.sdb.DataSource + */ + public class DataSourceInfo { + /** + * Representation of <code>'Name'</code> property. + */ + public String Name = null ; + /** + * Representation of <code>'URL'</code> property. + */ + public String URL = null ; + /** + * Representation of <code>'Info'</code> property. + */ + public PropertyValue[] Info = null ; + /** + * Representation of <code>'User'</code> property. + */ + public String User = null ; + /** + * Representation of <code>'Password'</code> property. + */ + public String Password = null ; + /** + * Representation of <code>'IsPasswordRequired'</code> property. + */ + public Boolean IsPasswordRequired = null ; + + /** + * Creates new <code>com.sun.star.sdb.DataSource</code> service + * instance and copies all fields (which are not null) to + * appropriate service properties. + * @return <code>com.sun.star.sdb.DataSource</code> service. + */ + public Object getDataSourceService() throws Exception + { + Object src = xMSF.createInstance("com.sun.star.sdb.DataSource") ; + + XPropertySet props = UnoRuntime.queryInterface + (XPropertySet.class, src) ; + + if (Name != null) props.setPropertyValue("Name", Name) ; + if (URL != null) props.setPropertyValue("URL", URL) ; + if (Info != null) props.setPropertyValue("Info", Info) ; + if (User != null) props.setPropertyValue("User", User) ; + if (Password != null) props.setPropertyValue("Password", Password) ; + if (IsPasswordRequired != null) props.setPropertyValue("IsPasswordRequired", IsPasswordRequired) ; + return src ; + } + } + + /** + * Creates class instance. + * @param xMSF <code>XMultiServiceFactory</code>. + */ + public DBTools(XMultiServiceFactory xMSF ) + { + this.xMSF = xMSF ; + try { + Object cont = xMSF.createInstance("com.sun.star.sdb.DatabaseContext") ; + + dbContext = UnoRuntime.queryInterface + (XNamingService.class, cont) ; + + } catch (com.sun.star.uno.Exception e) { + System.out.println("caught exception: " + e); + } + } + + /** + * Returns new instance of <code>DataSourceInfo</code> class. + */ + public DataSourceInfo newDataSourceInfo() { return new DataSourceInfo() ;} + + + + /** + * Registers the datasource on the specified name in + * <code>DatabaseContext</code> service. + * @param name Name which dataSource will have in global context. + * @param dataSource <code>DataSource</code> object which is to + * be registered. + */ + private void registerDB(String name, Object dataSource) + throws com.sun.star.uno.Exception { + + dbContext.registerObject(name, dataSource) ; + } + + + /** + * First tries to revoke the datasource with the specified + * name and then registers a new one. + * @param name Name which dataSource will have in global context. + * @param dataSource <code>DataSource</code> object which is to + * be registered. + */ + public void reRegisterDB(String name, Object dataSource) + throws com.sun.star.uno.Exception { + + try { + revokeDB(name) ; + } catch (com.sun.star.uno.Exception e) {} + + XDocumentDataSource xDDS = UnoRuntime.queryInterface(XDocumentDataSource.class, dataSource); + XStorable store = UnoRuntime.queryInterface(XStorable.class, + xDDS.getDatabaseDocument()); + String aFile = utils.getOfficeTemp(xMSF) + name + ".odb"; + store.storeAsURL(aFile, new PropertyValue[] { }); + + registerDB(name, dataSource) ; + } + + + + + + /** + * Performs connection to DataSource specified. + * @param dbSource <code>com.sun.star.sdb.DataSource</code> service + * specified data source which must be already registered in the + * <code>DatabaseContext</code> service. + * @return Connection to the data source. + */ + public XConnection connectToSource(Object dbSource) + throws com.sun.star.uno.Exception { + + Object handler = xMSF.createInstance("com.sun.star.sdb.InteractionHandler"); + XInteractionHandler xHandler = UnoRuntime.queryInterface(XInteractionHandler.class, handler) ; + + XCompletedConnection xSrcCon = UnoRuntime.queryInterface(XCompletedConnection.class, dbSource) ; + + return xSrcCon.connectWithCompletion(xHandler) ; + } + + /** + * Convert system pathname to SOffice URL string + * (for example 'C:\Temp\DBDir\' -> 'file:///C|/Temp/DBDir/'). + * (for example '\\server\Temp\DBDir\' -> 'file://server/Temp/DBDir/'). + * Already converted string returned unchanged. + */ + public static String dirToUrl(String dir) { + String retVal = null; + if (dir.startsWith("file:/")) retVal = dir; + else { + retVal = dir.replace(':', '|').replace('\\', '/'); + + if (dir.startsWith("\\\\")) { + retVal = "file:" + retVal; + } + + else retVal = "file:///" + retVal ; + } + return retVal; + } + + /** + * Revokes datasource from global DB context. + * @param name DataSource name to be revoked. + */ + public void revokeDB(String name) throws com.sun.star.uno.Exception + { + dbContext.revokeObject(name) ; + } + + /** + * Initializes test table specified of the connection specified + * using JDBC driver. Drops table with the name <code>tbl_name</code>, + * creates new table with this name and then inserts data from + * <code>TST_TABLE_VALUES</code> constant array. <p> + * Test table has some predefined format which includes as much + * field types as possible. For every column type constants + * {@link #TST_STRING TST_STRING}, {@link #TST_INT TST_INT}, etc. + * are declared for column index fast find. + * @param tbl_name Test table name. + */ + public void initTestTableUsingJDBC(String tbl_name, DataSourceInfo dsi) + throws java.sql.SQLException, + ClassNotFoundException { + + //register jdbc driver + if ( dsi.Info[0].Name.equals("JavaDriverClass") ) { + Class.forName((String)dsi.Info[0].Value); + } else { + Class.forName(TST_JDBC_DRIVER); + } + + Connection connection = null; + Statement statement = null; + try { + //getting connection + connection = DriverManager.getConnection(dsi.URL, dsi.User, dsi.Password); + try { + statement = connection.createStatement(); + + //drop table + dropMySQLTable(statement, tbl_name); + + //create table + createMySQLTable(statement, tbl_name); + + //insert some content + insertContentMySQLTable(statement, tbl_name); + } finally { + if (statement != null) + statement.close(); + } + } finally { + if (connection != null) + connection.close(); + } + } + + /** + * Inserts data from <code>TST_TABLE_VALUES</code> constant array + * to test table <code>tbl_name</code>. + * @param statement object used for executing a static SQL + * statement and obtaining the results produced by it. + * @param tbl_name Test table name. + */ + private void insertContentMySQLTable(Statement statement, String tbl_name) + throws java.sql.SQLException { + + + for(int i = 0; i < DBTools.TST_TABLE_VALUES.length; i++) { + StringBuilder query = new StringBuilder("insert into " + tbl_name + " values ("); + int j = 0; + while(j < DBTools.TST_TABLE_VALUES[i].length) { + if (j > 0) { + query.append(", "); + } + Object value = DBTools.TST_TABLE_VALUES[i][j]; + if (value instanceof String || + value instanceof Date) { + query.append("'"); + } + if (value instanceof Date) { + Date date = (Date)value; + query.append(date.Year).append("-").append(date.Month).append( + "-").append(date.Day); + } else if (value instanceof Boolean) { + query.append((((Boolean)value).booleanValue()) + ? "1" : "0"); + } else { + query.append(value); + } + + if (value instanceof String || + value instanceof Date) { + query.append("'"); + } + j++; + } + query.append(")"); + statement.executeUpdate(query.toString()); + } + } + + /** + * Creates test table specified. + * Test table has some predefined format which includes as much + * field types as possible. For every column type constants + * {@link #TST_STRING TST_STRING}, {@link #TST_INT TST_INT}, etc. + * are declared for column index fast find. + * @param statement object used for executing a static SQL + * statement and obtaining the results produced by it. + * @param tbl_name Test table name. + */ + private void createMySQLTable(Statement statement, String tbl_name) + throws java.sql.SQLException { + + final String empty_col_name = "Column"; + int c = 0; + String query = "create table " + tbl_name + " ("; + for (int i = 0; i < TST_TABLE_VALUES[0].length; i++) { + if (i > 0) query += ","; + + switch(i + 1) { + case TST_BINARY_STREAM: + query += TST_BINARY_STREAM_F + " BLOB"; + break; + case TST_BOOLEAN: + query += TST_BOOLEAN_F + " TINYINT"; + break; + case TST_CHARACTER_STREAM: + query += TST_CHARACTER_STREAM_F + " TEXT"; + break; + case TST_DATE: + query += TST_DATE_F + " DATE"; + break; + case TST_DOUBLE: + query += TST_DOUBLE_F + " DOUBLE"; + break; + case TST_INT: + query += TST_INT_F + " INT"; + break; + case TST_STRING: + query += TST_STRING_F + " TEXT"; + break; + default: query += empty_col_name + (c++) + " INT"; + if (c == 1) { + query += " NOT NULL AUTO_INCREMENT"; + } + } + } + query += ", PRIMARY KEY (" + empty_col_name + "0)"; + query += ")"; + statement.execute(query); + } + + /** + * Drops table. + * @param statement object used for executing a static SQL + * statement and obtaining the results produced by it. + * @param tbl_name Test table name. + */ + private void dropMySQLTable(Statement statement, String tbl_name) + throws java.sql.SQLException { + statement.executeUpdate("drop table if exists " + tbl_name); + } +} diff --git a/qadevOOo/runner/util/DefaultDsc.java b/qadevOOo/runner/util/DefaultDsc.java new file mode 100644 index 000000000..9c270007c --- /dev/null +++ b/qadevOOo/runner/util/DefaultDsc.java @@ -0,0 +1,75 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ + +package util; + +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.uno.XInterface; +import com.sun.star.uno.UnoRuntime; + +/** + * This descriptor is useful for instances in default values. + */ +public class DefaultDsc extends InstDescr { + + private final String name = null; + private final String ifcName; + private final String service; + + public DefaultDsc( String Interface, String kind ) { + service = kind; + ifcName = Interface; + initDefault(); + } + @Override + public String getName() { + return name; + } + + @Override + public String getIfcName() { + return ifcName; + } + @Override + public String getService() { + return service; + } + + private void initDefault() { + try { + ifcClass = Class.forName( ifcName ); + } + catch( ClassNotFoundException cnfE ) { + } + } + @Override + public XInterface createInstance( XMultiServiceFactory docMSF ) { + + Object SrvObj = null; + try { + SrvObj = docMSF.createInstance( service ); + } + catch( com.sun.star.uno.Exception cssuE ){ + } + + XInterface Default = (XInterface)UnoRuntime.queryInterface(ifcClass, SrvObj ); + + return Default; + + } +} diff --git a/qadevOOo/runner/util/DesktopTools.java b/qadevOOo/runner/util/DesktopTools.java new file mode 100644 index 000000000..1c1b04402 --- /dev/null +++ b/qadevOOo/runner/util/DesktopTools.java @@ -0,0 +1,516 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ +package util; + +import helper.ConfigHelper; + +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.FileInputStream; +import java.io.InputStream; +import java.util.ArrayList; + +import lib.StatusException; + +import com.sun.star.awt.Rectangle; +import com.sun.star.awt.WindowDescriptor; +import com.sun.star.awt.XToolkit; +import com.sun.star.awt.XTopWindow; +import com.sun.star.awt.XWindowPeer; +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XPropertySet; +import com.sun.star.container.XEnumeration; +import com.sun.star.frame.XComponentLoader; +import com.sun.star.frame.XDesktop; +import com.sun.star.frame.XFrame; +import com.sun.star.frame.XModel; +import com.sun.star.io.XInputStream; +import com.sun.star.lang.XComponent; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.lang.XServiceInfo; +import com.sun.star.lib.uno.adapter.ByteArrayToXInputStreamAdapter; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XInterface; +import com.sun.star.util.XCloseable; +import com.sun.star.util.XModifiable; +import com.sun.star.view.XViewSettingsSupplier; + +/** + * contains helper methods for the Desktop + */ +public class DesktopTools +{ + + /** + * Queries the XComponentLoader + * + * @param xMSF the MultiServiceFactory + * @return the gained XComponentLoader + */ + private static XComponentLoader getCLoader(XMultiServiceFactory xMSF) + { + XComponentLoader oCLoader = UnoRuntime.queryInterface( + XComponentLoader.class, createDesktop(xMSF)); + + return oCLoader; + } + + /** + * Creates an Instance of the Desktop service + * + * @param xMSF the MultiServiceFactory + * @return the gained XDesktop object + */ + public static XDesktop createDesktop(XMultiServiceFactory xMSF) + { + XDesktop xDesktop; + + try + { + xDesktop = UnoRuntime.queryInterface( + XDesktop.class, xMSF.createInstance("com.sun.star.comp.framework.Desktop")); + } + catch (com.sun.star.uno.Exception e) + { + throw new IllegalArgumentException("Desktop Service not available", e); + } + + return xDesktop; + } + + /** + * returns a XEnumeration containing all components containing on the desktop + * @param xMSF the XMultiServiceFactory + * @return XEnumeration of all components on the desktop + */ + public static XEnumeration getAllComponents(XMultiServiceFactory xMSF) + { + return createDesktop(xMSF).getComponents().createEnumeration(); + } + + + + /** + * returns the current component on the desktop + * @param xMSF the XMultiServiceFactory + * @return XComponent of the current component on the desktop + */ + public static XFrame getCurrentFrame(XMultiServiceFactory xMSF) + { + return createDesktop(xMSF).getCurrentFrame(); + } + + /** + * returns an object array of all open documents + * @param xMSF the MultiServiceFactory + * @return returns an Array of document kinds like ["swriter"] + */ + public static Object[] getAllOpenDocuments(XMultiServiceFactory xMSF) + { + ArrayList<XComponent> components = new ArrayList<XComponent>(); + + XEnumeration allComp = getAllComponents(xMSF); + + while (allComp.hasMoreElements()) + { + try + { + XComponent xComponent = UnoRuntime.queryInterface( + XComponent.class, allComp.nextElement()); + + if (getDocumentType(xComponent) != null) + { + components.add(xComponent); + } + + } + catch (com.sun.star.container.NoSuchElementException e) + { + } + catch (com.sun.star.lang.WrappedTargetException e) + { + } + } + return components.toArray(); + } + + /** + * Returns the document type for the given XComponent of a document + * @param xComponent the document to query for its type + * @return possible: + * <ul> + * <li>swriter</li> + * <li>scalc</li> + * <li>sdraw</li> + * <li>smath</li> + * </ul> + * or <CODE>null</CODE> + */ + private static String getDocumentType(XComponent xComponent) + { + XServiceInfo sInfo = UnoRuntime.queryInterface( + XServiceInfo.class, xComponent); + + if (sInfo == null) + { + return ""; + } + else if (sInfo.supportsService("com.sun.star.sheet.SpreadsheetDocument")) + { + return "scalc"; + } + else if (sInfo.supportsService("com.sun.star.text.TextDocument")) + { + return "swriter"; + } + else if (sInfo.supportsService("com.sun.star.drawing.DrawingDocument")) + { + return "sdraw"; + } + else if (sInfo.supportsService("com.sun.star.presentation.PresentationDocument")) + { + return "simpress"; + } + else if (sInfo.supportsService("com.sun.star.formula.FormulaProperties")) + { + return "smath"; + } + else + { + return null; + } + } + + /** + * Opens a new document of a given kind + * with arguments + * @return the XComponent Interface of the document + * @param kind the kind of document to load.<br> + * possible: + * <ul> + * <li>swriter</li> + * <li>scalc</li> + * <li>sdaw</li> + * <li>smath</li> + * </ul> + * @param Args arguments which passed to the document to load + * @param xMSF the MultiServiceFactory + */ + public static XComponent openNewDoc(XMultiServiceFactory xMSF, String kind, + PropertyValue[] Args) + { + XComponent oDoc = null; + + try + { + oDoc = getCLoader(xMSF).loadComponentFromURL("private:factory/" + kind, + "_blank", 0, Args); + } + catch (com.sun.star.uno.Exception e) + { + throw new IllegalArgumentException("Document could not be opened", e); + } + + return oDoc; + } + + /** + * loads a document of from a given url + * with arguments + * @return the XComponent Interface of the document + * @param url the URL of the document to load. + * @param Args arguments which passed to the document to load + * @param xMSF the MultiServiceFactory + */ + public static XComponent loadDoc(XMultiServiceFactory xMSF, String url, + PropertyValue[] Args) + { + XComponent oDoc = null; + if (Args == null) + { + Args = new PropertyValue[0]; + } + try + { + oDoc = getCLoader(xMSF).loadComponentFromURL(url, "_blank", 0, Args); + } + catch (com.sun.star.uno.Exception e) + { + throw new IllegalArgumentException("Document could not be loaded", e); + } + + bringWindowToFront(oDoc); + return oDoc; + } + + /** + * loads a document of from a given path using an input stream + * + * @param xMSF the MultiServiceFactory + * @param filePath the path of the document to load. + * @return the XComponent Interface of the document + */ + public static XComponent loadDocUsingStream(XMultiServiceFactory xMSF, String filePath) + { + XInputStream inputStream = null; + try { + final InputStream inputFile = new BufferedInputStream( + new FileInputStream(filePath)); + try { + final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + final byte[] byteBuffer = new byte[4096]; + int byteBufferLength = 0; + while ((byteBufferLength = inputFile.read(byteBuffer)) > 0) + bytes.write(byteBuffer, 0, byteBufferLength); + inputStream = new ByteArrayToXInputStreamAdapter( + bytes.toByteArray()); + } finally { + inputFile.close(); + } + } catch (java.io.IOException e) { + e.printStackTrace(); + } + + PropertyValue[] loadProps = new PropertyValue[1]; + loadProps[0] = new PropertyValue(); + loadProps[0].Name = "InputStream"; + loadProps[0].Value = inputStream; + + XComponent oDoc = null; + try + { + oDoc = getCLoader(xMSF).loadComponentFromURL("private:stream", "_blank", 0, loadProps); + } + catch (com.sun.star.uno.Exception e) + { + throw new IllegalArgumentException("Document could not be loaded", e); + } + return oDoc; + } + + /** + * closes a given document + * @param DocumentToClose the document to close + */ + public static void closeDoc(XInterface DocumentToClose) + { + if (DocumentToClose == null) + { + return; + } + + String kd = System.getProperty("KeepDocument"); + if (kd != null) + { + System.out.println("The property 'KeepDocument' is set and so the document won't be disposed"); + return; + } + XModifiable modified = UnoRuntime.queryInterface(XModifiable.class, DocumentToClose); + XCloseable closer = UnoRuntime.queryInterface(XCloseable.class, DocumentToClose); + + try + { + if (modified != null) + { + modified.setModified(false); + } + closer.close(true); + } + catch (com.sun.star.util.CloseVetoException e) + { + System.out.println("Couldn't close document"); + } + catch (com.sun.star.lang.DisposedException e) + { + System.out.println("Couldn't close document"); + } + catch (NullPointerException e) + { + System.out.println("Couldn't close document"); + } + catch (com.sun.star.beans.PropertyVetoException e) + { + System.out.println("Couldn't close document"); + } + } + + /** + * Creates a floating XWindow with the size of X=500 Y=100 width=400 height=600 + * @param xMSF the MultiServiceFactory + * @throws lib.StatusException if it is not possible to create a floating window a lib.StatusException was thrown + * @return a floating XWindow + */ + public static XWindowPeer createFloatingWindow(XMultiServiceFactory xMSF) + throws StatusException + { + return createFloatingWindow(xMSF, 500, 100, 400, 600); + } + + /** + * Creates a floating XWindow on the given position and size. + * @return a floating XWindow + * @param X the X-Position of the floating XWindow + * @param Y the Y-Position of the floating XWindow + * @param width the width of the floating XWindow + * @param height the height of the floating XWindow + * @param xMSF the MultiServiceFactory + * @throws lib.StatusException if it is not possible to create a floating window a lib.StatusException was thrown + */ + public static XWindowPeer createFloatingWindow(XMultiServiceFactory xMSF, int X, int Y, int width, int height) + throws StatusException + { + + XInterface oObj = null; + + try + { + oObj = (XInterface) xMSF.createInstance("com.sun.star.awt.Toolkit"); + } + catch (com.sun.star.uno.Exception e) + { + throw new StatusException("Couldn't get toolkit", e); + } + + XToolkit tk = UnoRuntime.queryInterface( + XToolkit.class, oObj); + + WindowDescriptor descriptor = new com.sun.star.awt.WindowDescriptor(); + + descriptor.Type = com.sun.star.awt.WindowClass.TOP; + descriptor.WindowServiceName = "modelessdialog"; + descriptor.ParentIndex = -1; + + Rectangle bounds = new com.sun.star.awt.Rectangle(); + bounds.X = X; + bounds.Y = Y; + bounds.Width = width; + bounds.Height = height; + + descriptor.Bounds = bounds; + descriptor.WindowAttributes = (com.sun.star.awt.WindowAttribute.BORDER + + com.sun.star.awt.WindowAttribute.MOVEABLE + + com.sun.star.awt.WindowAttribute.SIZEABLE + + com.sun.star.awt.WindowAttribute.CLOSEABLE + + com.sun.star.awt.VclWindowPeerAttribute.CLIPCHILDREN); + + XWindowPeer xWindow = null; + + try + { + xWindow = tk.createWindow(descriptor); + } + catch (com.sun.star.lang.IllegalArgumentException e) + { + throw new StatusException("Could not create window", e); + } + + return xWindow; + + } + + /** + * zoom to have a view over the whole page + * @param xDoc the document to zoom + */ + public static void zoomToEntirePage(XMultiServiceFactory xMSF, XInterface xDoc) + { + try + { + XModel xMod = UnoRuntime.queryInterface(XModel.class, xDoc); + XInterface oCont = xMod.getCurrentController(); + XViewSettingsSupplier oVSSupp = UnoRuntime.queryInterface(XViewSettingsSupplier.class, oCont); + + XInterface oViewSettings = oVSSupp.getViewSettings(); + XPropertySet oViewProp = UnoRuntime.queryInterface(XPropertySet.class, oViewSettings); + oViewProp.setPropertyValue("ZoomType", + Short.valueOf(com.sun.star.view.DocumentZoomType.ENTIRE_PAGE)); + + util.utils.waitForEventIdle(xMSF); + } + catch (Exception e) + { + System.out.println("Could not zoom to entire page: " + e.toString()); + } + + } + + /** + * This function docks the Navigator onto the right side of the window.</p> + * Note:<P> + * Since the svt.viewoptions cache the view configuration at start up + * the change of the docking will be effective at a restart. + * @param xMSF the XMultiServiceFactory + */ + public static void dockNavigator(XMultiServiceFactory xMSF) + { + // prepare Window settings + try + { + ConfigHelper aConfig = new ConfigHelper(xMSF, + "org.openoffice.Office.Views", false); + + aConfig.getOrInsertGroup("Windows", "10366"); + + aConfig.updateGroupProperty( + "Windows", "10366", "WindowState", "952,180,244,349;1;0,0,0,0;"); + + aConfig.insertOrUpdateExtensibleGroupProperty( + "Windows", "10366", "UserData", "Data", "V2,V,0,AL:(5,16,0/0/244/349,244;610)"); + + // Is node "SplitWindow2" available? If not, insert it. + aConfig.getOrInsertGroup("Windows", "SplitWindow2"); + + aConfig.insertOrUpdateExtensibleGroupProperty( + "Windows", "SplitWindow2", "UserData", "UserItem", "V1,2,1,0,10366"); + + aConfig.flush(); + aConfig = null; + + } + catch (com.sun.star.uno.Exception e) + { + e.printStackTrace(); + } + } + + + /** + * This function brings a document to the front.<P> + * NOTE: it is not possible to change the window order of your Window-Manager!! + * Only the order of Office documents are changeable. + * @param xModel the XModel of the document to bring to top + */ + public static void bringWindowToFront(XModel xModel) + { + XTopWindow xTopWindow = + UnoRuntime.queryInterface( + XTopWindow.class, + xModel.getCurrentController().getFrame().getContainerWindow()); + + xTopWindow.toFront(); + } + + public static void bringWindowToFront(XComponent xComponent) + { + XModel xModel = UnoRuntime.queryInterface(XModel.class, xComponent); + if (xModel != null) + { + bringWindowToFront(xModel); + } + } +} diff --git a/qadevOOo/runner/util/DrawTools.java b/qadevOOo/runner/util/DrawTools.java new file mode 100644 index 000000000..a8f416312 --- /dev/null +++ b/qadevOOo/runner/util/DrawTools.java @@ -0,0 +1,103 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ + +package util; + +// access the implementations via names +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.uno.UnoRuntime; + +import com.sun.star.beans.PropertyValue; +import com.sun.star.lang.XComponent; +import com.sun.star.drawing.XDrawPages; +import com.sun.star.drawing.XDrawPagesSupplier; +import com.sun.star.drawing.XDrawPage; +import com.sun.star.drawing.XShapes; +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.Type; + +/** + * contains helper methods for draw documents + */ + + +public class DrawTools { + + /** + * Opens a new draw document + * with arguments + * @param xMSF the MultiServiceFactory + * @return the XComponent Interface of the document + */ + + public static XComponent createDrawDoc( XMultiServiceFactory xMSF ) { + PropertyValue[] Args = new PropertyValue [0]; + XComponent DrawDoc = DesktopTools.openNewDoc( xMSF, "sdraw", Args ); + return DrawDoc; + } // finish createDrawDoc + + /** + * gets the XDrawPages container of a draw document + * + * @param aDoc the draw document + * @return the XDrawpages container of the document + */ + + public static XDrawPages getDrawPages ( XComponent aDoc ) { + XDrawPages oDPn = null; + try { + XDrawPagesSupplier oDPS = UnoRuntime.queryInterface(XDrawPagesSupplier.class,aDoc); + + oDPn = oDPS.getDrawPages(); + } catch ( Exception e ) { + throw new IllegalArgumentException( "Couldn't get drawpages", e ); + } + return oDPn; + } // finish getDrawPages + + /** + * gets the specified XDrawPage of a draw document + * + * @param aDoc the draw document + * @param nr the index of the DrawPage + * @return the XDrawpage with index nr of the document + */ + + public static XDrawPage getDrawPage ( XComponent aDoc, int nr ) { + XDrawPage oDP = null; + try { + oDP = (XDrawPage) AnyConverter.toObject( + new Type(XDrawPage.class),getDrawPages( aDoc ).getByIndex( nr )); + } catch ( Exception e ) { + throw new IllegalArgumentException( "Couldn't get drawpage", e ); + } + return oDP; + } + + /** + * gets the XShapes container of a draw page + * + * @param oDP the draw page + * @return the XDrawShape container of the drawpage + */ + + public static XShapes getShapes ( XDrawPage oDP ) { + return UnoRuntime.queryInterface(XShapes.class,oDP); + } + +} diff --git a/qadevOOo/runner/util/DynamicClassLoader.java b/qadevOOo/runner/util/DynamicClassLoader.java new file mode 100644 index 000000000..e2bab1f9d --- /dev/null +++ b/qadevOOo/runner/util/DynamicClassLoader.java @@ -0,0 +1,97 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ + +package util; + +import java.lang.reflect.Constructor; + +public class DynamicClassLoader { + + /** + * This method returns a class created by its name + * created by call to <code>Class.forName()</code>.<p> + * This method must be overridden if another loading + * policy is required for Component and Interface + * testing classes. + * @param className The name of the class to create. + * @return The created class. + */ + private static Class<?> forName(String className) + throws ClassNotFoundException { + + return Class.forName(className) ; + } + + /** + * Get an instance of a class. The empty constructor is used. + * @param className The class to instantiate. + * @return The instance of the class. + */ + public Object getInstance(String className) + throws IllegalArgumentException { + try { + Class<?> cls = DynamicClassLoader.forName(className); + return cls.newInstance(); + } catch ( ClassNotFoundException e ) { + throw new IllegalArgumentException("Couldn't find " + className + + " " + e); + } catch ( IllegalAccessException e ) { + throw new IllegalArgumentException("Couldn't access " + className + + " " + e); + } catch ( InstantiationException e ) { + throw new IllegalArgumentException("Couldn't instantiate " + + className + " " + e); + } + } + + /** + * Get an instance of a class. The constructor matching to the + * given calls types is used and the instance is created using the arguments + * for the constructor. + * @param className The class to instantiate. + * @param ctorClassTypes The class types matching to the constructor. + * @param ctorArgs Arguments for the constructor. + * @return The instance of the class. + */ + public Object getInstance(String className, Class<?>[]ctorClassTypes, Object[] ctorArgs) + throws IllegalArgumentException { + try { + Class<?> cls = DynamicClassLoader.forName(className); + Constructor<?> ctor = cls.getConstructor(ctorClassTypes); + System.out.println("ctor: " + ctor.getName() + " " + ctor.getModifiers()); + + return ctor.newInstance(ctorArgs); + } catch ( ClassNotFoundException e ) { + throw new IllegalArgumentException("Couldn't find " + className + + " " + e); + } catch ( IllegalAccessException e ) { + throw new IllegalArgumentException("Couldn't access " + className + + " " + e); + } catch ( NoSuchMethodException e ) { + throw new IllegalArgumentException("Couldn't find constructor for " + className + + " " + e); + } catch ( java.lang.reflect.InvocationTargetException e ) { + e.printStackTrace(); + throw new IllegalArgumentException("Couldn't invoke " + + className + " " + e); + } catch ( InstantiationException e ) { + throw new IllegalArgumentException("Couldn't instantiate " + + className + " " + e); + } + } +} diff --git a/qadevOOo/runner/util/FootnoteDsc.java b/qadevOOo/runner/util/FootnoteDsc.java new file mode 100644 index 000000000..b14f70bf8 --- /dev/null +++ b/qadevOOo/runner/util/FootnoteDsc.java @@ -0,0 +1,72 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ + +package util; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.uno.XInterface; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.text.XTextContent; + +/** + * describes a Footnote to be inserted in a container + */ +public class FootnoteDsc extends InstDescr { + + private static final String service = "com.sun.star.text.Footnote"; + private static final String ifcName = "com.sun.star.text.XTextContent"; + + public FootnoteDsc() { + initFootnote(); + } + + @Override + public String getName() { + return null; + } + + @Override + public String getIfcName() { + return ifcName; + } + + @Override + public String getService() { + return service; + } + + private void initFootnote() { + try { + ifcClass = Class.forName( ifcName ); + } + catch( ClassNotFoundException cnfE ) { + } + } + @Override + public XInterface createInstance( XMultiServiceFactory docMSF ) { + Object ServiceObj = null; + + try { + ServiceObj = docMSF.createInstance( service ); + } + catch( com.sun.star.uno.Exception cssuE ){ + } + XTextContent FN = (XTextContent)UnoRuntime.queryInterface( ifcClass, + ServiceObj ); + return FN; + } +} diff --git a/qadevOOo/runner/util/FormTools.java b/qadevOOo/runner/util/FormTools.java new file mode 100644 index 000000000..2189612cd --- /dev/null +++ b/qadevOOo/runner/util/FormTools.java @@ -0,0 +1,287 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ + +package util; + +// access the implementations via names +import com.sun.star.uno.XInterface; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.lang.XComponent; +import com.sun.star.drawing.XControlShape; +import com.sun.star.drawing.XDrawPage; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.awt.Size; +import com.sun.star.awt.Point; +import com.sun.star.awt.XControlModel; +import com.sun.star.container.XNameContainer; +import com.sun.star.container.XIndexContainer; +import com.sun.star.form.XFormsSupplier; +import com.sun.star.form.XForm; +import com.sun.star.form.XLoadable; +import com.sun.star.text.XTextDocument; +import com.sun.star.beans.XPropertySet; +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.Type; + +/** + * contains helper methods forms + */ + +public class FormTools { + + + /** + * creates a XControlShape + * + * @param oDoc the document + * @param height the height of the shape + * @param width the width of the shape + * @param x the x-position of the shape + * @param y the y-position of the shape + * @param kind the kind of the shape + * @return the created XControlShape + */ + public static XControlShape createControlShape( XComponent oDoc, int height, + int width, int x, int y, String kind ) + throws com.sun.star.uno.Exception + { + + Size size = new Size(); + Point position = new Point(); + XControlShape oCShape = null; + XControlModel aControl = null; + + XMultiServiceFactory oDocMSF = UnoRuntime.queryInterface( XMultiServiceFactory.class, oDoc ); + + Object oInt = oDocMSF.createInstance("com.sun.star.drawing.ControlShape"); + Object aCon = oDocMSF.createInstance("com.sun.star.form.component."+kind); + XPropertySet model_props = UnoRuntime.queryInterface(XPropertySet.class,aCon); + model_props.setPropertyValue("DefaultControl","com.sun.star.form.control."+kind); + aControl = UnoRuntime.queryInterface( XControlModel.class, aCon ); + oCShape = UnoRuntime.queryInterface( XControlShape.class, oInt ); + size.Height = height; + size.Width = width; + position.X = x; + position.Y = y; + oCShape.setSize(size); + oCShape.setPosition(position); + + oCShape.setControl(aControl); + + return oCShape; + } // finish createControlShape + + public static XControlShape createUnoControlShape( XComponent oDoc, int height, + int width, int x, int y, String kind, String defControl ) + throws com.sun.star.uno.Exception + { + + Size size = new Size(); + Point position = new Point(); + XControlShape oCShape = null; + XControlModel aControl = null; + + XMultiServiceFactory oDocMSF = UnoRuntime.queryInterface( XMultiServiceFactory.class, oDoc ); + + Object oInt = oDocMSF.createInstance("com.sun.star.drawing.ControlShape"); + Object aCon = oDocMSF.createInstance("com.sun.star.form.component."+kind); + XPropertySet model_props = UnoRuntime.queryInterface(XPropertySet.class,aCon); + model_props.setPropertyValue("DefaultControl","com.sun.star.awt."+defControl); + aControl = UnoRuntime.queryInterface( XControlModel.class, aCon ); + oCShape = UnoRuntime.queryInterface( XControlShape.class, oInt ); + size.Height = height; + size.Width = width; + position.X = x; + position.Y = y; + oCShape.setSize(size); + oCShape.setPosition(position); + + oCShape.setControl(aControl); + + return oCShape; + } // finish createControlShape + + public static XControlShape createControlShapeWithDefaultControl( XComponent oDoc, int height, + int width, int x, int y, String kind ) + throws com.sun.star.uno.Exception + { + + Size size = new Size(); + Point position = new Point(); + XControlShape oCShape = null; + XControlModel aControl = null; + + XMultiServiceFactory oDocMSF = UnoRuntime.queryInterface( XMultiServiceFactory.class, oDoc ); + + Object oInt = oDocMSF.createInstance("com.sun.star.drawing.ControlShape"); + Object aCon = oDocMSF.createInstance("com.sun.star.form.component."+kind); + + aControl = UnoRuntime.queryInterface( XControlModel.class, aCon ); + oCShape = UnoRuntime.queryInterface( XControlShape.class, oInt ); + size.Height = height; + size.Width = width; + position.X = x; + position.Y = y; + oCShape.setSize(size); + oCShape.setPosition(position); + + oCShape.setControl(aControl); + + return oCShape; + } // finish createControlShape + + public static XInterface createControl( XComponent oDoc, String kind ) + throws com.sun.star.uno.Exception + { + XInterface oControl = null; + + XMultiServiceFactory oDocMSF = UnoRuntime.queryInterface( XMultiServiceFactory.class, oDoc ); + + oControl = (XInterface) oDocMSF.createInstance( + "com.sun.star.form.component."+kind); + return oControl; + } // finish createControl + + public static XNameContainer getForms ( XDrawPage oDP ) + { + XFormsSupplier oFS = UnoRuntime.queryInterface( + XFormsSupplier.class,oDP); + return oFS.getForms(); + } //finish getForms + + private static XIndexContainer getIndexedForms ( XDrawPage oDP ) + { + XFormsSupplier oFS = UnoRuntime.queryInterface( + XFormsSupplier.class,oDP); + return UnoRuntime.queryInterface( XIndexContainer.class, + oFS.getForms() ); + } //finish getIndexedForms + + public static void insertForm ( XComponent aDoc, XNameContainer Forms, + String aName ) + throws com.sun.star.uno.Exception + { + XInterface oControl = createControl(aDoc, "Form"); + XForm oForm = UnoRuntime.queryInterface(XForm.class, oControl); + Forms.insertByName(aName,oForm); + } + + public static XControlShape insertControlShape( XComponent oDoc, int height, + int width, int x, int y, String kind ) + throws com.sun.star.uno.Exception + { + XControlShape aShape = createControlShape(oDoc,height,width,x,y,kind); + XDrawPage oDP = DrawTools.getDrawPage(oDoc,0); + DrawTools.getShapes(oDP).add(aShape); + return aShape; + } + + public static XLoadable bindForm( XTextDocument aDoc ) + throws com.sun.star.uno.Exception + { + XLoadable formLoader = null; + + Object aForm = FormTools.getIndexedForms(WriterTools.getDrawPage(aDoc)).getByIndex(0); + XForm the_form = null; + the_form = (XForm) AnyConverter.toObject(new Type(XForm.class), aForm); + XPropertySet formProps = UnoRuntime.queryInterface(XPropertySet.class, the_form); + formProps.setPropertyValue("DataSourceName","Bibliography"); + formProps.setPropertyValue("Command","biblio"); + formProps.setPropertyValue("CommandType",Integer.valueOf(com.sun.star.sdb.CommandType.TABLE)); + formLoader = UnoRuntime.queryInterface(XLoadable.class, the_form); + + return formLoader; + } + + /** + * Binds <code>'Standard'</code> form of <code>aDoc</code> Writer document + * to the <code>tableName</code> table of <code>sourceName</code> + * Data Source. + * @param aDoc Writer document where DB controls are added. + * @param sourceName The name of DataSource in the <code>DatabaseContext</code>. + * @param tableName The name of the table to which controls are bound. + * @return <code>com.sun.star.form.component.DatabaseForm</code> service + * implementation which is the bound form inside the document. + */ + public static XLoadable bindForm( XTextDocument aDoc, String sourceName, String tableName ) + throws com.sun.star.uno.Exception { + + XForm the_form = (XForm) AnyConverter.toObject(new Type(XForm.class), + FormTools.getIndexedForms(WriterTools.getDrawPage(aDoc)).getByIndex(0)); + XPropertySet formProps = UnoRuntime.queryInterface(XPropertySet.class, the_form); + formProps.setPropertyValue("DataSourceName",sourceName); + formProps.setPropertyValue("Command",tableName); + formProps.setPropertyValue("CommandType",Integer.valueOf(com.sun.star.sdb.CommandType.TABLE)); + + return UnoRuntime.queryInterface(XLoadable.class, the_form); + } + + + + /** + * Binds the form with the name specified of <code>aDoc</code> Writer document + * to the <code>tableName</code> table of <code>sourceName</code> + * Data Source. + * @param aDoc Writer document where DB controls are added. + * @param formName The name of the form to be bound. + * @param sourceName The name of DataSource in the <code>DatabaseContext</code>. + * @param tableName The name of the table to which controls are bound. + * @return <code>com.sun.star.form.component.DatabaseForm</code> service + * implementation which is the bound form inside the document. + */ + public static XLoadable bindForm( XTextDocument aDoc, String formName, String sourceName, + String tableName) throws com.sun.star.uno.Exception { + + XForm the_form = (XForm) AnyConverter.toObject(new Type(XForm.class), + FormTools.getForms(WriterTools.getDrawPage(aDoc)).getByName(formName)); + XPropertySet formProps = UnoRuntime.queryInterface(XPropertySet.class, the_form); + formProps.setPropertyValue("DataSourceName",sourceName); + formProps.setPropertyValue("Command",tableName); + formProps.setPropertyValue("CommandType",Integer.valueOf(com.sun.star.sdb.CommandType.TABLE)); + + return UnoRuntime.queryInterface(XLoadable.class, the_form); + } + + public static void switchDesignOf(XMultiServiceFactory xMSF, XTextDocument aDoc) + throws com.sun.star.uno.Exception + { + com.sun.star.frame.XController aController = aDoc.getCurrentController(); + com.sun.star.frame.XFrame aFrame = aController.getFrame(); + com.sun.star.frame.XDispatchProvider aDispProv = UnoRuntime.queryInterface(com.sun.star.frame.XDispatchProvider.class,aFrame); + com.sun.star.util.URL aURL = new com.sun.star.util.URL(); + aURL.Complete = ".uno:SwitchControlDesignMode"; + + Object instance = xMSF.createInstance("com.sun.star.util.URLTransformer"); + com.sun.star.util.XURLTransformer atrans = + UnoRuntime.queryInterface( + com.sun.star.util.XURLTransformer.class,instance); + com.sun.star.util.URL[] aURLA = new com.sun.star.util.URL[1]; + aURLA[0] = aURL; + atrans.parseStrict(aURLA); + aURL = aURLA[0]; + + com.sun.star.frame.XDispatch aDisp = aDispProv.queryDispatch(aURL, "", + com.sun.star.frame.FrameSearchFlag.SELF | + com.sun.star.frame.FrameSearchFlag.CHILDREN); + + com.sun.star.beans.PropertyValue[] noArgs = new com.sun.star.beans.PropertyValue[0]; + aDisp.dispatch(aURL, noArgs); + util.utils.waitForEventIdle(xMSF); // async dispatch + } + +} diff --git a/qadevOOo/runner/util/FrameDsc.java b/qadevOOo/runner/util/FrameDsc.java new file mode 100644 index 000000000..b2e690282 --- /dev/null +++ b/qadevOOo/runner/util/FrameDsc.java @@ -0,0 +1,109 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ + +package util; + +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.uno.XInterface; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.text.XTextFrame; +import com.sun.star.drawing.XShape; +import com.sun.star.awt.Size; +import com.sun.star.beans.XPropertySet; +/** + * the class FrameDsc + */ +public class FrameDsc extends InstDescr { + + private int height = 2000; + private int width = 2000; + private static final String ifcName = "com.sun.star.text.XTextFrame"; + private static final String service = "com.sun.star.text.TextFrame"; + + public FrameDsc() { + initFrame(); + } + + public FrameDsc( int nHeight, int nWidth ) { + height = nHeight; + width = nWidth; + initFrame(); + } + + @Override + public String getName() { + return null; + } + @Override + public String getIfcName() { + return ifcName; + } + @Override + public String getService() { + return service; + } + + private void initFrame() { + try { + ifcClass = Class.forName( ifcName ); + } + catch( ClassNotFoundException cnfE ) { + } + } + @Override + public XInterface createInstance( XMultiServiceFactory docMSF ) { + Object SrvObj = null; + + Size size = new Size(); + size.Height = height; + size.Width = width; + + try { + SrvObj = docMSF.createInstance( service ); + } + catch( com.sun.star.uno.Exception cssuE ){ + } + XShape shape = UnoRuntime.queryInterface( XShape.class, SrvObj ); + try { + shape.setSize(size); + } + catch( com.sun.star.beans.PropertyVetoException pvE ){ + } + + XTextFrame TF = (XTextFrame)UnoRuntime.queryInterface( ifcClass, SrvObj ); + + XPropertySet oPropSet = UnoRuntime.queryInterface( XPropertySet.class, SrvObj ); + + + try { + oPropSet.setPropertyValue("AnchorType", Integer.valueOf(2)); + } + catch( com.sun.star.beans.UnknownPropertyException upE ){ + } + catch( com.sun.star.beans.PropertyVetoException pvE ){ + } + catch( com.sun.star.lang.IllegalArgumentException iaE ){ + } + catch( com.sun.star.lang.WrappedTargetException wtE ){ + } + + + + return TF; + } +} diff --git a/qadevOOo/runner/util/InstCreator.java b/qadevOOo/runner/util/InstCreator.java new file mode 100644 index 000000000..d517f0cd1 --- /dev/null +++ b/qadevOOo/runner/util/InstCreator.java @@ -0,0 +1,104 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ + +package util; + +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XInterface; +import com.sun.star.text.XTextTablesSupplier; +import com.sun.star.text.XTextFramesSupplier; +import com.sun.star.text.XTextSectionsSupplier; +import com.sun.star.text.XFootnotesSupplier; +import com.sun.star.text.XBookmarksSupplier; +import com.sun.star.container.XNameAccess; +import com.sun.star.container.XIndexAccess; + + +public class InstCreator implements XInstCreator { + private final XInterface xParent; + private final XMultiServiceFactory xMSF; + private final XInterface xInstance; + private final XIndexAccess xIA; + private final InstDescr iDsc; + + public InstCreator( XInterface xParent, InstDescr iDsc ) { + this.xParent = xParent; + this.iDsc = iDsc; + + xMSF = UnoRuntime.queryInterface( + XMultiServiceFactory.class, xParent ); + + xInstance = createInstance(); + xIA = createCollection(); + } + public XInterface getInstance() { + return xInstance; + } + + public XInterface createInstance() { + XInterface xIfc = null; + xIfc = iDsc.createInstance( xMSF ); + + return xIfc; + } + + public XIndexAccess getCollection() { + return xIA; + } + + private XIndexAccess createCollection() { + XNameAccess oNA = null; + + if ( iDsc instanceof TableDsc ) { + XTextTablesSupplier oTTS = UnoRuntime.queryInterface( + XTextTablesSupplier.class, xParent ); + + oNA = oTTS.getTextTables(); + } + if ( iDsc instanceof FrameDsc ) { + XTextFramesSupplier oTTS = UnoRuntime.queryInterface( + XTextFramesSupplier.class, xParent ); + + oNA = oTTS.getTextFrames(); + } + if ( iDsc instanceof BookmarkDsc ) { + XBookmarksSupplier oTTS = UnoRuntime.queryInterface( + XBookmarksSupplier.class, xParent ); + + oNA = oTTS.getBookmarks(); + } + + if ( iDsc instanceof FootnoteDsc ) { + XFootnotesSupplier oTTS = UnoRuntime.queryInterface( + XFootnotesSupplier.class, xParent ); + + return oTTS.getFootnotes(); + } + + if ( iDsc instanceof TextSectionDsc ) { + XTextSectionsSupplier oTSS = UnoRuntime.queryInterface( + XTextSectionsSupplier.class, xParent ); + + oNA = oTSS.getTextSections(); + } + + return UnoRuntime.queryInterface( + XIndexAccess.class, oNA); + } +}
\ No newline at end of file diff --git a/qadevOOo/runner/util/InstDescr.java b/qadevOOo/runner/util/InstDescr.java new file mode 100644 index 000000000..7b7098be6 --- /dev/null +++ b/qadevOOo/runner/util/InstDescr.java @@ -0,0 +1,38 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ + +package util; + +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.uno.XInterface; +/** + * the class InstDescr + */ +abstract public class InstDescr { + + protected Class<?> ifcClass = null; + + protected abstract String getIfcName(); + protected abstract String getName(); + + /** + * the method getService + */ + protected abstract String getService(); + protected abstract XInterface createInstance( XMultiServiceFactory docMSF ); +}
\ No newline at end of file diff --git a/qadevOOo/runner/util/ParagraphDsc.java b/qadevOOo/runner/util/ParagraphDsc.java new file mode 100644 index 000000000..12ec3bf12 --- /dev/null +++ b/qadevOOo/runner/util/ParagraphDsc.java @@ -0,0 +1,73 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ + +package util; + +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.uno.XInterface; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.text.XTextContent; + +/** + * the class ParagraphDsc + */ +public class ParagraphDsc extends InstDescr { + + private static final String service = "com.sun.star.text.Paragraph"; + private static final String ifcName = "com.sun.star.text.XTextContent"; + + public ParagraphDsc() { + initParagraph(); + } + + @Override + public String getName() { + return null; + } + + @Override + public String getIfcName() { + return ifcName; + } + + @Override + public String getService() { + return service; + } + + private void initParagraph() { + try { + ifcClass = Class.forName( ifcName ); + } + catch( ClassNotFoundException cnfE ) { + } + } + @Override + public XInterface createInstance( XMultiServiceFactory docMSF ) { + Object ServiceObj = null; + + try { + ServiceObj = docMSF.createInstance( service ); + } + catch( com.sun.star.uno.Exception cssuE ){ + } + XTextContent PG = (XTextContent)UnoRuntime.queryInterface( ifcClass, + ServiceObj ); + return PG; + } +} diff --git a/qadevOOo/runner/util/PropertyName.java b/qadevOOo/runner/util/PropertyName.java new file mode 100644 index 000000000..4812bd7f6 --- /dev/null +++ b/qadevOOo/runner/util/PropertyName.java @@ -0,0 +1,117 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ +package util; + +/** + * This interfaces describes some key names which are used in <CODE>lib.TestParameters</CODE>. + */ + +public interface PropertyName { + /** + * parameter name: "AppExecutionCommand" + * The AppExecutionCmd contains the full qualified<br> + * command to an Application to be started. + */ + String APP_EXECUTION_COMMAND = "AppExecutionCommand"; + /** + * parameter name: "ConnectionString" + */ + String CONNECTION_STRING = "ConnectionString"; + String PIPE_CONNECTION_STRING = "PipeConnectionString"; + String USE_PIPE_CONNECTION = "UsePipeConnection"; + + /** + * parameter name: "TestBase" + * The Testbase to be executed by the runner<br> + * default is 'java_fat' + */ + String TEST_BASE = "TestBase"; + /** + * parameter name: "TestDocumentPath" + */ + String TEST_DOCUMENT_PATH = "TestDocumentPath"; + /** + * parameter name: "LoggingIsActive" + * 'true' is a log should be written, 'false' elsewhere <br> + * these will be provided by the testcases<br> + * default is true + */ + String LOGGING_IS_ACTIVE = "LoggingIsActive"; + /** + * parameter name: "DebugIsActive" + */ + String DEBUG_IS_ACTIVE = "DebugIsActive"; + /** + * parameter name: "OutProducer" + * This parameter contains the class used<br> + * for Logging + */ + String OUT_PRODUCER = "OutProducer"; + /** + * internal only, no parameter + * The OfficeProvider contains the full qualified + * class that provides a connection to StarOffice<br> + * default is helper.OfficeProvider + */ + String OFFICE_PROVIDER = "OfficeProvider"; + /** + * internal only, no parameter + */ + String OFFICE_WATCHER = "Watcher"; + /** + * internal only, no parameter + * This parameter contains the class used<br> + * for Logging + */ + String LOG_WRITER = "LogWriter"; + /** + * parameter name: "TimeOut"<p> + * time out given in milliseconds + * This parameter contains the timeout used<br> + * by the watcher + */ + String TIME_OUT = "TimeOut"; + /** + * parameter name: "ThreadTimeOut" + * This parameter contains the timeout used<br> + * by the complex tests + */ + String THREAD_TIME_OUT = "ThreadTimeOut"; + /** + * parameter name: "UnoRcName" + */ + String UNORC_NAME = "UnoRcName"; + /** + * parameter name: "AutoRestart" + * If this parameter is <CODE>true</CODE> the <CODE>OfficeProvider</CODE> tries + * to get the URL to the binary of the office and to fill the + * <CODE>AppExecutionCommand</CODE> with useful content if needed. + * Default is false. + */ + String AUTO_RESTART = "AutoRestart"; + /** + * parameter name: "NewOfficeInstance" + */ + String NEW_OFFICE_INSTANCE = "NewOfficeInstance"; + + /** + * parameter name: "SRC_ROOT"<p> + * path to the source root of OpenOffice.org + */ + String SRC_ROOT = "SRC_ROOT"; +} diff --git a/qadevOOo/runner/util/RegistryTools.java b/qadevOOo/runner/util/RegistryTools.java new file mode 100644 index 000000000..72ef5e743 --- /dev/null +++ b/qadevOOo/runner/util/RegistryTools.java @@ -0,0 +1,359 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ + +package util; + +// access the implementations via names +import com.sun.star.uno.UnoRuntime; +import java.io.PrintWriter ; + +import com.sun.star.registry.XRegistryKey ; +import com.sun.star.registry.XSimpleRegistry ; +import com.sun.star.registry.RegistryKeyType ; +import com.sun.star.registry.RegistryValueType ; +import com.sun.star.registry.InvalidRegistryException ; +import com.sun.star.lang.XMultiServiceFactory ; +import com.sun.star.uno.Exception; + +public class RegistryTools { + + /** + * Creates 'com.sun.star.registry.SimpleRegistry' + * service. + * @param xMSF Multiservice factory. + * @return Service created. + */ + public static XSimpleRegistry createRegistryService + (XMultiServiceFactory xMSF) throws com.sun.star.uno.Exception { + + Object oInterface = xMSF.createInstance + ("com.sun.star.registry.SimpleRegistry"); + return UnoRuntime.queryInterface ( + XSimpleRegistry.class, oInterface) ; + } + + /** + * Opens registry file for reading/writing. If file doesn't + * exist a new one created. + * @param file Registry file name. + * @param xMSF Multiservice factory. + * @return Opened registry. + */ + public static XSimpleRegistry openRegistry + (String file, XMultiServiceFactory xMSF) + throws com.sun.star.uno.Exception { + + XSimpleRegistry reg = createRegistryService(xMSF) ; + + reg.open(file, false, true) ; + + return reg ; + } + + /** + * Compares two registry keys, their names, value + * types and values. + * return <code>true</code> if key names, value types + * and values are equal, else returns <code>false</code>. + */ + private static boolean compareKeys + (XRegistryKey key1, XRegistryKey key2) { + + if (key1 == null || key2 == null || + !key1.isValid() || !key2.isValid()) + + return false ; + + String keyName1 = getShortKeyName(key1.getKeyName()) ; + String keyName2 = getShortKeyName(key2.getKeyName()) ; + + if (!keyName1.equals(keyName2)) return false ; + + try { + if (key1.getValueType() != key2.getValueType()) return false ; + } catch (InvalidRegistryException e) { + return false ; + } + + RegistryValueType type ; + try { + type = key1.getValueType() ; + + if (type.equals(RegistryValueType.ASCII)) { + if (!key1.getAsciiValue().equals(key2.getAsciiValue())) + return false ; + } else + if (type.equals(RegistryValueType.STRING)) { + if (!key1.getStringValue().equals(key2.getStringValue())) + return false ; + } else + if (type.equals(RegistryValueType.LONG)) { + if (key1.getLongValue() != key2.getLongValue()) + return false ; + } else + if (type.equals(RegistryValueType.BINARY)) { + byte[] bin1 = key1.getBinaryValue() ; + byte[] bin2 = key2.getBinaryValue() ; + if (bin1.length != bin2.length) + return false ; + for (int i = 0; i < bin1.length; i++) + if (bin1[i] != bin2[i]) return false ; + } else + if (type.equals(RegistryValueType.ASCIILIST)) { + String[] list1 = key1.getAsciiListValue() ; + String[] list2 = key2.getAsciiListValue() ; + if (list1.length != list2.length) + return false ; + for (int i = 0; i < list1.length; i++) + if (!list1[i].equals(list2[i])) return false ; + } else + if (type.equals(RegistryValueType.STRINGLIST)) { + String[] list1 = key1.getStringListValue() ; + String[] list2 = key2.getStringListValue() ; + if (list1.length != list2.length) + return false ; + for (int i = 0; i < list1.length; i++) + if (!list1[i].equals(list2[i])) return false ; + } else + if (type.equals(RegistryValueType.LONGLIST)) { + int[] list1 = key1.getLongListValue() ; + int[] list2 = key2.getLongListValue() ; + if (list1.length != list2.length) + return false ; + for (int i = 0; i < list1.length; i++) + if (list1[i] != list2[i]) return false ; + } + } catch (Exception e) { + return false ; + } + + return true ; + } + + /** + * Gets name of the key relative to its parent. + * For example if full name of key is '/key1/subkey' + * short key name is 'subkey' + * @param keyName Full key name. + * @return Short key name. + */ + private static String getShortKeyName(String keyName) { + if (keyName == null) return null ; + int idx = keyName.lastIndexOf('/') ; + if (idx < 0) return keyName ; + else return keyName.substring(idx + 1) ; + } + + /** + * Compare all child keys. + * @param compareRoot If <code>true</code> method also + * compare root keys, if <code>false</code> it begins recursive + * comparing from children of root keys. + * @return <code>true</code> if keys and their sub keys are equal. + */ + private static boolean compareKeyTrees + (XRegistryKey tree1, XRegistryKey tree2, boolean compareRoot) { + + if (compareRoot && !compareKeys(tree1, tree2)) return false ; + + try { + String[] keyNames1 = tree1.getKeyNames() ; + String[] keyNames2 = tree2.getKeyNames() ; + + if (keyNames1 == null && keyNames2 == null) return true ; + + if (keyNames1 == null || keyNames2 == null || + keyNames2.length != keyNames1.length) + return false ; + + for (int i = 0; i < keyNames1.length; i++) { + + String keyName = getShortKeyName(keyNames1[i]) ; + XRegistryKey key2 = tree2.openKey(keyName) ; + + if (key2 == null) + // key with the same name doesn't exist in the second tree + return false ; + + if (!tree1.getKeyType(keyName).equals( + tree2.getKeyType(keyName))) + return false ; + + if (tree1.getKeyType(keyName).equals( + RegistryKeyType.LINK)) { + + if (!getShortKeyName(tree1.getLinkTarget(keyName)).equals( + getShortKeyName(tree2.getLinkTarget(keyName)))) + + return false ; + } else { + + if (!compareKeyTrees(tree1.openKey(keyName), + tree2.openKey(keyName), true)) return false ; + } + } + } catch (InvalidRegistryException e) { + return false ; + } + + return true ; + } + + /** + * Compare keys specified and all their child keys. + * @return <code>true</code> if keys and their sub keys are equal. + */ + public static boolean compareKeyTrees + (XRegistryKey tree1, XRegistryKey tree2) { + + return compareKeyTrees(tree1, tree2, false) ; + } + + /** + * Prints to a specified output about all keys and subkeys information + * (key name, type, value, link target, attributes) recursively. + * @param reg Registry for which information is needed. + * @param out Output stream. + */ + public static void printRegistryInfo(XSimpleRegistry reg, PrintWriter out) { + try { + printRegistryInfo(reg.getRootKey(), out) ; + } catch (com.sun.star.registry.InvalidRegistryException e) { + out.println("!!! Can't open root registry key for info printing") ; + } + } + + /** + * Prints to a specified output about all keys and subkeys information + * (key name, type, value, link target, attributes) recursively. + * @param root Key for which subkeys (and further) information is required. + * @param out Output stream. + */ + public static void printRegistryInfo(XRegistryKey root, PrintWriter out) { + if (root == null) { + out.println("/(null)") ; + return ; + } + + out.println("/") ; + try { + printTreeInfo(root, out, " ") ; + } catch (com.sun.star.registry.InvalidRegistryException e) { + out.println("Exception accessing registry :") ; + e.printStackTrace(out) ; + } + } + + private static void printTreeInfo(XRegistryKey key, + PrintWriter out, String margin) + throws com.sun.star.registry.InvalidRegistryException { + + String[] subKeys = key.getKeyNames() ; + + if (subKeys == null || subKeys.length == 0) return ; + + for (int i = 0; i < subKeys.length; i++) { + printKeyInfo(key, subKeys[i], out, margin) ; + XRegistryKey subKey = key.openKey + (getShortKeyName(subKeys[i])) ; + printTreeInfo(subKey, out, margin + " ") ; + subKey.closeKey() ; + } + } + + private static void printKeyInfo(XRegistryKey parentKey, + String keyName, PrintWriter out, String margin) + throws com.sun.star.registry.InvalidRegistryException { + + out.print(margin) ; + keyName = getShortKeyName(keyName) ; + XRegistryKey key = parentKey.openKey(keyName) ; + if (key != null) + out.print("/" + getShortKeyName(key.getKeyName()) + " ") ; + else { + out.println("(null)") ; + return ; + } + + if (!key.isValid()) { + out.println("(not valid)") ; + return ; + } + + if (key.isReadOnly()) { + out.print("(read only) ") ; + } + + if (parentKey.getKeyType(keyName) == RegistryKeyType.LINK) { + out.println("(link to " + parentKey.getLinkTarget(keyName) + ")") ; + return ; + } + + RegistryValueType type ; + try { + type = key.getValueType() ; + + if (type.equals(RegistryValueType.ASCII)) { + out.println("[ASCII] = '" + key.getAsciiValue() + "'") ; + } else + if (type.equals(RegistryValueType.STRING)) { + out.println("[STRING] = '" + key.getStringValue() + "'") ; + } else + if (type.equals(RegistryValueType.LONG)) { + out.println("[LONG] = " + key.getLongValue()) ; + } else + if (type.equals(RegistryValueType.BINARY)) { + out.print("[BINARY] = {") ; + byte[] bin = key.getBinaryValue() ; + for (int i = 0; i < bin.length; i++) + out.print(bin[i] + ",") ; + out.println("}") ; + } else + if (type.equals(RegistryValueType.ASCIILIST)) { + out.print("[ASCIILIST] = {") ; + String[] list = key.getAsciiListValue() ; + for (int i = 0; i < list.length; i++) + out.print("'" + list[i] + "',") ; + out.println("}") ; + } else + if (type.equals(RegistryValueType.STRINGLIST)) { + out.print("[STRINGLIST] = {") ; + String[] list = key.getStringListValue() ; + for (int i = 0; i < list.length; i++) + out.print("'" + list[i] + "',") ; + out.println("}") ; + } else + if (type.equals(RegistryValueType.LONGLIST)) { + out.print("[LONGLIST] = {") ; + int[] list = key.getLongListValue() ; + for (int i = 0; i < list.length; i++) + out.print(list[i] + ",") ; + out.println("}") ; + } else { + out.println("") ; + } + } catch (com.sun.star.uno.Exception e) { + out.println("Exception occurred : ") ; + e.printStackTrace(out) ; + } finally { + key.closeKey() ; + } + } + + +} diff --git a/qadevOOo/runner/util/SOfficeFactory.java b/qadevOOo/runner/util/SOfficeFactory.java new file mode 100644 index 000000000..43667d15d --- /dev/null +++ b/qadevOOo/runner/util/SOfficeFactory.java @@ -0,0 +1,443 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ +package util; + +import java.util.HashMap; +// access the implementations via names +import com.sun.star.uno.XInterface; +import com.sun.star.lang.XMultiServiceFactory; + +import com.sun.star.uno.UnoRuntime; +// staroffice interfaces to provide desktop and componentloader +// and components i.e. spreadsheets, writerdocs etc. +import com.sun.star.frame.XDesktop; +import com.sun.star.frame.XComponentLoader; +import com.sun.star.lang.XComponent; +// name - value pair +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.PropertyState; + +// additional classes required for testcase +import com.sun.star.sheet.*; +import com.sun.star.text.*; +import com.sun.star.container.*; +import com.sun.star.chart.*; +import com.sun.star.drawing.*; + +public class SOfficeFactory { + + private static HashMap<String, SOfficeFactory> lookup = new HashMap<String, SOfficeFactory>(10); + private final XComponentLoader oCLoader; + + private SOfficeFactory(XMultiServiceFactory xMSF) { + // get XInterface of Desktop service + Object oInterface; + try { + oInterface = xMSF.createInstance("com.sun.star.frame.Desktop"); + } catch (com.sun.star.uno.Exception e) { + throw new IllegalArgumentException("Desktop Service not available", e); + } + + // query the desktop interface and then it's componentloader + XDesktop oDesktop = UnoRuntime.queryInterface( + XDesktop.class, oInterface); + + oCLoader = UnoRuntime.queryInterface( + XComponentLoader.class, oDesktop); + } + + public static SOfficeFactory getFactory(XMultiServiceFactory xMSF) { + + SOfficeFactory soFactory = lookup.get(Integer.toString(xMSF.hashCode())); + + if (soFactory == null) { + soFactory = new SOfficeFactory(xMSF); + lookup.put(Integer.toString(xMSF.hashCode()), soFactory); + } + + return soFactory; + } + + // ********************************************************* + // Document creation. The documents needed are created here. + // ********************************************************* + /** + * method which opens a new TextDocument + * + * @see XTextDocument + */ + public XTextDocument createTextDoc(String frameName) + throws com.sun.star.uno.Exception { + + XComponent oDoc = openDoc("swriter", frameName); + + if (oDoc != null) { + DesktopTools.bringWindowToFront(oDoc); + return UnoRuntime.queryInterface(XTextDocument.class, oDoc); + } else { + return null; + } + + } // finished createTextDoc + + + + /** + * method which opens a new SpreadsheetDocument + * + * @see XSpreadsheetDocument + */ + public XSpreadsheetDocument createCalcDoc(String frameName) + throws com.sun.star.uno.Exception { + + XComponent oDoc = openDoc("scalc", frameName); + + if (oDoc != null) { + DesktopTools.bringWindowToFront(oDoc); + return UnoRuntime.queryInterface(XSpreadsheetDocument.class, oDoc); + } else { + return null; + } + } // finished createCalcDoc + + + + /** + * method which opens a new DrawDocument + */ + public XComponent createDrawDoc(String frameName) + throws com.sun.star.uno.Exception { + + return openDoc("sdraw", frameName); + } // finished createDrawDoc + + + + /** + * method which opens a new ImpressDocument + */ + public XComponent createImpressDoc(String frameName) + throws com.sun.star.uno.Exception { + + return openDoc("simpress", frameName); + } // finished createImpressDoc + + + + /** + * method which opens a new MathDocument + */ + public XComponent createMathDoc(String frameName) + throws com.sun.star.uno.Exception { + + return openDoc("smath", frameName); + } // finished createMathDoc + + + + /** + * method which opens a new ChartDocument + * + * @see XChartDocument + */ + public XChartDocument createChartDoc() + throws com.sun.star.uno.Exception { + + XComponent oDoc = loadDocument("private:factory/schart"); + + if (oDoc != null) { + DesktopTools.bringWindowToFront(oDoc); + XChartDocument xChartDoc = UnoRuntime.queryInterface(XChartDocument.class, oDoc); + // Create a default chart which many chart tests rely on. + com.sun.star.chart2.XChartDocument xCD2 = + UnoRuntime.queryInterface(com.sun.star.chart2.XChartDocument.class, oDoc); + xCD2.createDefaultChart(); + return xChartDoc; + } else { + return null; + } + + } // finished createChartDoc + + /** + * creates a simple TextTable defaulted to 2 rows and 2 columns + */ + public static XTextTable createTextTable(XTextDocument xTextDoc) + { + + TableDsc tDsc = new TableDsc(); + InstCreator instCreate = new InstCreator(xTextDoc, tDsc); + + XTextTable oTable = (XTextTable) instCreate.getInstance(); + return oTable; + } + + /** + * creates a TextTable with a specified count of rows and columns + */ + public static XTextTable createTextTable(XTextDocument xTextDoc, + int rows, int columns) + { + + TableDsc tDsc = new TableDsc(rows, columns); + InstCreator instCreate = new InstCreator(xTextDoc, tDsc); + + XTextTable oTable = (XTextTable) instCreate.getInstance(); + return oTable; + } + + + + /** + * creates a simple TextFrame + * ... to be continued + */ + public static XTextFrame createTextFrame(XTextDocument xTextDoc, + int height, int width) { + + FrameDsc tDsc = new FrameDsc(height, width); + InstCreator instCreate = new InstCreator(xTextDoc, tDsc); + + XTextFrame oFrame = (XTextFrame) instCreate.getInstance(); + return oFrame; + } + + + + public static void insertTextContent(XTextDocument xTextDoc, + XTextContent xCont) + throws com.sun.star.lang.IllegalArgumentException { + XText xText = xTextDoc.getText(); + XText oText = UnoRuntime.queryInterface( + XText.class, xText); + + XTextCursor oCursor = oText.createTextCursor(); + oText.insertTextContent(oCursor, xCont, false); + } + + public static com.sun.star.table.XCell getFirstTableCell( + XTextContent oTable) { + + String CellNames[] = ((XTextTable) oTable).getCellNames(); + + com.sun.star.table.XCell oCell = ((XTextTable) oTable).getCellByName( + CellNames[0]); + return oCell; + + } + + /** + * the method createBookmark + */ + public static XTextContent createBookmark(XTextDocument xTextDoc) + { + + BookmarkDsc tDsc = new BookmarkDsc(); + InstCreator instCreate = new InstCreator(xTextDoc, tDsc); + + XTextContent oBookmark = (XTextContent) instCreate.getInstance(); + return oBookmark; + + } /// finish createBookmark + + + + + + /** + * the method create Index + */ + public static XTextContent createIndex(XTextDocument xTextDoc, String kind) + throws com.sun.star.uno.Exception { + + XMultiServiceFactory oDocMSF = UnoRuntime.queryInterface(XMultiServiceFactory.class, + xTextDoc); + + Object oInt = oDocMSF.createInstance(kind); + + XTextContent xTC = UnoRuntime.queryInterface(XDocumentIndex.class, oInt); + + return xTC; + + } + + public static XSpreadsheet createSpreadsheet(XSpreadsheetDocument oDoc) + throws com.sun.star.uno.Exception { + + XMultiServiceFactory oDocMSF = UnoRuntime.queryInterface(XMultiServiceFactory.class, oDoc); + + Object oInt = oDocMSF.createInstance( + "com.sun.star.sheet.Spreadsheet"); + + XSpreadsheet oSpreadsheet = UnoRuntime.queryInterface(XSpreadsheet.class, oInt); + + return oSpreadsheet; + } + + public static XIndexAccess getTableCollection(XTextDocument oDoc) { + + XTextTablesSupplier oTTS = UnoRuntime.queryInterface(XTextTablesSupplier.class, oDoc); + + XNameAccess oNA = oTTS.getTextTables(); + XIndexAccess oIA = UnoRuntime.queryInterface(XIndexAccess.class, oNA); + + return oIA; + } + + + + public XShape createShape(XComponent oDoc, int height, int width, int x, int y, String kind) { + //possible values for kind are 'Ellipse', 'Line' and 'Rectangle' + + ShapeDsc sDsc = new ShapeDsc(height, width, x, y, kind); + InstCreator instCreate = new InstCreator(oDoc, sDsc); + + XShape oShape = (XShape) instCreate.getInstance(); + + return oShape; + + } + + /** + * creates a Diagram as specified in kind + */ + public XDiagram createDiagram(XComponent oDoc, String kind) { + XInterface oInterface = null; + XDiagram oDiagram = null; + + //get LineDiagram + XMultiServiceFactory oDocMSF = UnoRuntime.queryInterface(XMultiServiceFactory.class, oDoc); + + try { + oInterface = (XInterface) oDocMSF.createInstance("com.sun.star.chart." + kind); + oDiagram = UnoRuntime.queryInterface(XDiagram.class, oInterface); + } catch (Exception e) { + // Some exception occurs.FAILED + System.out.println("Couldn't create " + kind + "-Diagram " + e); + } + return oDiagram; + } + + /** + * creates a control instance as specified in kind + */ + public XInterface createControl(XComponent oDoc, String kind) { + + XInterface oControl = null; + + XMultiServiceFactory oDocMSF = UnoRuntime.queryInterface(XMultiServiceFactory.class, oDoc); + + try { + oControl = (XInterface) oDocMSF.createInstance("com.sun.star.form.component." + kind); + } catch (Exception e) { + // Some exception occurs.FAILED + System.out.println("Couldn't create instance " + kind + ": " + e); + } + return oControl; + } + + /** + * create an Instance as specified in kind + */ + public Object createInstance(XComponent oDoc, String kind) { + + Object oInstance = null; + + XMultiServiceFactory oDocMSF = UnoRuntime.queryInterface(XMultiServiceFactory.class, oDoc); + + try { + oInstance = oDocMSF.createInstance(kind); + } catch (Exception e) { + // Some exception occurs.FAILED + System.out.println("Couldn't create instance " + kind + ": " + e); + } + return oInstance; + } + + + + public XComponent loadDocument(String fileName) + throws com.sun.star.lang.IllegalArgumentException, + com.sun.star.io.IOException, + com.sun.star.uno.Exception { + + // that noargs thing for load attributes + PropertyValue[] szEmptyArgs = new PropertyValue[0]; + String frameName = "_blank"; + + XComponent oDoc = oCLoader.loadComponentFromURL( + fileName, frameName, 0, szEmptyArgs); + + if (oDoc == null) { + return null; + } + DesktopTools.bringWindowToFront(oDoc); + return oDoc; + } + + public XComponent loadDocument(String fileName, PropertyValue[] Args) + throws com.sun.star.lang.IllegalArgumentException, + com.sun.star.io.IOException, + com.sun.star.uno.Exception { + + // that noargs thing for load attributes + String frameName = "_blank"; + + XComponent oDoc = oCLoader.loadComponentFromURL( + fileName, frameName, 0, Args); + + if (oDoc == null) { + return null; + } + DesktopTools.bringWindowToFront(oDoc); + + return oDoc; + } + + public XComponent openDoc(String kind, String frameName) + throws com.sun.star.lang.IllegalArgumentException, + com.sun.star.io.IOException, + com.sun.star.uno.Exception { + + // that noargs thing for load attributes + PropertyValue[] Args = null; + if (kind.equals("simpress")) { + Args = new PropertyValue[1]; + PropertyValue Arg = new PropertyValue(); + Arg.Name = "OpenFlags"; + Arg.Value = "S"; + Arg.Handle = -1; + Arg.State = PropertyState.DEFAULT_VALUE; + Args[0] = Arg; + } else { + Args = new PropertyValue[0]; + } + + if (frameName == null) { + frameName = "_blank"; + } + // load a blank a doc + XComponent oDoc = oCLoader.loadComponentFromURL("private:factory/" + kind, frameName, 40, Args); + DesktopTools.bringWindowToFront(oDoc); + + return oDoc; + + } // finished openDoc + + +} diff --git a/qadevOOo/runner/util/ShapeDsc.java b/qadevOOo/runner/util/ShapeDsc.java new file mode 100644 index 000000000..e47128172 --- /dev/null +++ b/qadevOOo/runner/util/ShapeDsc.java @@ -0,0 +1,97 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ + +package util; + +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.uno.XInterface; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.drawing.*; +import com.sun.star.awt.*; +/** + * the class TableDsc + */ +public class ShapeDsc extends InstDescr { + + private final int x; + private final int y; + private final int height; + private final int width; + private static final String name = null; + private static final String ifcName = "com.sun.star.drawing.XShape"; + private final String service; + + public ShapeDsc(int nheight, int nwidth, int nx, int ny, String kind) { + x = nx; + y = ny; + height = nheight; + width = nwidth; + service = "com.sun.star.drawing." + kind + "Shape"; + initShape(); + } + + @Override + public String getName() { + return name; + } + + @Override + public String getIfcName() { + return ifcName; + } + @Override + public String getService() { + return service; + } + + private void initShape() { + try { + ifcClass = Class.forName( ifcName ); + } + catch( ClassNotFoundException cnfE ) { + } + } + @Override + public XInterface createInstance( XMultiServiceFactory docMSF ) { + + + Object SrvObj = null; + try { + SrvObj = docMSF.createInstance( service ); + } + catch( com.sun.star.uno.Exception cssuE ){ + } + + XShape Sh = (XShape)UnoRuntime.queryInterface(ifcClass, SrvObj ); + Size size = new Size(); + Point position = new Point(); + size.Height = height; + size.Width = width; + position.X = x; + position.Y = y; + try { + Sh.setSize(size); + Sh.setPosition(position); + } + catch ( com.sun.star.beans.PropertyVetoException e) { + } + + return Sh; + + } +}
\ No newline at end of file diff --git a/qadevOOo/runner/util/SysUtils.java b/qadevOOo/runner/util/SysUtils.java new file mode 100644 index 000000000..2b02fd79b --- /dev/null +++ b/qadevOOo/runner/util/SysUtils.java @@ -0,0 +1,60 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ + +package util; + +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.datatransfer.clipboard.*; +import com.sun.star.datatransfer.*; + +public class SysUtils { + + /** + * Tries to obtain text data from clipboard if such one exists. + * The method iterates through all 'text/plain' supported data + * flavors and returns the first non-null String value. + * + * @param msf MultiserviceFactory + * @return First found string clipboard contents or null if no + * text contents were found. + * @throws com.sun.star.uno.Exception if system clipboard is not accessible. + */ + public static String getSysClipboardText(XMultiServiceFactory msf) + throws com.sun.star.uno.Exception { + + XClipboard xCB = UnoRuntime.queryInterface + (XClipboard.class, msf.createInstance + ("com.sun.star.datatransfer.clipboard.SystemClipboard")); + + XTransferable xTrans = xCB.getContents(); + + DataFlavor[] dfs = xTrans.getTransferDataFlavors(); + + for (int i = 0; i < dfs.length; i++) { + if (dfs[i].MimeType.startsWith("text/plain")) { + Object data = xTrans.getTransferData(dfs[i]); + if (data instanceof String) { + return (String) data; + } + } + } + + return null; + } +} diff --git a/qadevOOo/runner/util/TableDsc.java b/qadevOOo/runner/util/TableDsc.java new file mode 100644 index 000000000..3fef4ebd5 --- /dev/null +++ b/qadevOOo/runner/util/TableDsc.java @@ -0,0 +1,84 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ + +package util; + +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.uno.XInterface; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.text.XTextTable; +/** + * the class TableDsc + */ +public class TableDsc extends InstDescr { + + private int rows = 0; + private int columns = 0; + private static final String ifcName = "com.sun.star.text.XTextTable"; + private static final String service = "com.sun.star.text.TextTable"; + + public TableDsc() { + initTable(); + } + + public TableDsc( int nRows, int nColumns ) { + rows = nRows; + columns = nColumns; + initTable(); + } + + @Override + public String getName() { + return null; + } + @Override + public String getIfcName() { + return ifcName; + } + @Override + public String getService() { + return service; + } + + private void initTable() { + try { + ifcClass = Class.forName( ifcName ); + } + catch( ClassNotFoundException cnfE ) { + } + } + @Override + public XInterface createInstance( XMultiServiceFactory docMSF ) { + Object SrvObj = null; + try { + SrvObj = docMSF.createInstance( service ); + } + catch( com.sun.star.uno.Exception cssuE ){ + } + + XTextTable TT = (XTextTable)UnoRuntime.queryInterface( + ifcClass, SrvObj ); + + if ( rows > 0 && columns > 0 ) { + TT.initialize( rows, columns ); + } + + return TT; + + } +} diff --git a/qadevOOo/runner/util/TextSectionDsc.java b/qadevOOo/runner/util/TextSectionDsc.java new file mode 100644 index 000000000..3a6cce51d --- /dev/null +++ b/qadevOOo/runner/util/TextSectionDsc.java @@ -0,0 +1,72 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ + +package util; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.uno.XInterface; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.text.XTextContent; + +/** + * the class TextSectionDsc + */ +public class TextSectionDsc extends InstDescr { + + private static final String service = "com.sun.star.text.TextSection"; + private static final String ifcName = "com.sun.star.text.XTextContent"; + + public TextSectionDsc() { + initTextSection(); + } + + @Override + public String getName() { + return null; + } + + @Override + public String getIfcName() { + return ifcName; + } + + @Override + public String getService() { + return service; + } + + private void initTextSection() { + try { + ifcClass = Class.forName( ifcName ); + } + catch( ClassNotFoundException cnfE ) { + } + } + @Override + public XInterface createInstance( XMultiServiceFactory docMSF ) { + Object ServiceObj = null; + + try { + ServiceObj = docMSF.createInstance( service ); + } + catch( com.sun.star.uno.Exception cssuE ){ + } + XTextContent PG = (XTextContent)UnoRuntime.queryInterface( ifcClass, + ServiceObj ); + return PG; + } +} diff --git a/qadevOOo/runner/util/UITools.java b/qadevOOo/runner/util/UITools.java new file mode 100644 index 000000000..c9969d355 --- /dev/null +++ b/qadevOOo/runner/util/UITools.java @@ -0,0 +1,218 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ + +package util; + +import java.io.PrintWriter; +import java.util.ArrayList; + +import com.sun.star.accessibility.AccessibleRole; +import com.sun.star.accessibility.XAccessible; +import com.sun.star.accessibility.XAccessibleAction; +import com.sun.star.accessibility.XAccessibleContext; +import com.sun.star.accessibility.XAccessibleEditableText; +import com.sun.star.accessibility.XAccessibleText; +import com.sun.star.accessibility.XAccessibleValue; +import com.sun.star.awt.XWindow; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XInterface; + +/** + * This class supports some functions to handle easily accessible objects + */ +public class UITools { + + private final XAccessible mXRoot; + + public UITools(XWindow xWindow) + { + mXRoot = makeRoot(xWindow); + } + + private static String getString(XInterface xInt) + { + XAccessibleText oText = UnoRuntime.queryInterface(XAccessibleText.class, xInt); + return oText.getText(); + } + + private static void setString(XInterface xInt, String cText) + { + XAccessibleEditableText oText = UnoRuntime.queryInterface(XAccessibleEditableText.class, xInt); + + oText.setText(cText); + } + + private static XAccessible makeRoot(XWindow xWindow) + { + return AccessibilityTools.getAccessibleObject(xWindow); + } + + /** + * get the root element of the accessible tree + * @return the root element + */ + public XAccessible getRoot() + { + return mXRoot; + } + + /** + * Helper method: set a text into AccessibleEdit field + * @param textfiledName is the name of the text field + * @param stringToSet is the string to set + * @throws java.lang.Exception if something fail + */ + public void setTextEditFiledText(String textfiledName, String stringToSet) + throws java.lang.Exception + { + XInterface oTextField = AccessibilityTools.getAccessibleObjectForRole(mXRoot, + AccessibleRole.TEXT, textfiledName); + setString(oTextField, stringToSet); + } + + /** + * returns the button by the given name + * @param buttonName is the name of the button to get + * @return a XAccessibleContext of the button + * @throws java.lang.Exception if something fail + */ + public XAccessibleContext getButton(String buttonName) throws java.lang.Exception + { + return AccessibilityTools.getAccessibleObjectForRole + (mXRoot, AccessibleRole.PUSH_BUTTON, buttonName); + } + + /** + * Helper method: gets button via accessibility and 'click' it</code> + * @param buttonName is the name of the button to click + * @throws java.lang.Exception if something fail + */ + public void clickButton(String buttonName) throws java.lang.Exception + { + + XAccessibleContext oButton =AccessibilityTools.getAccessibleObjectForRole + (mXRoot, AccessibleRole.PUSH_BUTTON, buttonName); + if (oButton == null){ + throw new Exception("Could not get button '" + buttonName + "'"); + } + XAccessibleAction oAction = UnoRuntime.queryInterface(XAccessibleAction.class, oButton); + + // "click" the button + try{ + oAction.doAccessibleAction(0); + } catch (com.sun.star.lang.IndexOutOfBoundsException e) { + throw new Exception("Could not do accessible action with '" + + buttonName + "'", e); + } + } + + /** + * Helper method: returns the entry manes of a List-Box + * @param ListBoxName the name of the listbox + * @return the listbox entry names + * @throws java.lang.Exception if something fail + */ + public String[] getListBoxItems(String ListBoxName) + throws java.lang.Exception + { + ArrayList<String> Items = new ArrayList<String>(); + try { + XAccessibleContext xListBox = null; + XAccessibleContext xList = null; + + xListBox =AccessibilityTools.getAccessibleObjectForRole(mXRoot, + AccessibleRole.COMBO_BOX, ListBoxName); + if (xListBox == null){ + xListBox =AccessibilityTools.getAccessibleObjectForRole(mXRoot, + AccessibleRole.PANEL, ListBoxName); + } + + if (xListBox == null){ + // get the list of TreeListBox + xList =AccessibilityTools.getAccessibleObjectForRole(mXRoot, + AccessibleRole.TREE, ListBoxName); + + // all other list boxes have a children of kind of LIST + } else { + + XAccessible xListBoxAccess = UnoRuntime.queryInterface(XAccessible.class, xListBox); + // if a List is not pulled to be open all entries are not visible, therefore the + // boolean argument + xList =AccessibilityTools.getAccessibleObjectForRole( + xListBoxAccess, AccessibleRole.LIST, true); + } + + for (int i=0;i<xList.getAccessibleChildCount();i++) { + try { + XAccessible xChild = xList.getAccessibleChild(i); + XAccessibleContext xChildCont = + xChild.getAccessibleContext(); + XInterface xChildInterface = UnoRuntime.queryInterface(XInterface.class, xChildCont); + Items.add(getString(xChildInterface)); + + } catch (com.sun.star.lang.IndexOutOfBoundsException e) { + throw new Exception("Could not get child form list of '" + + ListBoxName + "'", e); + } + } + + } catch (Exception e) { + throw new Exception("Could not get list of items from '" + + ListBoxName + "'", e); + } + String[]ret = new String[Items.size()]; + return Items.toArray(ret); + } + + /** + * set a value to a named check box + * @param CheckBoxName the name of the check box + * @param Value the value to set + *<ul> + * <li>0: not checked </li> + * <li>1: checked </li> + * <li>2: don't know </li> + *</ul> + * @throws java.lang.Exception if something fail + */ + public void setCheckBoxValue(String CheckBoxName, Integer Value) + throws java.lang.Exception + { + try { + XInterface xCheckBox =AccessibilityTools.getAccessibleObjectForRole(mXRoot, + AccessibleRole.CHECK_BOX, CheckBoxName); + XAccessibleValue xCheckBoxValue = UnoRuntime.queryInterface(XAccessibleValue.class, xCheckBox); + xCheckBoxValue.setCurrentValue(Value); + + } catch (Exception e) { + throw new Exception("Could not set value to CheckBox '" + + CheckBoxName + "'", e); + } + } + + /** + * Prints the accessible tree to the <CODE>logWriter</CODE> only if <CODE>debugIsActive</CODE> + * is set to <CODE>true</CODE> + * @param log logWriter + * @param debugIsActive prints only if this parameter is set to TRUE + */ + public void printAccessibleTree(PrintWriter log, boolean debugIsActive) { + AccessibilityTools.printAccessibleTree(log, mXRoot, debugIsActive); + } + +} diff --git a/qadevOOo/runner/util/ValueChanger.java b/qadevOOo/runner/util/ValueChanger.java new file mode 100644 index 000000000..8a6c51936 --- /dev/null +++ b/qadevOOo/runner/util/ValueChanger.java @@ -0,0 +1,1102 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ + +package util; + +import com.sun.star.awt.Point; +import com.sun.star.beans.PropertyValue; +import com.sun.star.drawing.PolygonFlags; +import com.sun.star.uno.Enum; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.lang.reflect.Array; +import com.sun.star.uno.Any; +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.Type; + +public class ValueChanger { + + // Method to change a Value, thought for properties + public static Object changePValue(Object oldValue, String name) { + + Object newValue = null; + + if (oldValue instanceof com.sun.star.uno.Any) { + try { + oldValue = AnyConverter.toObject(((Any) oldValue).getType(), + oldValue); + } catch (com.sun.star.lang.IllegalArgumentException iae) { + } + } + + if (oldValue == null) + return null; + + if (oldValue instanceof Boolean) { + boolean oldbool = ((Boolean) oldValue).booleanValue(); + newValue = Boolean.valueOf(!oldbool); + } else if (oldValue instanceof Integer) { + int oldint = ((Integer) oldValue).intValue(); + newValue = Integer.valueOf(oldint + 5); + } else if (oldValue instanceof Long) { + long oldlong = ((Long) oldValue).longValue(); + newValue = Long.valueOf(oldlong + 15); + } else if (oldValue instanceof Short) { + short n = ((Short) oldValue).shortValue(); + if ("DefaultState".equals(name) && n == 2) { + // css.form.component.{CheckBox,RadioButton} DefaultState + // properties must have values in the range 0--2: + --n; + } else if ("LinkUpdateMode".equals(name) && n >= 2) { + // css.document.Settings LinkUpdateMode property must have + // values in the css.document.LinkUpdateModes range (0--3), + // while css.sheet.XGlobalSheetSettings LinkUpdateMode property + // must have values in the range 0--2: + --n; + } else { + ++n; + } + newValue = Short.valueOf(n); + } else if (oldValue instanceof Byte) { + byte oldbyte = ((Byte) oldValue).byteValue(); + newValue = Byte.valueOf((byte) (oldbyte + 1)); + } else if (oldValue instanceof Float) { + float oldfloat = ((Float) oldValue).floatValue(); + newValue = new Float((float) (oldfloat + 16.7)); + } else if (oldValue instanceof Double) { + double olddouble = ((Double) oldValue).doubleValue(); + newValue = new Double(olddouble + 17.8); + } else if (oldValue instanceof String) { + String oldString = (String) oldValue; + newValue = oldString + "New"; + } else if (oldValue instanceof com.sun.star.chart.ChartAxisArrangeOrderType) { + Object AO1 = com.sun.star.chart.ChartAxisArrangeOrderType.AUTO; + Object AO2 = com.sun.star.chart.ChartAxisArrangeOrderType.SIDE_BY_SIDE; + Object AO3 = com.sun.star.chart.ChartAxisArrangeOrderType.STAGGER_EVEN; + Object AO4 = com.sun.star.chart.ChartAxisArrangeOrderType.STAGGER_ODD; + + if (oldValue.equals(AO1)) + newValue = AO2; + if (oldValue.equals(AO2)) + newValue = AO3; + if (oldValue.equals(AO3)) + newValue = AO4; + if (oldValue.equals(AO4)) + newValue = AO1; + } else if (oldValue instanceof com.sun.star.view.PaperOrientation) { + Object OR1 = com.sun.star.view.PaperOrientation.LANDSCAPE; + Object OR2 = com.sun.star.view.PaperOrientation.PORTRAIT; + + if (oldValue.equals(OR1)) + newValue = OR2; + else + newValue = OR1; + } else if (oldValue instanceof com.sun.star.lang.Locale) { + com.sun.star.lang.Locale Loc1 = new com.sun.star.lang.Locale( + "en", "US", ""); + com.sun.star.lang.Locale Loc2 = new com.sun.star.lang.Locale( + "de", "DE", ""); + com.sun.star.lang.Locale old = (com.sun.star.lang.Locale) oldValue; + if (old.Language.equals(Loc1.Language) + && old.Country.equals(Loc1.Country) + && old.Variant.equals(Loc1.Variant)) + newValue = Loc2; + else + newValue = Loc1; + } else if (oldValue instanceof com.sun.star.style.ParagraphAdjust) { + Object PA1 = com.sun.star.style.ParagraphAdjust.LEFT; + Object PA2 = com.sun.star.style.ParagraphAdjust.CENTER; + + if (oldValue.equals(PA1)) + newValue = PA2; + else + newValue = PA1; + } else if (oldValue instanceof com.sun.star.style.LineSpacing) { + com.sun.star.style.LineSpacing LS = new com.sun.star.style.LineSpacing(); + com.sun.star.style.LineSpacing LSold = (com.sun.star.style.LineSpacing) oldValue; + LS.Height = (short) ((LSold.Height) + 1); + LS.Mode = (short) ((LSold.Mode) + 1); + newValue = LS; + } else if (oldValue instanceof com.sun.star.drawing.Direction3D) { + com.sun.star.drawing.Direction3D D3D = new com.sun.star.drawing.Direction3D(); + com.sun.star.drawing.Direction3D D3Dold = (com.sun.star.drawing.Direction3D) oldValue; + D3D.DirectionX = D3Dold.DirectionX + .5; + D3D.DirectionY = D3Dold.DirectionY + .5; + D3D.DirectionZ = D3Dold.DirectionZ + .5; + newValue = D3D; + } else if (oldValue instanceof com.sun.star.style.GraphicLocation) { + Object GL1 = com.sun.star.style.GraphicLocation.AREA; + Object GL2 = com.sun.star.style.GraphicLocation.LEFT_BOTTOM; + + if (oldValue.equals(GL1)) + newValue = GL2; + else + newValue = GL1; + } else if (oldValue instanceof com.sun.star.style.TabStop) { + com.sun.star.style.TabStop TS = new com.sun.star.style.TabStop(); + com.sun.star.style.TabStop TSold = (com.sun.star.style.TabStop) oldValue; + com.sun.star.style.TabAlign TA1 = com.sun.star.style.TabAlign.CENTER; + com.sun.star.style.TabAlign TA2 = com.sun.star.style.TabAlign.RIGHT; + + if (TSold.Alignment.equals(TA1)) + TS.Alignment = TA2; + else + TS.Alignment = TA1; + + TS.Position = ((TSold.Position) + 1); + + newValue = TS; + } else if (oldValue instanceof com.sun.star.style.DropCapFormat) { + com.sun.star.style.DropCapFormat DCF = new com.sun.star.style.DropCapFormat(); + com.sun.star.style.DropCapFormat DCFold = (com.sun.star.style.DropCapFormat) oldValue; + DCF.Count = (byte) ((DCFold.Count) + 1); + DCF.Distance = (short) ((DCFold.Distance) + 1); + DCF.Lines = (byte) ((DCFold.Lines) + 1); + newValue = DCF; + } else if (oldValue instanceof com.sun.star.text.TextContentAnchorType) { + com.sun.star.text.TextContentAnchorType TCAT1 = com.sun.star.text.TextContentAnchorType.AS_CHARACTER; + com.sun.star.text.TextContentAnchorType TCAT2 = com.sun.star.text.TextContentAnchorType.AT_CHARACTER; + com.sun.star.text.TextContentAnchorType TCAT3 = com.sun.star.text.TextContentAnchorType.AT_FRAME; + com.sun.star.text.TextContentAnchorType TCAT4 = com.sun.star.text.TextContentAnchorType.AT_PAGE; + com.sun.star.text.TextContentAnchorType TCAT5 = com.sun.star.text.TextContentAnchorType.AT_PARAGRAPH; + if (oldValue.equals(TCAT1)) + newValue = TCAT2; + if (oldValue.equals(TCAT2)) + newValue = TCAT3; + if (oldValue.equals(TCAT3)) + newValue = TCAT4; + if (oldValue.equals(TCAT4)) + newValue = TCAT5; + if (oldValue.equals(TCAT5)) + newValue = TCAT1; + } else if (oldValue instanceof com.sun.star.text.WrapTextMode) { + com.sun.star.text.WrapTextMode WTM1 = com.sun.star.text.WrapTextMode.DYNAMIC; + com.sun.star.text.WrapTextMode WTM2 = com.sun.star.text.WrapTextMode.LEFT; + com.sun.star.text.WrapTextMode WTM3 = com.sun.star.text.WrapTextMode.NONE; + com.sun.star.text.WrapTextMode WTM4 = com.sun.star.text.WrapTextMode.PARALLEL; + com.sun.star.text.WrapTextMode WTM5 = com.sun.star.text.WrapTextMode.RIGHT; + com.sun.star.text.WrapTextMode WTM6 = com.sun.star.text.WrapTextMode.THROUGH; + if (oldValue.equals(WTM1)) + newValue = WTM2; + if (oldValue.equals(WTM2)) + newValue = WTM3; + if (oldValue.equals(WTM3)) + newValue = WTM4; + if (oldValue.equals(WTM4)) + newValue = WTM5; + if (oldValue.equals(WTM5)) + newValue = WTM6; + if (oldValue.equals(WTM6)) + newValue = WTM1; + } else if (oldValue instanceof com.sun.star.awt.Size) { + com.sun.star.awt.Size oldSize = (com.sun.star.awt.Size) oldValue; + com.sun.star.awt.Size newSize = new com.sun.star.awt.Size(); + newSize.Height = oldSize.Height + 1; + newSize.Width = oldSize.Width + 1; + newValue = newSize; + } else if (oldValue instanceof com.sun.star.awt.Rectangle) { + com.sun.star.awt.Rectangle oldRectangle = (com.sun.star.awt.Rectangle) oldValue; + com.sun.star.awt.Rectangle newRectangle = new com.sun.star.awt.Rectangle(); + newRectangle.Height = oldRectangle.Height + 1; + newRectangle.Width = oldRectangle.Width + 1; + newRectangle.X = oldRectangle.Y + 1; + newRectangle.Y = oldRectangle.X + 1; + newValue = newRectangle; + } else if (oldValue instanceof com.sun.star.awt.Point) { + com.sun.star.awt.Point oldPoint = (com.sun.star.awt.Point) oldValue; + com.sun.star.awt.Point newPoint = new com.sun.star.awt.Point(); + newPoint.X = oldPoint.X + 1; + newPoint.Y = oldPoint.Y + 1; + newValue = newPoint; + } else if (oldValue instanceof com.sun.star.table.ShadowFormat) { + com.sun.star.table.ShadowFormat SF = new com.sun.star.table.ShadowFormat(); + com.sun.star.table.ShadowFormat SFold = (com.sun.star.table.ShadowFormat) oldValue; + SF.IsTransparent = (!SFold.IsTransparent); + SF.ShadowWidth = (short) ((SFold.ShadowWidth) + 1); + newValue = SF; + } else if (oldValue instanceof com.sun.star.awt.FontSlant) { + com.sun.star.awt.FontSlant FS1 = com.sun.star.awt.FontSlant.DONTKNOW; + com.sun.star.awt.FontSlant FS2 = com.sun.star.awt.FontSlant.ITALIC; + com.sun.star.awt.FontSlant FS3 = com.sun.star.awt.FontSlant.NONE; + com.sun.star.awt.FontSlant FS4 = com.sun.star.awt.FontSlant.OBLIQUE; + com.sun.star.awt.FontSlant FS5 = com.sun.star.awt.FontSlant.REVERSE_ITALIC; + com.sun.star.awt.FontSlant FS6 = com.sun.star.awt.FontSlant.REVERSE_OBLIQUE; + if (oldValue.equals(FS1)) + newValue = FS2; + if (oldValue.equals(FS2)) + newValue = FS3; + if (oldValue.equals(FS3)) + newValue = FS4; + if (oldValue.equals(FS4)) + newValue = FS5; + if (oldValue.equals(FS5)) + newValue = FS6; + if (oldValue.equals(FS6)) + newValue = FS1; + } else if (oldValue instanceof com.sun.star.table.CellHoriJustify) { + com.sun.star.table.CellHoriJustify CHJ1 = com.sun.star.table.CellHoriJustify.BLOCK; + com.sun.star.table.CellHoriJustify CHJ2 = com.sun.star.table.CellHoriJustify.CENTER; + com.sun.star.table.CellHoriJustify CHJ3 = com.sun.star.table.CellHoriJustify.LEFT; + com.sun.star.table.CellHoriJustify CHJ4 = com.sun.star.table.CellHoriJustify.REPEAT; + com.sun.star.table.CellHoriJustify CHJ5 = com.sun.star.table.CellHoriJustify.RIGHT; + com.sun.star.table.CellHoriJustify CHJ6 = com.sun.star.table.CellHoriJustify.STANDARD; + if (oldValue.equals(CHJ1)) + newValue = CHJ2; + if (oldValue.equals(CHJ2)) + newValue = CHJ3; + if (oldValue.equals(CHJ3)) + newValue = CHJ4; + if (oldValue.equals(CHJ4)) + newValue = CHJ5; + if (oldValue.equals(CHJ5)) + newValue = CHJ6; + if (oldValue.equals(CHJ6)) + newValue = CHJ1; + } else if (oldValue instanceof com.sun.star.table.CellVertJustify) { + com.sun.star.table.CellVertJustify CVJ1 = com.sun.star.table.CellVertJustify.BOTTOM; + com.sun.star.table.CellVertJustify CVJ2 = com.sun.star.table.CellVertJustify.CENTER; + com.sun.star.table.CellVertJustify CVJ3 = com.sun.star.table.CellVertJustify.STANDARD; + com.sun.star.table.CellVertJustify CVJ4 = com.sun.star.table.CellVertJustify.TOP; + if (oldValue.equals(CVJ1)) + newValue = CVJ2; + if (oldValue.equals(CVJ2)) + newValue = CVJ3; + if (oldValue.equals(CVJ3)) + newValue = CVJ4; + if (oldValue.equals(CVJ4)) + newValue = CVJ1; + } else if (oldValue instanceof com.sun.star.table.CellOrientation) { + com.sun.star.table.CellOrientation CO1 = com.sun.star.table.CellOrientation.BOTTOMTOP; + com.sun.star.table.CellOrientation CO2 = com.sun.star.table.CellOrientation.STACKED; + com.sun.star.table.CellOrientation CO3 = com.sun.star.table.CellOrientation.STANDARD; + com.sun.star.table.CellOrientation CO4 = com.sun.star.table.CellOrientation.TOPBOTTOM; + if (oldValue.equals(CO1)) + newValue = CO2; + if (oldValue.equals(CO2)) + newValue = CO3; + if (oldValue.equals(CO3)) + newValue = CO4; + if (oldValue.equals(CO4)) + newValue = CO1; + } else if (oldValue instanceof com.sun.star.util.CellProtection) { + com.sun.star.util.CellProtection CP = new com.sun.star.util.CellProtection(); + com.sun.star.util.CellProtection CPold = (com.sun.star.util.CellProtection) oldValue; + CP.IsFormulaHidden = (!CPold.IsFormulaHidden); + CP.IsHidden = (!CPold.IsHidden); + CP.IsLocked = (!CPold.IsLocked); + CP.IsPrintHidden = (!CPold.IsPrintHidden); + newValue = CP; + } else if (oldValue instanceof com.sun.star.table.TableBorder) { + com.sun.star.table.TableBorder TBold = (com.sun.star.table.TableBorder) oldValue; + com.sun.star.table.TableBorder TB = new com.sun.star.table.TableBorder(); + TB.IsBottomLineValid = (!TBold.IsBottomLineValid); + TB.IsDistanceValid = (!TBold.IsDistanceValid); + TB.IsRightLineValid = (!TBold.IsRightLineValid); + TB.IsTopLineValid = (!TBold.IsTopLineValid); + newValue = TB; + } else if (oldValue instanceof com.sun.star.drawing.FillStyle) { + /* + * if (oldValue instanceof com.sun.star.awt.XBitmap) { newValue = + * new BitmapLoader(); } + */ + com.sun.star.drawing.FillStyle FS1 = com.sun.star.drawing.FillStyle.NONE; + com.sun.star.drawing.FillStyle FS2 = com.sun.star.drawing.FillStyle.SOLID; + com.sun.star.drawing.FillStyle FS3 = com.sun.star.drawing.FillStyle.GRADIENT; + com.sun.star.drawing.FillStyle FS4 = com.sun.star.drawing.FillStyle.HATCH; + com.sun.star.drawing.FillStyle FS5 = com.sun.star.drawing.FillStyle.BITMAP; + if (oldValue.equals(FS1)) + newValue = FS2; + if (oldValue.equals(FS2)) + newValue = FS3; + if (oldValue.equals(FS3)) + newValue = FS4; + if (oldValue.equals(FS4)) + newValue = FS5; + if (oldValue.equals(FS5)) + newValue = FS1; + } else if (oldValue instanceof com.sun.star.awt.Gradient) { + com.sun.star.awt.Gradient _newValue = copyStruct( + (com.sun.star.awt.Gradient) oldValue); + _newValue.Angle += 10; + _newValue.Border += 1; + _newValue.EndColor += 1000; + _newValue.EndIntensity -= 10; + _newValue.StartColor += 500; + _newValue.StartIntensity += 10; + _newValue.StepCount += 50; + _newValue.Style = com.sun.star.awt.GradientStyle.RADIAL; + _newValue.XOffset += 10; + _newValue.YOffset += 10; + newValue = _newValue; + } else if (oldValue instanceof com.sun.star.text.GraphicCrop) { + com.sun.star.text.GraphicCrop _newValue = copyStruct( + (com.sun.star.text.GraphicCrop) oldValue); + _newValue.Bottom += 10; + _newValue.Left += 10; + _newValue.Right += 10; + _newValue.Top += 10; + newValue = _newValue; + } else if (oldValue instanceof com.sun.star.drawing.BitmapMode) { + com.sun.star.drawing.BitmapMode bm1 = com.sun.star.drawing.BitmapMode.NO_REPEAT; + com.sun.star.drawing.BitmapMode bm2 = com.sun.star.drawing.BitmapMode.REPEAT; + com.sun.star.drawing.BitmapMode bm3 = com.sun.star.drawing.BitmapMode.STRETCH; + if (oldValue.equals(bm1)) + newValue = bm2; + if (oldValue.equals(bm2)) + newValue = bm3; + if (oldValue.equals(bm3)) + newValue = bm1; + } else if (oldValue instanceof com.sun.star.drawing.TextAdjust) { + com.sun.star.drawing.TextAdjust TA1 = com.sun.star.drawing.TextAdjust.BLOCK; + com.sun.star.drawing.TextAdjust TA2 = com.sun.star.drawing.TextAdjust.CENTER; + com.sun.star.drawing.TextAdjust TA3 = com.sun.star.drawing.TextAdjust.LEFT; + com.sun.star.drawing.TextAdjust TA4 = com.sun.star.drawing.TextAdjust.RIGHT; + com.sun.star.drawing.TextAdjust TA5 = com.sun.star.drawing.TextAdjust.STRETCH; + if (oldValue.equals(TA1)) + newValue = TA2; + if (oldValue.equals(TA2)) + newValue = TA3; + if (oldValue.equals(TA3)) + newValue = TA4; + if (oldValue.equals(TA4)) + newValue = TA5; + if (oldValue.equals(TA5)) + newValue = TA1; + } else if (oldValue instanceof com.sun.star.drawing.TextFitToSizeType) { + com.sun.star.drawing.TextFitToSizeType TF1 = com.sun.star.drawing.TextFitToSizeType.ALLLINES; + com.sun.star.drawing.TextFitToSizeType TF2 = com.sun.star.drawing.TextFitToSizeType.NONE; + com.sun.star.drawing.TextFitToSizeType TF3 = com.sun.star.drawing.TextFitToSizeType.PROPORTIONAL; + com.sun.star.drawing.TextFitToSizeType TF4 = com.sun.star.drawing.TextFitToSizeType.AUTOFIT; + if (oldValue.equals(TF1)) + newValue = TF2; + if (oldValue.equals(TF2)) + newValue = TF3; + if (oldValue.equals(TF3)) + newValue = TF4; + if (oldValue.equals(TF4)) + newValue = TF1; + } else if (oldValue instanceof com.sun.star.drawing.TextAnimationKind) { + com.sun.star.drawing.TextAnimationKind AK1 = com.sun.star.drawing.TextAnimationKind.NONE; + com.sun.star.drawing.TextAnimationKind AK2 = com.sun.star.drawing.TextAnimationKind.SLIDE; + com.sun.star.drawing.TextAnimationKind AK3 = com.sun.star.drawing.TextAnimationKind.SCROLL; + com.sun.star.drawing.TextAnimationKind AK4 = com.sun.star.drawing.TextAnimationKind.BLINK; + com.sun.star.drawing.TextAnimationKind AK5 = com.sun.star.drawing.TextAnimationKind.ALTERNATE; + + if (oldValue.equals(AK1)) + newValue = AK2; + if (oldValue.equals(AK2)) + newValue = AK3; + if (oldValue.equals(AK3)) + newValue = AK4; + if (oldValue.equals(AK4)) + newValue = AK5; + if (oldValue.equals(AK5)) + newValue = AK1; + } else if (oldValue instanceof com.sun.star.drawing.TextAnimationDirection) { + com.sun.star.drawing.TextAnimationDirection AD1 = com.sun.star.drawing.TextAnimationDirection.LEFT; + com.sun.star.drawing.TextAnimationDirection AD2 = com.sun.star.drawing.TextAnimationDirection.RIGHT; + com.sun.star.drawing.TextAnimationDirection AD3 = com.sun.star.drawing.TextAnimationDirection.DOWN; + com.sun.star.drawing.TextAnimationDirection AD4 = com.sun.star.drawing.TextAnimationDirection.UP; + if (oldValue.equals(AD1)) + newValue = AD2; + if (oldValue.equals(AD2)) + newValue = AD3; + if (oldValue.equals(AD3)) + newValue = AD4; + if (oldValue.equals(AD4)) + newValue = AD1; + } else if (oldValue instanceof com.sun.star.drawing.LineStyle) { + com.sun.star.drawing.LineStyle LS1 = com.sun.star.drawing.LineStyle.NONE; + com.sun.star.drawing.LineStyle LS2 = com.sun.star.drawing.LineStyle.DASH; + com.sun.star.drawing.LineStyle LS3 = com.sun.star.drawing.LineStyle.SOLID; + if (oldValue.equals(LS1)) + newValue = LS2; + if (oldValue.equals(LS2)) + newValue = LS3; + if (oldValue.equals(LS3)) + newValue = LS1; + } else if (oldValue instanceof com.sun.star.drawing.LineJoint) { + com.sun.star.drawing.LineJoint LJ1 = com.sun.star.drawing.LineJoint.BEVEL; + com.sun.star.drawing.LineJoint LJ2 = com.sun.star.drawing.LineJoint.MIDDLE; + com.sun.star.drawing.LineJoint LJ3 = com.sun.star.drawing.LineJoint.MITER; + com.sun.star.drawing.LineJoint LJ4 = com.sun.star.drawing.LineJoint.NONE; + com.sun.star.drawing.LineJoint LJ5 = com.sun.star.drawing.LineJoint.ROUND; + if (oldValue.equals(LJ1)) + newValue = LJ2; + if (oldValue.equals(LJ2)) + newValue = LJ3; + if (oldValue.equals(LJ3)) + newValue = LJ4; + if (oldValue.equals(LJ4)) + newValue = LJ5; + if (oldValue.equals(LJ5)) + newValue = LJ1; + } else if (oldValue instanceof com.sun.star.drawing.LineDash) { + com.sun.star.drawing.LineDash _newValue = copyStruct( + (com.sun.star.drawing.LineDash) oldValue); + _newValue.Dashes += 1; + _newValue.DashLen += 10; + _newValue.Distance += 20; + _newValue.DotLen += 10; + _newValue.Dots += 10; + _newValue.Style = com.sun.star.drawing.DashStyle.RECT; + newValue = _newValue; + } else if (oldValue instanceof com.sun.star.drawing.Hatch) { + com.sun.star.drawing.Hatch _newValue = copyStruct( + (com.sun.star.drawing.Hatch) oldValue); + _newValue.Angle += 10; + _newValue.Color += 1000; + _newValue.Distance += 10; + _newValue.Style = com.sun.star.drawing.HatchStyle.DOUBLE; + } else if (oldValue instanceof com.sun.star.drawing.RectanglePoint) { + com.sun.star.drawing.RectanglePoint RP1 = com.sun.star.drawing.RectanglePoint.LEFT_BOTTOM; + com.sun.star.drawing.RectanglePoint RP2 = com.sun.star.drawing.RectanglePoint.LEFT_MIDDLE; + com.sun.star.drawing.RectanglePoint RP3 = com.sun.star.drawing.RectanglePoint.LEFT_TOP; + com.sun.star.drawing.RectanglePoint RP4 = com.sun.star.drawing.RectanglePoint.MIDDLE_BOTTOM; + com.sun.star.drawing.RectanglePoint RP5 = com.sun.star.drawing.RectanglePoint.MIDDLE_MIDDLE; + com.sun.star.drawing.RectanglePoint RP6 = com.sun.star.drawing.RectanglePoint.MIDDLE_TOP; + com.sun.star.drawing.RectanglePoint RP7 = com.sun.star.drawing.RectanglePoint.RIGHT_BOTTOM; + com.sun.star.drawing.RectanglePoint RP8 = com.sun.star.drawing.RectanglePoint.RIGHT_MIDDLE; + com.sun.star.drawing.RectanglePoint RP9 = com.sun.star.drawing.RectanglePoint.RIGHT_TOP; + + if (oldValue.equals(RP1)) + newValue = RP2; + if (oldValue.equals(RP2)) + newValue = RP3; + if (oldValue.equals(RP3)) + newValue = RP4; + if (oldValue.equals(RP4)) + newValue = RP5; + if (oldValue.equals(RP5)) + newValue = RP6; + if (oldValue.equals(RP6)) + newValue = RP7; + if (oldValue.equals(RP7)) + newValue = RP8; + if (oldValue.equals(RP8)) + newValue = RP9; + if (oldValue.equals(RP9)) + newValue = RP1; + + } else if (oldValue instanceof com.sun.star.chart.ChartErrorCategory) { + com.sun.star.chart.ChartErrorCategory CC1 = com.sun.star.chart.ChartErrorCategory.CONSTANT_VALUE; + com.sun.star.chart.ChartErrorCategory CC2 = com.sun.star.chart.ChartErrorCategory.ERROR_MARGIN; + com.sun.star.chart.ChartErrorCategory CC3 = com.sun.star.chart.ChartErrorCategory.NONE; + com.sun.star.chart.ChartErrorCategory CC4 = com.sun.star.chart.ChartErrorCategory.PERCENT; + com.sun.star.chart.ChartErrorCategory CC5 = com.sun.star.chart.ChartErrorCategory.STANDARD_DEVIATION; + com.sun.star.chart.ChartErrorCategory CC6 = com.sun.star.chart.ChartErrorCategory.VARIANCE; + if (oldValue.equals(CC1)) + newValue = CC2; + if (oldValue.equals(CC2)) + newValue = CC3; + if (oldValue.equals(CC3)) + newValue = CC4; + if (oldValue.equals(CC4)) + newValue = CC5; + if (oldValue.equals(CC5)) + newValue = CC6; + if (oldValue.equals(CC6)) + newValue = CC1; + } else if (oldValue instanceof com.sun.star.chart.ChartErrorIndicatorType) { + com.sun.star.chart.ChartErrorIndicatorType IT1 = com.sun.star.chart.ChartErrorIndicatorType.LOWER; + com.sun.star.chart.ChartErrorIndicatorType IT2 = com.sun.star.chart.ChartErrorIndicatorType.NONE; + com.sun.star.chart.ChartErrorIndicatorType IT3 = com.sun.star.chart.ChartErrorIndicatorType.TOP_AND_BOTTOM; + com.sun.star.chart.ChartErrorIndicatorType IT4 = com.sun.star.chart.ChartErrorIndicatorType.UPPER; + if (oldValue.equals(IT1)) + newValue = IT2; + if (oldValue.equals(IT2)) + newValue = IT3; + if (oldValue.equals(IT3)) + newValue = IT4; + if (oldValue.equals(IT4)) + newValue = IT1; + } else if (oldValue instanceof com.sun.star.chart.ChartRegressionCurveType) { + com.sun.star.chart.ChartRegressionCurveType CT1 = com.sun.star.chart.ChartRegressionCurveType.EXPONENTIAL; + com.sun.star.chart.ChartRegressionCurveType CT2 = com.sun.star.chart.ChartRegressionCurveType.LINEAR; + com.sun.star.chart.ChartRegressionCurveType CT3 = com.sun.star.chart.ChartRegressionCurveType.LOGARITHM; + com.sun.star.chart.ChartRegressionCurveType CT4 = com.sun.star.chart.ChartRegressionCurveType.NONE; + com.sun.star.chart.ChartRegressionCurveType CT5 = com.sun.star.chart.ChartRegressionCurveType.POLYNOMIAL; + com.sun.star.chart.ChartRegressionCurveType CT6 = com.sun.star.chart.ChartRegressionCurveType.POWER; + if (oldValue.equals(CT1)) + newValue = CT2; + if (oldValue.equals(CT2)) + newValue = CT3; + if (oldValue.equals(CT3)) + newValue = CT4; + if (oldValue.equals(CT4)) + newValue = CT5; + if (oldValue.equals(CT5)) + newValue = CT6; + if (oldValue.equals(CT6)) + newValue = CT1; + + } else if (oldValue instanceof com.sun.star.chart.ChartDataRowSource) { + com.sun.star.chart.ChartDataRowSource RS1 = com.sun.star.chart.ChartDataRowSource.COLUMNS; + com.sun.star.chart.ChartDataRowSource RS2 = com.sun.star.chart.ChartDataRowSource.ROWS; + if (oldValue.equals(RS1)) + newValue = RS2; + if (oldValue.equals(RS2)) + newValue = RS1; + } else if (oldValue instanceof com.sun.star.awt.FontDescriptor) { + com.sun.star.awt.FontDescriptor _newValue = copyStruct( + (com.sun.star.awt.FontDescriptor) oldValue); + _newValue.CharacterWidth += 5; + _newValue.CharSet = com.sun.star.awt.CharSet.ANSI; + _newValue.Family = com.sun.star.awt.FontFamily.DECORATIVE; + _newValue.Height += 2; + _newValue.Kerning = !_newValue.Kerning; + _newValue.Name = "Courier"; + _newValue.Orientation += 45; + _newValue.Pitch = com.sun.star.awt.FontPitch.VARIABLE; + _newValue.Slant = com.sun.star.awt.FontSlant.REVERSE_ITALIC; + _newValue.Strikeout = com.sun.star.awt.FontStrikeout.X; + _newValue.StyleName = "Bold"; + _newValue.Type = com.sun.star.awt.FontType.SCALABLE; + _newValue.Underline = com.sun.star.awt.FontUnderline.BOLDDASHDOTDOT; + _newValue.Weight += 5; + _newValue.Width += 6; + _newValue.WordLineMode = !_newValue.WordLineMode; + + newValue = _newValue; + } else if (oldValue instanceof com.sun.star.form.NavigationBarMode) { + com.sun.star.form.NavigationBarMode BM1 = com.sun.star.form.NavigationBarMode.CURRENT; + com.sun.star.form.NavigationBarMode BM2 = com.sun.star.form.NavigationBarMode.NONE; + com.sun.star.form.NavigationBarMode BM3 = com.sun.star.form.NavigationBarMode.PARENT; + if (oldValue.equals(BM1)) + newValue = BM2; + if (oldValue.equals(BM2)) + newValue = BM3; + if (oldValue.equals(BM3)) + newValue = BM1; + } else if (oldValue instanceof com.sun.star.form.FormSubmitEncoding) { + com.sun.star.form.FormSubmitEncoding SE1 = com.sun.star.form.FormSubmitEncoding.MULTIPART; + com.sun.star.form.FormSubmitEncoding SE2 = com.sun.star.form.FormSubmitEncoding.TEXT; + com.sun.star.form.FormSubmitEncoding SE3 = com.sun.star.form.FormSubmitEncoding.URL; + if (oldValue.equals(SE1)) + newValue = SE2; + if (oldValue.equals(SE2)) + newValue = SE3; + if (oldValue.equals(SE3)) + newValue = SE1; + } else if (oldValue instanceof com.sun.star.form.FormSubmitMethod) { + com.sun.star.form.FormSubmitMethod FM1 = com.sun.star.form.FormSubmitMethod.GET; + com.sun.star.form.FormSubmitMethod FM2 = com.sun.star.form.FormSubmitMethod.POST; + if (oldValue.equals(FM1)) + newValue = FM2; + if (oldValue.equals(FM2)) + newValue = FM1; + } else if (oldValue instanceof com.sun.star.text.SectionFileLink) { + com.sun.star.text.SectionFileLink _newValue = new com.sun.star.text.SectionFileLink(); + + _newValue.FileURL = util.utils.getFullTestURL("SwXTextSection.sdw"); + newValue = _newValue; + } else if (oldValue instanceof com.sun.star.table.BorderLine) { + com.sun.star.table.BorderLine _newValue = copyStruct( + (com.sun.star.table.BorderLine) oldValue); + _newValue.Color += 2; + _newValue.InnerLineWidth += 2; + _newValue.LineDistance += 2; + _newValue.OuterLineWidth += 3; + if (_newValue instanceof com.sun.star.table.BorderLine2) { + ((com.sun.star.table.BorderLine2) _newValue).LineStyle + = com.sun.star.table.BorderLineStyle.DOUBLE; + } + newValue = _newValue; + } else if (oldValue instanceof com.sun.star.text.XTextColumns) { + com.sun.star.text.XTextColumns _newValue = (com.sun.star.text.XTextColumns) oldValue; + _newValue.setColumnCount((short) 1); + newValue = _newValue; + } else if (oldValue instanceof com.sun.star.form.FormButtonType) { + com.sun.star.form.FormButtonType BT1 = com.sun.star.form.FormButtonType.PUSH; + com.sun.star.form.FormButtonType BT2 = com.sun.star.form.FormButtonType.RESET; + com.sun.star.form.FormButtonType BT3 = com.sun.star.form.FormButtonType.SUBMIT; + com.sun.star.form.FormButtonType BT4 = com.sun.star.form.FormButtonType.URL; + + if (oldValue.equals(BT1)) + newValue = BT2; + if (oldValue.equals(BT2)) + newValue = BT3; + if (oldValue.equals(BT3)) + newValue = BT4; + if (oldValue.equals(BT4)) + newValue = BT1; + + } else if (oldValue instanceof com.sun.star.form.ListSourceType) { + com.sun.star.form.ListSourceType ST1 = com.sun.star.form.ListSourceType.QUERY; + com.sun.star.form.ListSourceType ST2 = com.sun.star.form.ListSourceType.SQL; + com.sun.star.form.ListSourceType ST3 = com.sun.star.form.ListSourceType.SQLPASSTHROUGH; + com.sun.star.form.ListSourceType ST4 = com.sun.star.form.ListSourceType.TABLE; + com.sun.star.form.ListSourceType ST5 = com.sun.star.form.ListSourceType.TABLEFIELDS; + com.sun.star.form.ListSourceType ST6 = com.sun.star.form.ListSourceType.VALUELIST; + if (oldValue.equals(ST1)) + newValue = ST2; + if (oldValue.equals(ST2)) + newValue = ST3; + if (oldValue.equals(ST3)) + newValue = ST4; + if (oldValue.equals(ST4)) + newValue = ST5; + if (oldValue.equals(ST5)) + newValue = ST6; + if (oldValue.equals(ST6)) + newValue = ST1; + } else if (oldValue instanceof com.sun.star.sheet.DataPilotFieldOrientation) { + com.sun.star.sheet.DataPilotFieldOrientation FO1 = com.sun.star.sheet.DataPilotFieldOrientation.PAGE; + com.sun.star.sheet.DataPilotFieldOrientation FO2 = com.sun.star.sheet.DataPilotFieldOrientation.COLUMN; + com.sun.star.sheet.DataPilotFieldOrientation FO3 = com.sun.star.sheet.DataPilotFieldOrientation.DATA; + com.sun.star.sheet.DataPilotFieldOrientation FO4 = com.sun.star.sheet.DataPilotFieldOrientation.HIDDEN; + com.sun.star.sheet.DataPilotFieldOrientation FO5 = com.sun.star.sheet.DataPilotFieldOrientation.ROW; + if (oldValue.equals(FO1)) + newValue = FO2; + if (oldValue.equals(FO2)) + newValue = FO3; + if (oldValue.equals(FO3)) + newValue = FO4; + if (oldValue.equals(FO4)) + newValue = FO5; + if (oldValue.equals(FO5)) + newValue = FO1; + } else if (oldValue instanceof com.sun.star.sheet.GeneralFunction) { + com.sun.star.sheet.GeneralFunction GF1 = com.sun.star.sheet.GeneralFunction.NONE; + com.sun.star.sheet.GeneralFunction GF2 = com.sun.star.sheet.GeneralFunction.AVERAGE; + com.sun.star.sheet.GeneralFunction GF3 = com.sun.star.sheet.GeneralFunction.COUNT; + com.sun.star.sheet.GeneralFunction GF4 = com.sun.star.sheet.GeneralFunction.COUNTNUMS; + com.sun.star.sheet.GeneralFunction GF5 = com.sun.star.sheet.GeneralFunction.MAX; + com.sun.star.sheet.GeneralFunction GF6 = com.sun.star.sheet.GeneralFunction.MIN; + com.sun.star.sheet.GeneralFunction GF7 = com.sun.star.sheet.GeneralFunction.AUTO; + com.sun.star.sheet.GeneralFunction GF8 = com.sun.star.sheet.GeneralFunction.PRODUCT; + com.sun.star.sheet.GeneralFunction GF9 = com.sun.star.sheet.GeneralFunction.STDEV; + com.sun.star.sheet.GeneralFunction GF10 = com.sun.star.sheet.GeneralFunction.STDEVP; + com.sun.star.sheet.GeneralFunction GF11 = com.sun.star.sheet.GeneralFunction.SUM; + com.sun.star.sheet.GeneralFunction GF12 = com.sun.star.sheet.GeneralFunction.VAR; + com.sun.star.sheet.GeneralFunction GF13 = com.sun.star.sheet.GeneralFunction.VARP; + + if (oldValue.equals(GF1)) + newValue = GF2; + if (oldValue.equals(GF2)) + newValue = GF3; + if (oldValue.equals(GF3)) + newValue = GF4; + if (oldValue.equals(GF4)) + newValue = GF5; + if (oldValue.equals(GF5)) + newValue = GF6; + if (oldValue.equals(GF6)) + newValue = GF7; + if (oldValue.equals(GF7)) + newValue = GF8; + if (oldValue.equals(GF8)) + newValue = GF9; + if (oldValue.equals(GF9)) + newValue = GF10; + if (oldValue.equals(GF10)) + newValue = GF11; + if (oldValue.equals(GF11)) + newValue = GF12; + if (oldValue.equals(GF12)) + newValue = GF13; + if (oldValue.equals(GF13)) + newValue = GF1; + } else if (oldValue instanceof com.sun.star.table.CellAddress) { + com.sun.star.table.CellAddress _newValue = copyStruct( + (com.sun.star.table.CellAddress) oldValue); + _newValue.Column += 1; + _newValue.Row += 1; + newValue = _newValue; + } else if (oldValue instanceof com.sun.star.table.TableOrientation) { + com.sun.star.table.TableOrientation TO1 = com.sun.star.table.TableOrientation.COLUMNS; + com.sun.star.table.TableOrientation TO2 = com.sun.star.table.TableOrientation.ROWS; + if (oldValue.equals(TO1)) + newValue = TO2; + else + newValue = TO1; + } else if (oldValue instanceof com.sun.star.sheet.DataImportMode) { + com.sun.star.sheet.DataImportMode DIM1 = com.sun.star.sheet.DataImportMode.NONE; + com.sun.star.sheet.DataImportMode DIM2 = com.sun.star.sheet.DataImportMode.QUERY; + com.sun.star.sheet.DataImportMode DIM3 = com.sun.star.sheet.DataImportMode.SQL; + com.sun.star.sheet.DataImportMode DIM4 = com.sun.star.sheet.DataImportMode.TABLE; + + if (oldValue.equals(DIM1)) + newValue = DIM2; + if (oldValue.equals(DIM2)) + newValue = DIM3; + if (oldValue.equals(DIM3)) + newValue = DIM4; + if (oldValue.equals(DIM4)) + newValue = DIM1; + + } else if (oldValue instanceof com.sun.star.style.BreakType) { + com.sun.star.style.BreakType BT1 = com.sun.star.style.BreakType.COLUMN_AFTER; + com.sun.star.style.BreakType BT2 = com.sun.star.style.BreakType.COLUMN_BEFORE; + com.sun.star.style.BreakType BT3 = com.sun.star.style.BreakType.COLUMN_BOTH; + com.sun.star.style.BreakType BT4 = com.sun.star.style.BreakType.PAGE_AFTER; + com.sun.star.style.BreakType BT5 = com.sun.star.style.BreakType.PAGE_BEFORE; + com.sun.star.style.BreakType BT6 = com.sun.star.style.BreakType.PAGE_BOTH; + com.sun.star.style.BreakType BT7 = com.sun.star.style.BreakType.NONE; + if (oldValue.equals(BT1)) + newValue = BT2; + if (oldValue.equals(BT2)) + newValue = BT3; + if (oldValue.equals(BT3)) + newValue = BT4; + if (oldValue.equals(BT4)) + newValue = BT5; + if (oldValue.equals(BT5)) + newValue = BT6; + if (oldValue.equals(BT6)) + newValue = BT7; + if (oldValue.equals(BT7)) + newValue = BT1; + } else if (oldValue instanceof PropertyValue) { + PropertyValue newVal = new PropertyValue(); + newVal.Name = ((PropertyValue) oldValue).Name; + newVal.Value = changePValue(((PropertyValue) oldValue).Value); + newValue = newVal; + } else if (oldValue instanceof com.sun.star.sheet.ValidationAlertStyle) { + com.sun.star.sheet.ValidationAlertStyle VAS1 = com.sun.star.sheet.ValidationAlertStyle.INFO; + com.sun.star.sheet.ValidationAlertStyle VAS2 = com.sun.star.sheet.ValidationAlertStyle.MACRO; + com.sun.star.sheet.ValidationAlertStyle VAS3 = com.sun.star.sheet.ValidationAlertStyle.STOP; + com.sun.star.sheet.ValidationAlertStyle VAS4 = com.sun.star.sheet.ValidationAlertStyle.WARNING; + + if (oldValue.equals(VAS1)) + newValue = VAS2; + if (oldValue.equals(VAS2)) + newValue = VAS3; + if (oldValue.equals(VAS3)) + newValue = VAS4; + if (oldValue.equals(VAS4)) + newValue = VAS1; + + } else if (oldValue instanceof com.sun.star.sheet.ValidationType) { + com.sun.star.sheet.ValidationType VT1 = com.sun.star.sheet.ValidationType.ANY; + com.sun.star.sheet.ValidationType VT2 = com.sun.star.sheet.ValidationType.CUSTOM; + com.sun.star.sheet.ValidationType VT3 = com.sun.star.sheet.ValidationType.DATE; + com.sun.star.sheet.ValidationType VT4 = com.sun.star.sheet.ValidationType.DECIMAL; + com.sun.star.sheet.ValidationType VT5 = com.sun.star.sheet.ValidationType.LIST; + com.sun.star.sheet.ValidationType VT6 = com.sun.star.sheet.ValidationType.TEXT_LEN; + com.sun.star.sheet.ValidationType VT7 = com.sun.star.sheet.ValidationType.TIME; + com.sun.star.sheet.ValidationType VT8 = com.sun.star.sheet.ValidationType.WHOLE; + + if (oldValue.equals(VT1)) + newValue = VT2; + if (oldValue.equals(VT2)) + newValue = VT3; + if (oldValue.equals(VT3)) + newValue = VT4; + if (oldValue.equals(VT4)) + newValue = VT5; + if (oldValue.equals(VT5)) + newValue = VT6; + if (oldValue.equals(VT6)) + newValue = VT7; + if (oldValue.equals(VT7)) + newValue = VT8; + if (oldValue.equals(VT8)) + newValue = VT1; + + } else if (oldValue instanceof com.sun.star.text.WritingMode) { + if (oldValue.equals(com.sun.star.text.WritingMode.LR_TB)) { + newValue = com.sun.star.text.WritingMode.TB_RL; + } else { + newValue = com.sun.star.text.WritingMode.LR_TB; + } + } else if (oldValue instanceof com.sun.star.uno.Enum) { + // universal changer for Enumerations + try { + Class<?> enumClass = oldValue.getClass(); + Field[] flds = enumClass.getFields(); + + for (int i = 0; i < flds.length; i++) { + if (Enum.class.equals(flds[i].getType().getSuperclass())) { + + Enum value = (Enum) flds[i].get(null); + if (!value.equals(oldValue)) { + newValue = value; + break; + } + } + } + } catch (Exception e) { + System.err + .println("Exception occurred while changing Enumeration value:"); + e.printStackTrace(System.err); + } + if (newValue == null) + newValue = oldValue; + + } else if (oldValue instanceof com.sun.star.style.TabStop[]) { + com.sun.star.style.TabStop[] old = (com.sun.star.style.TabStop[]) + oldValue; + com.sun.star.style.TabStop[] _newValue + = new com.sun.star.style.TabStop[old.length]; + for (int i = 0; i != old.length; ++i) { + _newValue[i] = copyStruct(old[i]); + } + if (_newValue.length == 0) { + _newValue = new com.sun.star.style.TabStop[1]; + } + com.sun.star.style.TabStop sep = new com.sun.star.style.TabStop(); + sep.Position += 1; + _newValue[0] = sep; + newValue = _newValue; + } else if (oldValue instanceof short[]) { + short[] oldArr = (short[]) oldValue; + int len = oldArr.length; + short[] newArr = new short[len + 1]; + for (int i = 0; i < len; i++) { + newArr[i] = (short) (oldArr[i] + 1); + } + newArr[len] = 5; + newValue = newArr; + } else if (oldValue instanceof String[]) { + String[] oldArr = (String[]) oldValue; + int len = oldArr.length; + String[] newArr = new String[len + 1]; + for (int i = 0; i < len; i++) { + newArr[i] = "_" + oldArr[i]; + } + newArr[len] = "_dummy"; + newValue = newArr; + } else if (oldValue instanceof PropertyValue) { + PropertyValue newVal = new PropertyValue(); + newVal.Name = ((PropertyValue) oldValue).Name; + newVal.Value = changePValue(((PropertyValue) oldValue).Value); + newValue = newVal; + } else if (oldValue instanceof com.sun.star.util.Date) { + com.sun.star.util.Date oldD = (com.sun.star.util.Date) oldValue; + com.sun.star.util.Date newD = new com.sun.star.util.Date(); + newD.Day = (short) (oldD.Day + (short) 1); + newValue = newD; + } else if (oldValue instanceof com.sun.star.util.DateTime) { + com.sun.star.util.DateTime oldDT = (com.sun.star.util.DateTime) oldValue; + com.sun.star.util.DateTime newDT = new com.sun.star.util.DateTime(); + newDT.Day = (short) (oldDT.Day + (short) 1); + newDT.Hours = (short) (oldDT.Hours + (short) 1); + newValue = newDT; + } else if (oldValue instanceof com.sun.star.util.Time) { + com.sun.star.util.Time oldT = (com.sun.star.util.Time) oldValue; + com.sun.star.util.Time newT = new com.sun.star.util.Time(); + newT.Hours = (short) (oldT.Hours + (short) 1); + newValue = newT; + } else if (oldValue instanceof com.sun.star.text.TableColumnSeparator) { + com.sun.star.text.TableColumnSeparator oldTCS = (com.sun.star.text.TableColumnSeparator) oldValue; + com.sun.star.text.TableColumnSeparator newTCS = new com.sun.star.text.TableColumnSeparator(); + newTCS.IsVisible = oldTCS.IsVisible; + newTCS.Position = (short) (oldTCS.Position - 1); + newValue = newTCS; + } else if (oldValue instanceof com.sun.star.drawing.HomogenMatrix3) { + com.sun.star.drawing.HomogenMatrix3 oldHM = (com.sun.star.drawing.HomogenMatrix3) oldValue; + com.sun.star.drawing.HomogenMatrix3 newHM = new com.sun.star.drawing.HomogenMatrix3(); + newHM.Line1.Column1 = oldHM.Line1.Column1 + 1; + newHM.Line2.Column2 = oldHM.Line2.Column2 + 1; + newHM.Line3.Column3 = oldHM.Line3.Column3 + 1; + newValue = newHM; + } else if (oldValue instanceof com.sun.star.drawing.PolyPolygonBezierCoords) { + com.sun.star.drawing.PolyPolygonBezierCoords oldPPC = (com.sun.star.drawing.PolyPolygonBezierCoords) oldValue; + com.sun.star.drawing.PolyPolygonBezierCoords newPPC = new com.sun.star.drawing.PolyPolygonBezierCoords(); + newPPC.Coordinates = oldPPC.Coordinates; + newPPC.Flags = oldPPC.Flags; + PolygonFlags[][] fArray = new PolygonFlags[1][1]; + PolygonFlags[] flags = new PolygonFlags[1]; + flags[0] = PolygonFlags.NORMAL; + fArray[0] = flags; + Point[][] pArray = new Point[1][1]; + Point[] points = new Point[1]; + Point aPoint = new Point(); + aPoint.X = 1; + aPoint.Y = 2; + points[0] = aPoint; + pArray[0] = points; + if (oldPPC.Coordinates.length == 0) { + newPPC.Coordinates = pArray; + newPPC.Flags = fArray; + } else { + if (oldPPC.Coordinates[0].length == 0) { + newPPC.Coordinates = pArray; + newPPC.Flags = fArray; + } else { + newPPC.Coordinates[0][0].X = oldPPC.Coordinates[0][0].X + 1; + newPPC.Coordinates[0][0].Y = oldPPC.Coordinates[0][0].Y + 1; + } + } + newValue = newPPC; + } else if (oldValue.getClass().isArray()) { + // changer for arrays : changes all elements + Class<?> arrType = oldValue.getClass().getComponentType(); + int oldLen = Array.getLength(oldValue); + if (oldLen == 0 && "TypedItemList".equals(name) && !arrType.isPrimitive()) { + // This case is needed to make the Sequence<Any> property pass + // the addPropertyChangeListener tests, where the property has + // to be changed (and not stay empty ...) + newValue = Array.newInstance(arrType, 1); + Object elem = new Any(new Type(String.class), "_Any"); + Array.set(newValue, 0, elem); + } else { + newValue = Array.newInstance(arrType, oldLen); + for (int i = 0; i < Array.getLength(newValue); i++) { + if (!arrType.isPrimitive()) { + Object elem = changePValue(Array.get(oldValue, i)); + Array.set(newValue, i, elem); + } else { + if (Boolean.TYPE.equals(arrType)) { + Array.setBoolean(newValue, i, + !Array.getBoolean(oldValue, i)); + } else if (Byte.TYPE.equals(arrType)) { + Array.setByte(newValue, i, + (byte) (Array.getByte(oldValue, i) + 1)); + } else if (Character.TYPE.equals(arrType)) { + Array.setChar(newValue, i, + (char) (Array.getChar(oldValue, i) + 1)); + } else if (Double.TYPE.equals(arrType)) { + Array.setDouble(newValue, i, + Array.getDouble(oldValue, i) + 1); + } else if (Float.TYPE.equals(arrType)) { + Array.setFloat(newValue, i, + Array.getFloat(oldValue, i) + 1); + } else if (Integer.TYPE.equals(arrType)) { + Array.setInt(newValue, i, Array.getInt(oldValue, i) + 1); + } else if (Long.TYPE.equals(arrType)) { + Array.setLong(newValue, i, + Array.getLong(oldValue, i) + 1); + } else if (Short.TYPE.equals(arrType)) { + Array.setShort(newValue, i, + (short) (Array.getShort(oldValue, i) + 1)); + } + } + } + } + } else if (isStructure(oldValue)) { + // universal changer for structures + Class<?> clazz = oldValue.getClass(); + try { + newValue = clazz.newInstance(); + Field[] fields = clazz.getFields(); + for (int i = 0; i < fields.length; i++) { + if ((fields[i].getModifiers() & Modifier.STATIC) == 0) { + Class<?> fType = fields[i].getType(); + Field field = fields[i]; + if (!fType.isPrimitive()) { + field.set(newValue, + changePValue(field.get(oldValue))); + } else { + if (Boolean.TYPE.equals(fType)) { + field.setBoolean(newValue, + !field.getBoolean(oldValue)); + } else if (Byte.TYPE.equals(fType)) { + field.setByte(newValue, + (byte) (field.getByte(oldValue) + 1)); + } else if (Character.TYPE.equals(fType)) { + field.setChar(newValue, + (char) (field.getChar(oldValue) + 1)); + } else if (Double.TYPE.equals(fType)) { + field.setDouble(newValue, + field.getDouble(oldValue) + 1); + } else if (Float.TYPE.equals(fType)) { + field.setFloat(newValue, + field.getFloat(oldValue) + 1); + } else if (Integer.TYPE.equals(fType)) { + field.setInt(newValue, + field.getInt(oldValue) + 1); + } else if (Long.TYPE.equals(fType)) { + field.setLong(newValue, + field.getLong(oldValue) + 1); + } else if (Short.TYPE.equals(fType)) { + field.setShort(newValue, + (short) (field.getShort(oldValue) + 1)); + } + } + } + } + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (InstantiationException e) { + e.printStackTrace(); + } + + } else { + System.out.println("ValueChanger don't know type " + + oldValue.getClass()); + } + + return newValue; + + } // end of Change PValue + + public static Object changePValue(Object oldValue) { + return changePValue(oldValue, null); + } + + /** + * Checks if the passed value is the API structure. The value assumed to be + * a structure if there are no public methods, and all public fields are not + * static or final. + * + * @param val + * the value to be checked. + * @return <code>true</code> if the value is assumed to be a structure. + */ + public static boolean isStructure(Object val) { + boolean result = true; + + Class<?> clazz = val.getClass(); + + Method[] meth = clazz.getDeclaredMethods(); + for (int i = 0; i < meth.length; i++) { + result &= (meth[i].getModifiers() & Modifier.PUBLIC) == 0; + } + + Field[] fields = clazz.getDeclaredFields(); + for (int i = 0; i < fields.length; i++) { + int mod = fields[i].getModifiers(); + if (mod == (Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL) + && fields[i].getName().equals("UNOTYPEINFO")) + { + continue; + } + // If the field is PUBLIC it must not be STATIC or FINAL + result &= ((mod & Modifier.PUBLIC) == 0) + || (((mod & Modifier.STATIC) == 0) && ((mod & Modifier.FINAL) == 0)); + } + + return result; + } + + private static <T> T copyStruct(T value) { + Class<T> clazz = (Class<T>) value.getClass(); + T newValue; + try { + newValue = clazz.newInstance(); + } catch (IllegalAccessException e) { + throw new RuntimeException("unexpected " + e, e); + } catch (InstantiationException e) { + throw new RuntimeException("unexpected " + e, e); + } + Field[] fields = clazz.getFields(); + for (int i = 0; i != fields.length; ++i) { + if ((fields[i].getModifiers() & Modifier.STATIC) == 0) { + try { + fields[i].set(newValue, fields[i].get(value)); + } catch (IllegalAccessException e) { + throw new RuntimeException("unexpected " + e, e); + } + } + } + return newValue; + } +} diff --git a/qadevOOo/runner/util/ValueComparer.java b/qadevOOo/runner/util/ValueComparer.java new file mode 100644 index 000000000..a581ad3cb --- /dev/null +++ b/qadevOOo/runner/util/ValueComparer.java @@ -0,0 +1,231 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ + +package util; + +import com.sun.star.beans.PropertyValue; +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import com.sun.star.uno.Type; +import com.sun.star.uno.Enum; +import com.sun.star.uno.XInterface; +import com.sun.star.uno.Any; +import com.sun.star.uno.AnyConverter; +import java.util.HashMap; + + +public class ValueComparer { + + // Method to change a Value, thought for properties + public static boolean equalValue( Object first, Object second ) { + + if (first instanceof com.sun.star.uno.Any) { + try { + first = AnyConverter.toObject(((Any) first).getType(),first); + } catch (com.sun.star.lang.IllegalArgumentException iae) { + } + } + if (second instanceof com.sun.star.uno.Any) { + try { + second = AnyConverter.toObject(((Any) second).getType(),second); + } catch (com.sun.star.lang.IllegalArgumentException iae) { + } + } + boolean eq = false; + try { + if ( (first==null) || (second == null) ) { + eq = (first == second); + } + else { + if ( util.utils.isVoid(first) && util.utils.isVoid(second) ) { + eq=true; + } else if ( util.utils.isVoid(first) || util.utils.isVoid(second) ) { + eq = (first == second); + } else { + eq = compareObjects(first, second); + } + } + } + catch (Exception e) { + System.out.println("Exception occurred while comparing Objects"); + e.printStackTrace(); + } + return eq; + } // end of equalValue + + private static boolean compareArrayOfPropertyValue(PropertyValue[] pv1, PropertyValue[] pv2){ + if ( pv1.length != pv2.length) { + return false; + } + HashMap<String, Object> hm1 = new HashMap<String, Object>(); + boolean result = true; + int i = 0; + + for (i = 0; i < pv1.length; i++){ + hm1.put(pv1[i].Name, pv1[i].Value); + } + + i = 0; + while (i < pv2.length && result) { + result &= equalValue(hm1.get(pv2[i].Name),pv2[i].Value); + i++; + } + return result; + } + + private static boolean compareArrays(Object op1, Object op2) throws Exception { + + if (op1 instanceof PropertyValue[] && op2 instanceof PropertyValue[]) { + return compareArrayOfPropertyValue((PropertyValue[])op1,(PropertyValue[])op2); + } + boolean result = true; + if((op1.getClass().getComponentType() == op2.getClass().getComponentType()) + && (Array.getLength(op1) == Array.getLength(op2))) + { + for(int i = 0; i < Array.getLength(op1); ++ i) + result = result & compareObjects(Array.get(op1, i), Array.get(op2, i)); + } else { + result = false ; + } + + return result; + } + + private static boolean compareInterfaces(XInterface op1, XInterface op2) { + return op1 == op2; + } + + private static boolean compareUntil(Class<?> zClass, Class<?> untilClass, Object op1, Object op2) throws Exception { + boolean result = true; + + // write inherited members first + Class<?> superClass = zClass.getSuperclass(); + if(superClass != null && superClass != untilClass) + result = result & compareUntil(superClass, untilClass, op1, op2); + + Field fields[] = zClass.getDeclaredFields(); + + for(int i = 0; i < fields.length && result; ++ i) { + if((fields[i].getModifiers() & (Modifier.STATIC | Modifier.TRANSIENT)) == 0) { // neither static nor transient ? + Object obj1 = fields[i].get(op1); + Object obj2 = fields[i].get(op2); + if (obj1 instanceof com.sun.star.uno.Any) { + try { + if (utils.isVoid(obj1)) { + obj1 = null; + } else { + obj1 = AnyConverter.toObject(((Any) obj1).getType(),obj1); + } + } catch (com.sun.star.lang.IllegalArgumentException iae) { + } + } + if (obj2 instanceof com.sun.star.uno.Any) { + try { + if (utils.isVoid(obj2)) { + obj2 = null; + } else { + obj2 = AnyConverter.toObject(((Any) obj2).getType(),obj2); + } + } catch (com.sun.star.lang.IllegalArgumentException iae) { + } + } + + result = result & compareObjects(obj1, obj2); + + } + } + + return result; + } + + private static boolean compareStructs(Object op1, Object op2) throws Exception { + boolean result = true; + + if(op1.getClass() != op2.getClass()) + result = false; + else { + result = compareUntil(op1.getClass(), Object.class, op1, op2); + } + + return result; + } + + private static boolean compareThrowable(Throwable op1, Throwable op2) throws Exception { + boolean result = true; + + if(op1.getClass() != op2.getClass()) + result = false; + else { + result = compareUntil(op1.getClass(), Throwable.class, op1, op2); + + result = result & op1.getMessage().equals(op2.getMessage()); + } + + return result; + } + + private static boolean compareEnums(Enum en1, Enum en2) { + return en1.getValue() == en2.getValue(); + } + + private static boolean compareObjects(Object op1, Object op2) throws Exception { + if(op1 == op2) + return true; + else if(op1==null || op2 == null) + return op1 == op2; + else if(op1.getClass().isPrimitive() && op2.getClass().isPrimitive()) + return op1.equals(op2); + else if(op1.getClass() == Byte.class && op2.getClass() == Byte.class) + return op1.equals(op2); + else if(op1.getClass() == Type.class && op2.getClass() == Type.class) + return op1.equals(op2); + else if(op1.getClass() == Boolean.class && op2.getClass() == Boolean.class) + return op1.equals(op2); + else if(op1.getClass() == Short.class && op2.getClass() == Short.class) + return op1.equals(op2); + else if(Throwable.class.isAssignableFrom(op1.getClass()) && Throwable.class.isAssignableFrom(op2.getClass())) + return compareThrowable((Throwable)op1, (Throwable)op2); + else if(op1.getClass() == Integer.class && op2.getClass() == Integer.class) + return op1.equals(op2); + else if(op1.getClass() == Character.class && op2.getClass() == Character.class) + return op1.equals(op2); + else if(op1.getClass() == Long.class && op2.getClass() == Long.class) + return op1.equals(op2); + else if(op1.getClass() == Void.class && op2.getClass() == Void.class) + return op1.equals(op2); + else if(op1.getClass() == Float.class && op2.getClass() == Float.class) + return op1.equals(op2); + else if(op1.getClass() == Double.class && op2.getClass() == Double.class) + return op1.equals(op2); + else if(op1.getClass().isArray() && op2.getClass().isArray()) + return compareArrays(op1, op2); + else if(op1.getClass() == Void.class || op2.getClass() == void.class) // write nothing ? + return true; + else if(XInterface.class.isAssignableFrom(op1.getClass()) && XInterface.class.isAssignableFrom(op2.getClass())) + return compareInterfaces((XInterface)op1, (XInterface)op2); + else if(Enum.class.isAssignableFrom(op1.getClass()) && Enum.class.isAssignableFrom(op2.getClass())) + return compareEnums((Enum)op1, (Enum)op2); + else if(op1.getClass() == String.class && op2.getClass() == String.class) // is it a String ? + return ((String)op1).equals(op2); + else // otherwise it must be a struct + return compareStructs(op1, op2); + } + + +} diff --git a/qadevOOo/runner/util/WaitUnreachable.java b/qadevOOo/runner/util/WaitUnreachable.java new file mode 100644 index 000000000..f90fa6552 --- /dev/null +++ b/qadevOOo/runner/util/WaitUnreachable.java @@ -0,0 +1,119 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ + +package util; + +import java.lang.ref.PhantomReference; +import java.lang.ref.ReferenceQueue; + +/** + * Wait until an object has become unreachable. + * + * <p>Instances of this class will typically be used as either:</p> + * <pre> + * SomeType o = new SomeType(...); + * ... // use "o" + * WaitUnreachable u = new WaitUnreachable(o); + * o = null; + * u.waitUnreachable(); + * </pre> + * <p>or:</p> + * <pre> + * WaitUnreachable u = new WaitUnreachable(new SomeType(...)); + * ... // use "(SomeType) u.get()" + * u.waitUnreachable(); + * </pre> + */ +public final class WaitUnreachable { + /** + * Creates a new waiter. + * + * @param obj the object on which to wait + */ + public WaitUnreachable(Object obj) { + this.obj = obj; + queue = new ReferenceQueue<Object>(); + ref = new PhantomReference<Object>(obj, queue); + } + + /** + * Gets the object on which to wait. + * + * @return the object on which to wait, or <code>null</code> if + * <code>waitUnreachable</code> has already been called + */ + public synchronized Object get() { + return obj; + } + + /** + * Starts waiting for the object to become unreachable. + * + * <p>This blocks the current thread until the object has become + * unreachable.</p> + * + * <p>Actually, this method waits until the JVM has <em>detected</em> that + * the object has become unreachable. This is not deterministic, but this + * methods makes a best effort to cause the JVM to eventually detect the + * situation. With a typical JVM, this should suffice.</p> + */ + public void waitUnreachable() { + synchronized (this) { + obj = null; + } + System.out.println("waiting for gc"); + while (queue.poll() == null) { + System.gc(); + System.runFinalization(); + } + } + + /** + * Ensures that an object will be finalized as soon as possible. + * + * <p>This does not block the current thread. Instead, a new thread is + * spawned that busy waits for the given object to become unreachable.</p> + * + * <p>This method cannot guarantee that the given object is eventually + * finalized, but it makes a best effort. With a typical JVM, this should + * suffice.</p> + * + * @param obj the object of which to ensure finalization + */ + public static void ensureFinalization(final Object obj) { + final class WaitThread extends Thread { + private WaitThread(Object obj) { + super("ensureFinalization"); + unreachable = new WaitUnreachable(obj); + } + + @Override + public void run() { + unreachable.waitUnreachable(); + } + + private final WaitUnreachable unreachable; + } + new WaitThread(obj).start(); + } + + private Object obj; + private final ReferenceQueue<Object> queue; + @SuppressWarnings("unused") + private final PhantomReference<Object> ref; +} diff --git a/qadevOOo/runner/util/WriterTools.java b/qadevOOo/runner/util/WriterTools.java new file mode 100644 index 000000000..cdff65557 --- /dev/null +++ b/qadevOOo/runner/util/WriterTools.java @@ -0,0 +1,128 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ +package util; + +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XPropertySet; + +import com.sun.star.container.XNamed; + +import com.sun.star.drawing.XDrawPage; +import com.sun.star.drawing.XDrawPageSupplier; + +import com.sun.star.lang.XComponent; +import com.sun.star.lang.XMultiServiceFactory; + +import com.sun.star.text.XText; +import com.sun.star.text.XTextContent; +import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextDocument; + +import com.sun.star.graphic.XGraphic; +import com.sun.star.graphic.XGraphicProvider; + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; + +public class WriterTools { + public static XTextDocument createTextDoc(XMultiServiceFactory xMSF) { + PropertyValue[] Args = new PropertyValue[0]; + XComponent comp = DesktopTools.openNewDoc(xMSF, "swriter", Args); + XTextDocument WriterDoc = UnoRuntime.queryInterface( + XTextDocument.class, comp); + + return WriterDoc; + } // finish createTextDoc + + public static XTextDocument loadTextDoc(XMultiServiceFactory xMSF, + String url) { + PropertyValue[] Args = new PropertyValue[0]; + XTextDocument WriterDoc = loadTextDoc(xMSF, url, Args); + + return WriterDoc; + } // finish createTextDoc + + private static XTextDocument loadTextDoc(XMultiServiceFactory xMSF, + String url, PropertyValue[] Args) { + XComponent comp = DesktopTools.loadDoc(xMSF, url, Args); + XTextDocument WriterDoc = UnoRuntime.queryInterface( + XTextDocument.class, comp); + + return WriterDoc; + } // finish createTextDoc + + public static XDrawPage getDrawPage(XTextDocument aDoc) { + XDrawPage oDP = null; + + try { + XDrawPageSupplier oDPS = UnoRuntime.queryInterface( + XDrawPageSupplier.class, aDoc); + oDP = oDPS.getDrawPage(); + } catch (Exception e) { + throw new IllegalArgumentException("Couldn't get drawpage", e); + } + + return oDP; + } + + public static void insertTextGraphic(XTextDocument aDoc, + XMultiServiceFactory xMSF, XComponentContext xContext, int hpos, + int vpos, int width, int height, + String pic, String name) { + try { + Object oGObject = xMSF.createInstance( + "com.sun.star.text.GraphicObject"); + + XGraphicProvider xGraphicProvider = UnoRuntime.queryInterface( + XGraphicProvider.class, + xContext.getServiceManager().createInstanceWithContext( + "com.sun.star.graphic.GraphicProvider", xContext)); + + String fullURL = util.utils.getFullTestURL(pic); + + PropertyValue[] aMediaProps = new PropertyValue[] { new PropertyValue() }; + aMediaProps[0].Name = "URL"; + aMediaProps[0].Value = fullURL; + + XGraphic xGraphic = UnoRuntime.queryInterface(XGraphic.class, + xGraphicProvider.queryGraphic(aMediaProps)); + + XText the_text = aDoc.getText(); + XTextCursor the_cursor = the_text.createTextCursor(); + XTextContent the_content = UnoRuntime.queryInterface( + XTextContent.class, oGObject); + the_text.insertTextContent(the_cursor, the_content, true); + + XPropertySet oProps = UnoRuntime.queryInterface( + XPropertySet.class, oGObject); + + oProps.setPropertyValue("Graphic", xGraphic); + oProps.setPropertyValue("HoriOrientPosition", Integer.valueOf(hpos)); + oProps.setPropertyValue("VertOrientPosition", Integer.valueOf(vpos)); + oProps.setPropertyValue("Width", Integer.valueOf(width)); + oProps.setPropertyValue("Height", Integer.valueOf(height)); + + XNamed the_name = UnoRuntime.queryInterface(XNamed.class, + oGObject); + the_name.setName(name); + } catch (Exception ex) { + System.out.println("Exception while inserting TextGraphic"); + ex.printStackTrace(); + } + } +} diff --git a/qadevOOo/runner/util/XInstCreator.java b/qadevOOo/runner/util/XInstCreator.java new file mode 100644 index 000000000..c0fe76837 --- /dev/null +++ b/qadevOOo/runner/util/XInstCreator.java @@ -0,0 +1,29 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ + +package util; + +import com.sun.star.uno.XInterface; +import com.sun.star.container.XIndexAccess; + +public interface XInstCreator { + + XInterface getInstance(); + XInterface createInstance(); + XIndexAccess getCollection(); +} diff --git a/qadevOOo/runner/util/XLayerHandlerImpl.java b/qadevOOo/runner/util/XLayerHandlerImpl.java new file mode 100644 index 000000000..399db9a24 --- /dev/null +++ b/qadevOOo/runner/util/XLayerHandlerImpl.java @@ -0,0 +1,110 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ +package util; + +public class XLayerHandlerImpl + implements com.sun.star.configuration.backend.XLayerHandler { + private String calls = ""; + private final String ls = System.getProperty("line.separator"); + + public void addOrReplaceNode(String str, short param) + throws com.sun.star.configuration.backend.MalformedDataException, + com.sun.star.lang.WrappedTargetException { + calls += ("addOrReplace(" + str + "," + param + ");" + ls); + } + + public void addOrReplaceNodeFromTemplate(String str, + com.sun.star.configuration.backend.TemplateIdentifier templateIdentifier, + short param) + throws com.sun.star.configuration.backend.MalformedDataException, + com.sun.star.lang.WrappedTargetException { + calls += ("addOrReplaceNodeFromTemplate(" + str + "," + templateIdentifier + ");" + ls); + } + + public void addProperty(String str, short param, + com.sun.star.uno.Type type) + throws com.sun.star.configuration.backend.MalformedDataException, + com.sun.star.lang.WrappedTargetException { + calls += ("addProperty(" + str + "," + param + "," + type + ");" + ls); + } + + public void addPropertyWithValue(String str, short param, Object obj) + throws com.sun.star.configuration.backend.MalformedDataException, + com.sun.star.lang.WrappedTargetException { + calls += ("addPropertyWithValue(" + str + "," + param + "," + obj + ");" + ls); + } + + public void dropNode(String str) + throws com.sun.star.configuration.backend.MalformedDataException, + com.sun.star.lang.WrappedTargetException { + calls += ("dropNode(" + str + ");" + ls); + } + + public void endLayer() + throws com.sun.star.configuration.backend.MalformedDataException, + com.sun.star.lang.WrappedTargetException { + calls += ("endLayer();" + ls); + } + + public void endNode() + throws com.sun.star.configuration.backend.MalformedDataException, + com.sun.star.lang.WrappedTargetException { + calls += ("endNode();" + ls); + } + + public void endProperty() + throws com.sun.star.configuration.backend.MalformedDataException, + com.sun.star.lang.WrappedTargetException { + calls += ("endProperty();" + ls); + } + + public void overrideNode(String str, short param, boolean param2) + throws com.sun.star.configuration.backend.MalformedDataException, + com.sun.star.lang.WrappedTargetException { + calls += ("overrideNode(" + str + "," + param + "," + param2 + ");" + ls); + } + + public void overrideProperty(String str, short param, + com.sun.star.uno.Type type, boolean param3) + throws com.sun.star.configuration.backend.MalformedDataException, + com.sun.star.lang.WrappedTargetException { + calls += ("overrideProperty(" + str + "," + param + "," + type + "," + param3 + ");" + ls); + } + + public void setPropertyValue(Object obj) + throws com.sun.star.configuration.backend.MalformedDataException, + com.sun.star.lang.WrappedTargetException { + calls += ("setPropertyValue(" + obj + ");" + ls); + } + + public void setPropertyValueForLocale(Object obj, String str) + throws com.sun.star.configuration.backend.MalformedDataException, + com.sun.star.lang.WrappedTargetException { + calls += ("setPropertyValueForLocale(" + obj + "," + str + ");" + ls); + } + + public void startLayer() + throws com.sun.star.configuration.backend.MalformedDataException, + com.sun.star.lang.WrappedTargetException { + calls = "startLayer();" + ls; + } + + public String getCalls() { + return calls; + } +}
\ No newline at end of file diff --git a/qadevOOo/runner/util/XLayerImpl.java b/qadevOOo/runner/util/XLayerImpl.java new file mode 100644 index 000000000..3b2ac9ca4 --- /dev/null +++ b/qadevOOo/runner/util/XLayerImpl.java @@ -0,0 +1,33 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ + +package util; + +public class XLayerImpl implements com.sun.star.configuration.backend.XLayer { + + private boolean wasCalled = false; + + public void readData(com.sun.star.configuration.backend.XLayerHandler xLayerHandler) throws com.sun.star.lang.NullPointerException, com.sun.star.lang.WrappedTargetException, com.sun.star.configuration.backend.MalformedDataException { + wasCalled = true; + } + + public boolean hasBeenCalled() { + return wasCalled; + } + +} diff --git a/qadevOOo/runner/util/XMLTools.java b/qadevOOo/runner/util/XMLTools.java new file mode 100644 index 000000000..fc821b9ff --- /dev/null +++ b/qadevOOo/runner/util/XMLTools.java @@ -0,0 +1,669 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ + +package util; + +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; + +import com.sun.star.beans.PropertyValue; +import com.sun.star.xml.sax.XAttributeList; +import com.sun.star.xml.sax.XDocumentHandler; +import com.sun.star.xml.sax.XLocator; + + +public class XMLTools { + + /** + * The implementation of <code>com.sun.star.xml.sax.XAttributeList</code> + * where attributes and their values can be added. + */ + public static class AttributeList implements XAttributeList { + private static class Attribute { + public String Name ; + public String Type ; + public String Value ; + } + private final HashMap<String, Attribute> attrByName = new HashMap<String, Attribute>() ; + private final ArrayList<Attribute> attributes = new ArrayList<Attribute>() ; + + /** + * Creates a class instance. + */ + public AttributeList() {} + + private AttributeList(XAttributeList list) { + if (list == null) return ; + for (short i = 0; i < list.getLength(); i++) { + add(list.getNameByIndex(i), list.getTypeByIndex(i), + list.getValueByIndex(i)) ; + } + } + + /** + * Adds an attribute with type and value specified. + * @param name The attribute name. + * @param type Value type (usually 'CDATA' used). + * @param value Attribute value. + */ + public void add(String name, String type, String value) { + Attribute attr = new Attribute() ; + attr.Name = name ; + attr.Type = type ; + attr.Value = value ; + attributes.add(attr) ; + attrByName.put(attr.Name, attr) ; + } + + + + + + /*************************************** + * XAttributeList methods + ****************************************/ + + public short getLength() { + return (short) attributes.size() ; + } + + public String getNameByIndex(short idx) { + String name = attributes.get(idx).Name ; + return name ; + } + + public String getTypeByIndex(short idx) { + String type = attributes.get(idx).Type ; + return type; + } + + public String getTypeByName(String name) { + String type = attrByName.get(name).Type ; + return type; + } + public String getValueByIndex(short idx) { + String value = attributes.get(idx).Value ; + return value; + } + + public String getValueByName(String name) { + String value = attrByName.get(name).Value ; + return value; + } + } + + /** + * This class writes all XML data handled into a stream specified + * in the constructor. + */ + private static class XMLWriter implements XDocumentHandler { + private PrintWriter _log = null ; + private String align = "" ; + + /** + * Creates a SAX handler which writes all XML data + * handled into a <code>log</code> stream specified. + */ + private XMLWriter(PrintWriter log) { + _log = log ; + } + + /** + * Creates a SAX handler which does nothing. + */ + public XMLWriter() { + } + + public void processingInstruction(String appl, String data) { + if (_log == null) return ; + _log.println(align + "<?" + appl + " " + data + "?>") ; + } + public void startDocument() { + if (_log == null) return ; + _log.println("START DOCUMENT:") ; + } + public void endDocument() { + if (_log == null) return ; + _log.println("END DOCUMENT:") ; + } + public void setDocumentLocator(XLocator loc) { + if (_log == null) return ; + _log.println("DOCUMENT LOCATOR: ('" + loc.getPublicId() + + "','" + loc.getSystemId() + "')") ; + } + public void startElement(String name, XAttributeList attr) { + if (_log == null) return ; + _log.print(align + "<" + name + " ") ; + if (attr != null) { + short attrLen = attr.getLength() ; + for (short i = 0; i < attrLen; i++) { + if (i != 0) _log.print(align + " ") ; + _log.print(attr.getNameByIndex(i) + "[" + + attr.getTypeByIndex(i) + "]=\"" + + attr.getValueByIndex(i) + "\"") ; + if (i+1 != attrLen) { + _log.println() ; + } + } + } + _log.println(">") ; + + align += " " ; + } + + public void endElement(String name) { + if (_log == null) return ; + align = align.substring(3) ; + _log.println(align + "</" + name + ">") ; + } + + public void characters(String chars) { + if (_log == null) return ; + _log.println(align + chars) ; + } + public void ignorableWhitespace(String sp) { + if (_log == null) return ; + _log.println(sp) ; + } + } + + /** + * Checks if the XML structure is well formed (i.e. all tags opened must be + * closed and all tags opened inside a tag must be closed + * inside the same tag). It also checks parameters passed. + * If any collisions found appropriate error message is + * output into a stream specified. No XML data output, i.e. + * no output will be performed if no errors occur.<p> + * After document is completed there is a way to check + * if the XML data and structure was valid. + */ + private static class XMLWellFormChecker extends XMLWriter { + private boolean docStarted = false ; + private boolean docEnded = false ; + ArrayList<String> tagStack = new ArrayList<String>() ; + private boolean wellFormed = true ; + private boolean noOtherErrors = true ; + PrintWriter log = null ; + private boolean printXMLData = false ; + + private XMLWellFormChecker(PrintWriter log) { + super() ; + this.log = log ; + } + + private XMLWellFormChecker(PrintWriter log_, boolean printXMLData) { + super(printXMLData ? log_ : null) ; + this.printXMLData = printXMLData ; + this.log = log_ ; + } + + /** + * Reset all values. This is important e.g. for test of XFilter + * interface, where 'filter()' method is started twice. + */ + void reset() { + docStarted = false ; + docEnded = false ; + tagStack = new ArrayList<String>() ; + wellFormed = true ; + noOtherErrors = true ; + printXMLData = false ; + } + + @Override + public void startDocument() { + super.startDocument(); + + if (docStarted) { + printError("Document is started twice.") ; + wellFormed = false ; + } + + docStarted = true ; + } + @Override + public void endDocument() { + super.endDocument(); + if (!docStarted) { + wellFormed = false ; + printError("Document ended but not started.") ; + } + docEnded = true ; + } + @Override + public void startElement(String name, XAttributeList attr) { + super.startElement(name, attr); + if (attr == null) { + printError("attribute list passed as parameter to startElement()"+ + " method has null value for tag <" + name + ">") ; + noOtherErrors = false ; + } + tagStack.add(0, name) ; + } + @Override + public void endElement(String name) { + super.endElement(name); + if (wellFormed) { + if (tagStack.isEmpty()) { + wellFormed = false ; + printError("No tags to close (bad closing tag </" + name + ">)") ; + } else { + String startTag = tagStack.get(0) ; + tagStack.remove(0) ; + if (!startTag.equals(name)) { + wellFormed = false ; + printError("Bad closing tag: </" + name + + ">; tag expected: </" + startTag + ">"); + } + } + } + } + + /** + * Checks if there were no errors during document handling. + * I.e. startDocument() and endDocument() must be called, + * XML must be well formed, parameters must be valid. + */ + public boolean isWellFormed() { + if (!docEnded) { + printError("Document was not ended.") ; + wellFormed = false ; + } + + return wellFormed && noOtherErrors ; + } + + /** + * Prints error message and all tags where error occurred inside. + * Also prints "Tag trace" in case if the full XML data isn't + * printed. + */ + void printError(String msg) { + log.println("!!! Error: " + msg) ; + if (printXMLData) return ; + log.println(" Tag trace :") ; + for (int i = 0; i < tagStack.size(); i++) { + String tag = tagStack.get(i) ; + log.println(" <" + tag + ">") ; + } + } + } + + /** + * Beside structure of XML this class also can check existence + * of tags, inner tags, and character data. After document + * completion there is a way to check if required tags and + * character data was found. If there any error occurs an + * appropriate message is output. + */ + public static class XMLTagsChecker extends XMLWellFormChecker { + private final HashMap<String,String> tags = new HashMap<String,String>() ; + private final HashMap<String,String> chars = new HashMap<String,String>() ; + private boolean allOK = true ; + + public XMLTagsChecker(PrintWriter log) { + super(log) ; + } + + /** + * Adds a tag name which must be contained in the XML data. + */ + public void addTag(String tag) { + tags.put(tag, "") ; + } + /** + * Adds a tag name which must be contained in the XML data and + * must be inside the tag with name <code>outerTag</code>. + */ + public void addTagEnclosed(String tag, String outerTag) { + tags.put(tag, outerTag) ; + } + + /** + * Adds a character data which must be contained in the XML data and + * must be inside the tag with name <code>outerTag</code>. + */ + public void addCharactersEnclosed(String ch, String outerTag) { + chars.put(ch, outerTag) ; + } + + @Override + public void startElement(String name, XAttributeList attrs) { + super.startElement(name, attrs) ; + if (tags.containsKey(name)) { + String outerTag = tags.get(name); + if (outerTag.length() != 0) { + boolean isInTag = false ; + for (int i = 0; i < tagStack.size(); i++) { + if (outerTag.equals(tagStack.get(i))) { + isInTag = true ; + break ; + } + } + if (!isInTag) { + printError("Required tag <" + name + "> found, but is not enclosed in tag <" + + outerTag + ">") ; + allOK = false ; + } + } + tags.remove(name) ; + } + } + + @Override + public void characters(String ch) { + super.characters(ch) ; + + if (chars.containsKey(ch)) { + String outerTag = chars.get(ch); + if (outerTag.length() != 0) { + boolean isInTag = false ; + for (int i = 0; i < tagStack.size(); i++) { + if (outerTag.equals(tagStack.get(i))) { + isInTag = true ; + break ; + } + } + if (!isInTag) { + printError("Required characters '" + ch + "' found, but are not enclosed in tag <" + + outerTag + ">") ; + allOK = false ; + } + } + chars.remove(ch) ; + } + } + + /** + * Checks if the XML data was valid and well formed and if + * all necessary tags and character data was found. + */ + public boolean checkTags() { + if (!isWellFormed()) + allOK = false ; + + Iterator<String> badTags = tags.keySet().iterator() ; + Iterator<String> badChars = chars.keySet().iterator() ; + + if (badTags.hasNext()) { + allOK = false ; + log.println("Required tags were not found in export :") ; + while(badTags.hasNext()) { + log.println(" <" + badTags.next() + ">") ; + } + } + if (badChars.hasNext()) { + allOK = false ; + log.println("Required characters were not found in export :") ; + while(badChars.hasNext()) { + log.println(" <" + badChars.next() + ">") ; + } + } + reset(); + return allOK ; + } + } + + /** + * Represents an XML tag which must be found in XML data written. + * This tag can contain only its name or tag name and attribute + * name, or attribute value additionally. + */ + public static class Tag { + private final String name; + private String[][] attrList = new String[0][3] ; + + /** + * Creates tag which has only a name. Attributes don't make sense. + * @param tagName The name of the tag. + */ + public Tag(String tagName) { + name = tagName ; + } + + /** + * Creates a tag with the name specified, which must have an + * attribute with the value specified. The type of value + * assumed to be 'CDATA'. + * @param tagName The name of the tag. + * @param attrName The name of attribute which must be contained + * in the tag. + * @param attrValue Attribute value. + */ + public Tag(String tagName, String attrName, String attrValue) { + name = tagName ; + attrList = new String[1][3] ; + attrList[0][0] = attrName ; + attrList[0][1] = "CDATA" ; + attrList[0][2] = attrValue ; + } + + /** + * Gets tag String description. + */ + @Override + public String toString() { + StringBuffer ret = new StringBuffer("<" + name); + for (int i = 0; i < attrList.length; i++) { + ret.append(" ").append(attrList[i][0]).append("="); + if (attrList[i][2] == null) { + ret.append("(not specified)"); + } else { + ret.append("\"").append(attrList[i][2]).append("\""); + } + } + ret.append(">"); + + return ret.toString(); + } + + private boolean checkAttr(int attrListIdx, XAttributeList list) { + short j = 0 ; + int listLen = list.getLength(); + while(j < listLen) { + if (attrList[attrListIdx][0].equals(list.getNameByIndex(j))) { + if (attrList[attrListIdx][2] == null) return true ; + return attrList[attrListIdx][2].equals(list.getValueByIndex(j)) ; + } + j++ ; + } + return false ; + } + + /** + * Checks if this tag matches tag passed in parameters. + * I.e. if tag specifies only its name it matches if names + * are equal (attributes don't make sense). If there are + * some attributes names specified in this tag method checks + * if all names present in attribute list <code>list</code> + * (attributes' values don't make sense). If attributes specified + * with values method checks if these attributes exist and + * have appropriate values. + */ + private boolean isMatchTo(String tagName, XAttributeList list) { + if (!name.equals(tagName)) return false; + boolean result = true ; + for (int i = 0; i < attrList.length; i++) { + result &= checkAttr(i, list) ; + } + return result ; + } + } + + /** + * Class realises extended XML data checking. It has possibilities + * to check if a tag exists, if it has some attributes with + * values, and if this tag is contained in another tag (which + * also can specify any attributes). It can check if some + * character data exists inside any tag specified. + */ + public static class XMLChecker extends XMLWellFormChecker { + private final HashSet<String> tagSet = new HashSet<String>() ; + private final ArrayList<Tag[]> tags = new ArrayList<Tag[]>() ; + private final ArrayList<Object[]> chars = new ArrayList<Object[]>() ; + private final ArrayList<String> tagStack = new ArrayList<String>() ; + private final ArrayList<AttributeList> attrStack = new ArrayList<AttributeList>() ; + + public XMLChecker(PrintWriter log, boolean writeXML) { + super(log, writeXML) ; + } + + public void addTag(Tag tag) { + tags.add(new Tag[] {tag, null}) ; + tagSet.add(tag.name) ; + } + + public void addTagEnclosed(Tag tag, Tag outerTag) { + tags.add(new Tag[] {tag, outerTag}) ; + tagSet.add(tag.name) ; + } + + + + public void addCharactersEnclosed(String ch, Tag outerTag) { + chars.add(new Object[] {ch.trim(), outerTag}) ; + } + + @Override + public void startElement(String name, XAttributeList attr) { + try { + super.startElement(name, attr); + + if (tagSet.contains(name)) { + for (int i = 0; i < tags.size(); i++) { + Tag[] tag = tags.get(i); + if (tag[0].isMatchTo(name, attr)) { + if (tag[1] == null) { + tags.remove(i--); + } else { + boolean isInStack = false ; + for (int j = 0; j < tagStack.size(); j++) { + if (tag[1].isMatchTo(tagStack.get(j), + attrStack.get(j))) { + + isInStack = true ; + break ; + } + } + if (isInStack) { + tags.remove(i--) ; + } + } + } + } + } + + tagStack.add(0, name) ; + attrStack.add(0, new AttributeList(attr)); + } catch (Exception e) { + e.printStackTrace(log); + } + } + + @Override + public void characters(String ch) { + super.characters(ch) ; + for (int i = 0; i < chars.size(); i++) { + Object[] chr = chars.get(i); + if (((String) chr[0]).equals(ch)) { + if (chr[1] == null) { + chars.remove(i--); + } else { + boolean isInStack = false ; + for (int j = 0; j < tagStack.size(); j++) { + if (((Tag) chr[1]).isMatchTo(tagStack.get(j), + attrStack.get(j))) { + + isInStack = true ; + break ; + } + } + if (isInStack) { + chars.remove(i--) ; + } + } + } + } + } + + @Override + public void endElement(String name) { + try { + super.endElement(name); + + if (tagStack.size() > 0) { + tagStack.remove(0) ; + attrStack.remove(0) ; + } + } catch(Exception e) { + e.printStackTrace(log) ; + } + } + + public boolean check() { + if (tags.size()> 0) { + log.println("!!! Error: Some tags were not found :") ; + for (int i = 0; i < tags.size(); i++) { + Tag[] tag = tags.get(i) ; + log.println(" Tag " + tag[0] + " was not found"); + if (tag[1] != null) + log.println(" inside tag " + tag[1]) ; + } + } + if (chars.size() > 0) { + log.println("!!! Error: Some character data blocks were not found :") ; + for (int i = 0; i < chars.size(); i++) { + Object[] ch = chars.get(i) ; + log.println(" Character data \"" + ch[0] + "\" was not found ") ; + if (ch[1] != null) + log.println(" inside tag " + ch[1]) ; + } + } + + if (!isWellFormed()) + log.println("!!! Some errors were found in XML structure") ; + + boolean result = tags.isEmpty() && chars.isEmpty() && isWellFormed(); + reset(); + return result; + } + } + + + + public static PropertyValue[] createMediaDescriptor(String[] propNames, Object[] values) { + PropertyValue[] props = new PropertyValue[propNames.length] ; + + for (int i = 0; i < props.length; i++) { + props[i] = new PropertyValue() ; + props[i].Name = propNames[i] ; + if (values != null && i < values.length) { + props[i].Value = values[i] ; + } + } + + return props ; + } + + + + +} diff --git a/qadevOOo/runner/util/XSchemaHandlerImpl.java b/qadevOOo/runner/util/XSchemaHandlerImpl.java new file mode 100644 index 000000000..cd72fd6ed --- /dev/null +++ b/qadevOOo/runner/util/XSchemaHandlerImpl.java @@ -0,0 +1,128 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ +package util; + +public class XSchemaHandlerImpl + implements com.sun.star.configuration.backend.XSchemaHandler { + private String calls = ""; + private final String ls = System.getProperty("line.separator"); + + public void addInstance(String str, + com.sun.star.configuration.backend.TemplateIdentifier templateIdentifier) + throws com.sun.star.configuration.backend.MalformedDataException, + com.sun.star.lang.WrappedTargetException { + calls += ("addInstance();" + ls); + } + + public void addItemType(com.sun.star.configuration.backend.TemplateIdentifier templateIdentifier) + throws com.sun.star.configuration.backend.MalformedDataException, + com.sun.star.lang.WrappedTargetException { + calls += ("addItemType();" + ls); + } + + public void addProperty(String str, short param, + com.sun.star.uno.Type type) + throws com.sun.star.configuration.backend.MalformedDataException, + com.sun.star.lang.WrappedTargetException { + calls += ("addProperty();" + ls); + } + + public void addPropertyWithDefault(String str, short param, Object obj) + throws com.sun.star.configuration.backend.MalformedDataException, + com.sun.star.lang.WrappedTargetException { + calls += ("addPropertyWithDefault();" + ls); + } + + public void endComponent() + throws com.sun.star.configuration.backend.MalformedDataException, + com.sun.star.lang.WrappedTargetException { + calls += ("endComponent();" + ls); + } + + public void endNode() + throws com.sun.star.configuration.backend.MalformedDataException, + com.sun.star.lang.WrappedTargetException { + calls += ("endNode();" + ls); + } + + public void endSchema() + throws com.sun.star.configuration.backend.MalformedDataException, + com.sun.star.lang.WrappedTargetException { + calls += ("endSchema();" + ls); + } + + public void endTemplate() + throws com.sun.star.configuration.backend.MalformedDataException, + com.sun.star.lang.WrappedTargetException { + calls += ("endTemplate();" + ls); + } + + public void importComponent(String str) + throws com.sun.star.configuration.backend.MalformedDataException, + com.sun.star.lang.WrappedTargetException { + calls += ("importComponent();" + ls); + } + + public void startComponent(String str) + throws com.sun.star.configuration.backend.MalformedDataException, + com.sun.star.lang.WrappedTargetException { + calls += ("startComponent();" + ls); + } + + public void startGroup(String str, short param) + throws com.sun.star.configuration.backend.MalformedDataException, + com.sun.star.lang.WrappedTargetException { + calls += ("startGroup();" + ls); + } + + public void startGroupTemplate(com.sun.star.configuration.backend.TemplateIdentifier templateIdentifier, + short param) + throws com.sun.star.configuration.backend.MalformedDataException, + com.sun.star.lang.WrappedTargetException { + calls += ("startGroupTemplate();" + ls); + } + + public void startSchema() + throws com.sun.star.configuration.backend.MalformedDataException, + com.sun.star.lang.WrappedTargetException { + calls += ("startSchema();" + ls); + } + + public void startSet(String str, short param, + com.sun.star.configuration.backend.TemplateIdentifier templateIdentifier) + throws com.sun.star.configuration.backend.MalformedDataException, + com.sun.star.lang.WrappedTargetException { + calls += ("startSet();" + ls); + } + + public void startSetTemplate(com.sun.star.configuration.backend.TemplateIdentifier templateIdentifier, + short param, + com.sun.star.configuration.backend.TemplateIdentifier templateIdentifier2) + throws com.sun.star.configuration.backend.MalformedDataException, + com.sun.star.lang.WrappedTargetException { + calls += ("startSetTemplate();" + ls); + } + + public String getCalls() { + return calls; + } + + public void cleanCalls() { + calls = ""; + } +}
\ No newline at end of file diff --git a/qadevOOo/runner/util/db/DataSource.java b/qadevOOo/runner/util/db/DataSource.java new file mode 100644 index 000000000..b9f41c332 --- /dev/null +++ b/qadevOOo/runner/util/db/DataSource.java @@ -0,0 +1,146 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ + +package util.db; + +import com.sun.star.beans.XPropertySet; +import com.sun.star.container.NoSuchElementException; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.sdbc.XDataSource; +import com.sun.star.uno.Exception; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XNamingService; +import lib.StatusException; + +/** wraps a com.sun.star.sdb.DataSource + */ +public class DataSource +{ + protected DataSource( XMultiServiceFactory _orb, DataSourceDescriptor _descriptor ) + { + m_orb = _orb; + try + { + m_dataSource = UnoRuntime.queryInterface( XDataSource.class, + m_orb.createInstance( "com.sun.star.sdb.DataSource" ) ); + m_properties = UnoRuntime.queryInterface( XPropertySet.class, + m_dataSource ); + + Object[] descriptorProperties = new Object[] { + null, _descriptor.URL, _descriptor.Info, _descriptor.User, _descriptor.Password, + _descriptor.IsPasswordRequired }; + String[] propertyNames = new String[] { + "Name", "URL", "Info", "User", "Password", "IsPasswordRequired" }; + for ( int i=0; i < descriptorProperties.length; ++i ) + if ( descriptorProperties[i] != null ) + m_properties.setPropertyValue( propertyNames[i], descriptorProperties[i] ); + } + catch ( Exception e ) + { + throw new StatusException( "could not create/fill a css.sdb.DataSource object", e ); + } + } + + public XDataSource getDataSource() + { + return m_dataSource; + } + + /** + * retrieves the css.sdb.OfficeDatabaseDocument associated with the data source + */ + public synchronized DatabaseDocument getDatabaseDocument() + { + if ( m_document == null ) + m_document = new DatabaseDocument( this ); + return m_document; + } + + public void revokeRegistration() + { + String dataSourceName = ""; + try + { + dataSourceName = (String)m_properties.getPropertyValue( "Name" ); + XNamingService dbContext = UnoRuntime.queryInterface( XNamingService.class, + m_orb.createInstance( "com.sun.star.sdb.DatabaseContext" ) ); + dbContext.revokeObject( dataSourceName ); + } + catch ( Exception e ) + { + throw new StatusException( "DataSource.revokeRegistration: could not revoke the object (" + dataSourceName + ")", e ); + } + } + + public void registerAs( final String _registrationName, final boolean _revokeIfRegistered ) + { + String doing = null; + try + { + doing = "creating database context"; + XNamingService dbContext = UnoRuntime.queryInterface( XNamingService.class, + m_orb.createInstance( "com.sun.star.sdb.DatabaseContext" ) ); + + if ( _revokeIfRegistered ) + { + doing = "revoking previously registered data source"; + try + { + dbContext.revokeObject( _registrationName ); + } + catch( NoSuchElementException e ) + { /* allowed here */ } + } + + // if the document associated with the database document has not yet been saved, then we need to do so + DatabaseDocument doc = getDatabaseDocument(); + String docURL = doc.getURL(); + if ( docURL.length() == 0 ) + { + final java.io.File tempFile = java.io.File.createTempFile( _registrationName + "_", ".odb" ); + if ( tempFile.exists() ) { + // we did not really want to create that file, we just wanted its local name, but + // createTempFile actually creates it => throw it away + // (This is necessary since some JVM/platform combinations seem to actually lock the file) + boolean bDeleteOk = tempFile.delete(); + if (!bDeleteOk) { + System.out.println("delete failed"); + } + } + String localPart = tempFile.toURI().toURL().toString(); + localPart = localPart.substring( localPart.lastIndexOf( '/' ) + 1 ); + docURL = util.utils.getOfficeTemp( m_orb ) + localPart; + doing = "storing database document to temporary location (" + docURL + ")"; + doc.storeAsURL( docURL ); + } + + // register the data source + doing = "registering the data source at the database context"; + dbContext.registerObject( _registrationName, m_dataSource ); + } + catch( final java.lang.Exception e ) + { + throw new StatusException( "DataSource.registerAs: error during " + doing, e ); + } + } + + private final XMultiServiceFactory m_orb; + private final XDataSource m_dataSource; + private final XPropertySet m_properties; + private DatabaseDocument m_document = null; +} diff --git a/qadevOOo/runner/util/db/DataSourceDescriptor.java b/qadevOOo/runner/util/db/DataSourceDescriptor.java new file mode 100644 index 000000000..6b699445f --- /dev/null +++ b/qadevOOo/runner/util/db/DataSourceDescriptor.java @@ -0,0 +1,60 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ + +package util.db; + +import com.sun.star.beans.PropertyValue; +import com.sun.star.lang.XMultiServiceFactory; + +/** a descriptor for creating a com.sun.star.sdb.DataSource + */ +public class DataSourceDescriptor +{ + /** + * Representation of <code>'URL'</code> property. + */ + public String URL = null ; + /** + * Representation of <code>'Info'</code> property. + */ + public PropertyValue[] Info = null ; + /** + * Representation of <code>'User'</code> property. + */ + public String User = null ; + /** + * Representation of <code>'Password'</code> property. + */ + public String Password = null ; + /** + * Representation of <code>'IsPasswordRequired'</code> property. + */ + public Boolean IsPasswordRequired = null ; + + public DataSourceDescriptor( XMultiServiceFactory _orb ) + { + m_orb = _orb; + } + + public DataSource createDataSource() + { + return new DataSource( m_orb, this ); + } + + private final XMultiServiceFactory m_orb; +} diff --git a/qadevOOo/runner/util/db/DatabaseDocument.java b/qadevOOo/runner/util/db/DatabaseDocument.java new file mode 100644 index 000000000..f9c4913e7 --- /dev/null +++ b/qadevOOo/runner/util/db/DatabaseDocument.java @@ -0,0 +1,71 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ + +package util.db; + +import com.sun.star.beans.PropertyValue; +import com.sun.star.frame.XModel; +import com.sun.star.frame.XStorable; +import com.sun.star.io.IOException; +import com.sun.star.sdb.XDocumentDataSource; +import com.sun.star.sdb.XOfficeDatabaseDocument; +import com.sun.star.uno.UnoRuntime; + +/** + * encapsulates a css.sdb.DatabaseDocument + */ +public class DatabaseDocument +{ + protected DatabaseDocument( final DataSource _dataSource ) + { + XDocumentDataSource docDataSource = UnoRuntime.queryInterface( + XDocumentDataSource.class, _dataSource.getDataSource() ); + m_databaseDocument = UnoRuntime.queryInterface(XOfficeDatabaseDocument.class, + docDataSource.getDatabaseDocument() ); + + m_model = UnoRuntime.queryInterface( XModel.class, m_databaseDocument ); + m_storeDoc = UnoRuntime.queryInterface( XStorable.class, m_databaseDocument ); + } + + public XOfficeDatabaseDocument getDatabaseDocument() + { + return m_databaseDocument; + } + + /** + * passes through to XModel.getURL. + */ + public String getURL() + { + return m_model.getURL(); + } + + /** + * simplified version (taking no arguments except the target URL) of XStorage.storeAsURL + * @param _url + * specifies the location to where to store the document + */ + public void storeAsURL( final String _url ) throws IOException + { + m_storeDoc.storeAsURL( _url, new PropertyValue[] { } ); + } + + private final XOfficeDatabaseDocument m_databaseDocument; + private final XModel m_model; + private final XStorable m_storeDoc; +} diff --git a/qadevOOo/runner/util/dbg.java b/qadevOOo/runner/util/dbg.java new file mode 100644 index 000000000..5416e92f6 --- /dev/null +++ b/qadevOOo/runner/util/dbg.java @@ -0,0 +1,274 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ + +package util; + +import com.sun.star.uno.XInterface; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.Type; +import com.sun.star.beans.XPropertySet; +import com.sun.star.beans.XPropertySetInfo; +import com.sun.star.beans.Property; +import com.sun.star.beans.PropertyAttribute; +import com.sun.star.beans.PropertyValue; +import com.sun.star.lang.XTypeProvider; +import com.sun.star.lang.XServiceInfo; +import java.io.PrintWriter; +import java.io.OutputStreamWriter; +import java.io.UnsupportedEncodingException; +import java.lang.reflect.Method; + +/** + * This class accumulates all kinds of methods for accessing debug information + * from UNO implementations. + */ +public class dbg { + + /** + * Prints information about the supported interfaces of an implementation + * to standard out. + * @param xTarget The implementation which should be analysed. + * @see com.sun.star.uno.XInterface + */ + public static void printInterfaces(XInterface xTarget) { + printInterfaces(xTarget, false); + } + + /** + * Prints information about the supported interfaces of an implementation + * to standard out. Extended information can be printed. + * @param xTarget The implementation which should be analysed. + * @param extendedInfo Should extended information be printed? + * @see com.sun.star.uno.XInterface + */ + private static void printInterfaces(XInterface xTarget, + boolean extendedInfo){ + Type[] types = getInterfaceTypes(xTarget); + if( null != types ) { + int nLen = types.length; + for( int i = 0; i < nLen ; i++ ) { + System.out.println(types[i].getTypeName()); + if (extendedInfo) { + printInterfaceInfo(types[i]); + System.out.println(); + } + } + } + } + + /** + * Returns all interface types of an implementation as a type array. + * @param xTarget The implementation which should be analyzed. + * @return An array with all interface types; null if there are none. + * @see com.sun.star.uno.XInterface + */ + private static Type[] getInterfaceTypes(XInterface xTarget) { + Type[] types = null; + XTypeProvider xTypeProvider = UnoRuntime.queryInterface( XTypeProvider.class, xTarget); + if( xTypeProvider != null ) + types = xTypeProvider.getTypes(); + return types; + } + + + + /** + * Prints information about an interface type. + * + * @param aType The type of the given interface. + * @see com.sun.star.uno.Type + */ + private static void printInterfaceInfo(Type aType) { + try { + Class<?> zClass = aType.getZClass(); + Method[] methods = zClass.getDeclaredMethods(); + for (int i=0; i<methods.length; i++) { + System.out.println("\t" + methods[i].getReturnType().getName() + + " " + methods[i].getName() + "()"); + } + } + catch (Exception ex) { + System.out.println("Exception occurred while printing InterfaceInfo"); + ex.printStackTrace(); + } + } + + /** + * Prints a string array to standard out. + * + * @param entries : The array to be printed. + */ + public static void printArray( String [] entries ) { + for ( int i=0; i< entries.length;i++ ) { + System.out.println(entries[i]); + } + } + + /** + * Print all information about the property <code>name</code> from + * the property set <code>PS</code> to standard out. + * @param PS The property set which should contain a property called + * <code>name</code>. + * @param name The name of the property. + * @see com.sun.star.beans.XPropertySet + */ + public static void printPropertyInfo(XPropertySet PS, String name) throws UnsupportedEncodingException { + printPropertyInfo(PS, name, new PrintWriter(new OutputStreamWriter(System.out, "UTF-8"))); + } + + /** + * Print all information about the property <code>name</code> from + * the property set <code>PS</code> to a print writer. + * @param PS The property set which should contain a property called + * <code>name</code>. + * @param name The name of the property. + * @param out The print writer which is used as output. + * @see com.sun.star.beans.XPropertySet + */ + public static void printPropertyInfo(XPropertySet PS, String name, + PrintWriter out) { + try { + XPropertySetInfo PSI = PS.getPropertySetInfo(); + PSI.getProperties(); + Property prop = PSI.getPropertyByName(name); + out.println("Property name is " + prop.Name); + out.println("Property handle is " + prop.Handle); + out.println("Property type is " + prop.Type.getTypeName()); + out.println("Property current value is " + + PS.getPropertyValue(name)); + out.println("Attributes :"); + short attr = prop.Attributes; + + if ((attr & PropertyAttribute.BOUND) != 0) + out.println("\t-BOUND"); + + if ((attr & PropertyAttribute.CONSTRAINED) != 0) + out.println("\t-CONSTRAINED"); + + if ((attr & PropertyAttribute.MAYBEAMBIGUOUS) != 0) + out.println("\t-MAYBEAMBIGUOUS"); + + if ((attr & PropertyAttribute.MAYBEDEFAULT) != 0) + out.println("\t-MAYBEDEFAULT"); + + if ((attr & PropertyAttribute.MAYBEVOID) != 0) + out.println("\t-MAYBEVOID"); + + if ((attr & PropertyAttribute.READONLY) != 0) + out.println("\t-READONLY"); + + if ((attr & PropertyAttribute.REMOVABLE) != 0) + out.println("\t-REMOVABLE"); + + if ((attr & PropertyAttribute.TRANSIENT) != 0) + out.println("\t-TRANSIENT"); + } catch(com.sun.star.uno.Exception e) { + out.println("Exception!!!!"); + e.printStackTrace(out); + } + } + + + + /** + * Print the names and the values of a sequence of <code>PropertyValue</code> + * to a print writer. + * @param ps The property which should displayed + * @param out The print writer which is used as output. + * @see com.sun.star.beans.PropertyValue + */ + private static void printPropertyValueSequencePairs(PropertyValue[] ps, PrintWriter out){ + for( int i = 0; i < ps.length; i++){ + printPropertyValuePairs(ps[i], out); + } + } + + + + /** + * Print the name and the value of a <code>PropertyValue</code> to a print writer. + * @param ps The property which should displayed + * @param out The print writer which is used as output. + * @see com.sun.star.beans.PropertyValue + */ + private static void printPropertyValuePairs(PropertyValue ps, PrintWriter out){ + + if (ps.Value instanceof String[] ){ + String[] values = (String[]) ps.Value; + StringBuilder oneValue = new StringBuilder("value is an empty String[]"); + if (values.length > 0){ + oneValue.append("['"); + for( int i=0; i < values.length; i++){ + oneValue.append(values[i]); + if (i+1 < values.length) oneValue.append("';'"); + } + oneValue.append("']"); + } + out.println("--------"); + out.println(" Name: '" + ps.Name + "' contains String[]:"); + out.println(oneValue.toString()); + out.println("--------"); + + } else if (ps.Value instanceof PropertyValue){ + out.println("--------"); + out.println(" Name: '" + ps.Name + "' contains PropertyValue:"); + printPropertyValuePairs((PropertyValue)ps.Value, out); + out.println("--------"); + + } else if (ps.Value instanceof PropertyValue[]){ + out.println("--------"); + out.println(" Name: '" + ps.Name + "' contains PropertyValue[]:"); + printPropertyValueSequencePairs((PropertyValue[])ps.Value, out); + out.println("--------"); + + } else { + out.println("Name: '" + ps.Name + "' Value: '" + ps.Value.toString() + "'"); + } + } + + /** + * Print the names of all properties inside this property set + * @param ps The property set which is printed. + * @see com.sun.star.beans.XPropertySet + */ + public static void printPropertiesNames(XPropertySet ps) { + XPropertySetInfo psi = ps.getPropertySetInfo(); + Property[] props = psi.getProperties(); + for (int i = 0; i < props.length; i++) + System.out.println(i + ". " + props[i].Name); + } + + /** + * Print the supported services of a UNO object. + * @param aObject A UNO object. + */ + public static void getSuppServices (Object aObject) { + XServiceInfo xSI = UnoRuntime.queryInterface(XServiceInfo.class,aObject); + printArray(xSI.getSupportedServiceNames()); + StringBuilder str = new StringBuilder("Therein not Supported Service"); + boolean notSupportedServices = false; + for (int i=0;i<xSI.getSupportedServiceNames().length;i++) { + if (! xSI.supportsService(xSI.getSupportedServiceNames()[i])) { + notSupportedServices = true; + str.append("\n").append(xSI.getSupportedServiceNames()[i]); + } + } + if (notSupportedServices) + System.out.println(str.toString()); + } +} diff --git a/qadevOOo/runner/util/utils.java b/qadevOOo/runner/util/utils.java new file mode 100644 index 000000000..1e6901fca --- /dev/null +++ b/qadevOOo/runner/util/utils.java @@ -0,0 +1,846 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * 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 . + */ +package util; + +import com.sun.star.frame.XController; +import com.sun.star.frame.XDispatch; +import com.sun.star.frame.XDispatchProvider; +import com.sun.star.frame.XModel; +import com.sun.star.lang.XComponent; + +import java.util.StringTokenizer; +import java.io.*; +import java.util.ArrayList; +import java.net.Socket; +import java.net.ServerSocket; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Arrays; + +import com.sun.star.awt.XToolkitExperimental; +import com.sun.star.beans.XPropertySet; +import com.sun.star.beans.Property; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.ucb.InteractiveAugmentedIOException; +import com.sun.star.ucb.XSimpleFileAccess; +import com.sun.star.lang.XServiceInfo; +import com.sun.star.util.URL; +import com.sun.star.util.XURLTransformer; +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.Type; +import com.sun.star.uno.XComponentContext; +import com.sun.star.util.XMacroExpander; + +import java.text.DecimalFormat; +import java.util.Calendar; +import java.util.Collections; +import java.util.GregorianCalendar; + +public class utils { + + /** + * + * This method adds the DOCPTH to a given file + * + * @param sDocName the file which should be completed to the test doc path + * @return $TESTDOCPATH/sDocName + */ + public static String getFullTestDocName(String sDocName) { + String docpth = System.getProperty("DOCPTH"); + if (docpth.endsWith("\\") || docpth.endsWith("/")) { + docpth = docpth.substring(0, docpth.length() - 1); + } + + System.out.println("docpth:" + docpth); + + String pthSep = System.getProperty("file.separator"); + + if (docpth.equals("unknown")) { + System.out.println("try to get tDoc from $SRC_ROOT/qadevOOo"); + String srcRoot = System.getProperty(PropertyName.SRC_ROOT); + if (srcRoot != null) { + File srcR = new File(srcRoot); + String[] list = srcR.list(new FilenameFilter() { + + public boolean accept(File dir, String name) { + return name.startsWith("qadevOOo"); + } + }); + + if (list != null && list[0] != null) { + String tDoc = srcRoot.concat(pthSep).concat(list[0]).concat(pthSep).concat("testdocs"); + + if (new File(tDoc).exists()) { + docpth = tDoc; + } + } + } + } + + if (docpth.startsWith("http:")) { + return docpth + "/" + sDocName; + } + String testdocPth = ""; + + if (docpth.equals("unknown")) { + System.out.println("try to get tDoc from OBJDSCS"); + String objdscPth = System.getProperty("OBJDSCS"); + if (objdscPth != null) { + int i = objdscPth.indexOf("objdsc"); + String arcPth = objdscPth.substring(0, i - 1); + testdocPth = arcPth + pthSep + "doc" + pthSep + "java" + + pthSep + "testdocs" + pthSep + sDocName; + } + } else { + testdocPth = docpth + pthSep + sDocName; + } + return testdocPth; + } + + /** + * + * This method adds the DOCPTH to a given file + * and changes the format to an file URL + * + */ + public static String getFullTestURL(String sDocName) { + String fullDocPath = getFullTestDocName(sDocName); + if (fullDocPath.startsWith("http:")) { + return fullDocPath; + } + if (fullDocPath.startsWith("file:")) { + return fullDocPath; + } + String prefix = null; + + // Windows: \\\\margritte\\qaapi\\workspace\\qadev\\testdocs/emptyChart.sds + if (fullDocPath.startsWith("\\\\")) { + prefix = "file:"; + } + + fullDocPath = fullDocPath.replace('\\', '/'); + if (prefix == null) { + if (fullDocPath.startsWith("//")) { + prefix = "file:/"; + } else if (fullDocPath.startsWith("/")) { + prefix = "file://"; + } else { + prefix = "file:///"; + } + } + if (!fullDocPath.endsWith("/")) { + File aFile = new File(fullDocPath); + if (aFile.isDirectory()) { + fullDocPath += "/"; + } + } + String fulldocURL = prefix + fullDocPath; + return fulldocURL; + } + + /** + * + * This method changes a given URL to a valid file URL + * + */ + public static String getFullURL(String sDocName) { + String fullDocPath = sDocName; + fullDocPath = fullDocPath.replace('\\', '/'); + + if (fullDocPath.startsWith("http:")) { + return fullDocPath; + } + if (fullDocPath.startsWith("ftp:")) { + return fullDocPath; + } + String prefix = ""; + if (!fullDocPath.startsWith("file:///")) { + if (fullDocPath.startsWith("//")) { + prefix = "file:"; + } else { + if (fullDocPath.startsWith("/")) { + prefix = "file://"; + } + else + { + prefix = "file:///"; + } + } + } + if (!fullDocPath.endsWith("/")) { + File aFile = new File(fullDocPath); + if (aFile.isDirectory()) { + fullDocPath += "/"; + } + } + String fulldocURL = prefix + fullDocPath; + + return fulldocURL; + } + + /** + * + * This method gets the user dir of the connected office + * + */ + public static String getOfficeUserPath(XMultiServiceFactory msf) { + // get a folder located in the user dir + String userPath = getOfficeSettingsValue(msf, "UserConfig"); + + // strip the returned folder to the user dir + if (userPath.charAt(userPath.length() - 1) == '/') { + userPath = userPath.substring(0, userPath.length() - 1); + } + int index = userPath.lastIndexOf('/'); + if (index != -1) { + userPath = userPath.substring(0, index); + } + + return userPath; + } + + /** + * In the office there are some settings available. This function + * returns the value of the given setting name. For Example the setting name "Temp" + * "Temp" returns the temp folder of the office instance. + * @param msf a XMultiServiceFactory + * @param setting the name of the setting the value should be returned. + * For example "Temp" returns the temp folder of the current office instance. + * @see com.sun.star.util.PathSettings + * @return the value as String + */ + private static String getOfficeSettingsValue(XMultiServiceFactory msf, String setting) { + try { + Object settings = msf.createInstance("com.sun.star.comp.framework.PathSettings"); + XPropertySet pthSettings = (XPropertySet) AnyConverter.toObject( + new Type(XPropertySet.class), settings); + return (String) pthSettings.getPropertyValue(setting); + } catch (com.sun.star.uno.Exception ex) { + throw new RuntimeException(ex); + } + } + + /** + * This method returns the temp directory of the user. + * Since Java 1.4 it is not possible to read environment variables. To workaround + * this, the Java parameter -D could be used. + */ + public static String getUsersTempDir() { + String tempDir = System.getProperty("my.temp"); + if (tempDir == null) { + tempDir = System.getProperty("my.tmp"); + if (tempDir == null) { + tempDir = System.getProperty("java.io.tmpdir"); + } + } + // remove ending file separator + if (tempDir.endsWith(System.getProperty("file.separator"))) { + tempDir = tempDir.substring(0, tempDir.length() - 1); + } + + return tempDir; + } + + /** + * + * This method gets the temp dir of the connected office + * + */ + public static String getOfficeTemp(XMultiServiceFactory msf) { + String url = getOfficeUserPath(msf) + "/test-temp/"; + try { + new File(new URI(url)).mkdir(); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + return url; + } + + /** + * Gets StarOffice temp directory without 'file:///' prefix. + * For example is useful for Registry URL specifying. + * @msf Office factory for accessing its settings. + * @return SOffice temporary directory in form for example + * 'd:/Office60/user/temp/'. + */ + public static String getOfficeTempDir(XMultiServiceFactory msf) { + + String dir = getOfficeTemp(msf); + + int idx = dir.indexOf("file:///"); + + if (idx < 0) { + return dir; + } + + dir = dir.substring("file:///".length()); + + idx = dir.indexOf(':'); + + // is the last character a '/' or a '\'? + boolean lastCharSet = dir.endsWith("/") || dir.endsWith("\\"); + + if (idx < 0) { // linux or solaris + dir = "/" + dir; + dir += lastCharSet ? "" : "/"; + } else { // windows + dir += lastCharSet ? "" : "\\"; + } + + return dir; + } + + /** + * Gets StarOffice temp directory without 'file:///' prefix. + * and System dependent file separator + */ + public static String getOfficeTempDirSys(XMultiServiceFactory msf) { + + String dir = getOfficeTemp(msf); + String sysDir = ""; + + int idx = dir.indexOf("file://"); + + // remove leading 'file://' + if (idx < 0) { + sysDir = dir; + } else { + sysDir = dir.substring("file://".length()); + } + + // append '/' if not there (e.g. linux) + if (sysDir.charAt(sysDir.length() - 1) != '/') { + sysDir += "/"; + } + + // remove leading '/' and replace others with '\' on windows machines + if (sysDir.indexOf(':') != -1) { + sysDir = sysDir.substring(1); + sysDir = sysDir.replace('/', '\\'); + } + return sysDir; + } + + /** + * converts a fileURL to a system URL + * @param fileURL a file URL + * @return a system URL + */ + public static String getSystemURL(String fileURL) { + String sysDir = ""; + + int idx = fileURL.indexOf("file://"); + + // remove leading 'file://' + if (idx < 0) { + sysDir = fileURL; + } else { + sysDir = fileURL.substring("file://".length()); + } + + // remove leading '/' and replace others with '\' on windows machines + if (sysDir.indexOf(':') != -1) { + sysDir = sysDir.substring(1); + sysDir = sysDir.replace('/', '\\'); + } + return sysDir; + } + + /** + * This method check via Office the existence of the given file URL + * @param msf the multiservice factory + * @param fileURL the file which existence should be checked + * @return true if the file exists, else false + */ + public static boolean fileExists(XMultiServiceFactory msf, String fileURL) throws com.sun.star.uno.Exception { + Object fileacc = msf.createInstance("com.sun.star.comp.ucb.SimpleFileAccess"); + XSimpleFileAccess simpleAccess = UnoRuntime.queryInterface(XSimpleFileAccess.class, + fileacc); + return simpleAccess.exists(fileURL); + } + + /** + * This method deletes via office the given file URL. It checks the existence + * of <CODE>fileURL</CODE>. If exists it will be deleted. + * @param xMsf the multiservice factory + * @param fileURL the file to delete + * @return true if the file could be deleted or the file does not exist + */ + public static boolean deleteFile(XMultiServiceFactory xMsf, String fileURL) { + boolean delete = true; + try { + + Object fileacc = xMsf.createInstance("com.sun.star.comp.ucb.SimpleFileAccess"); + XSimpleFileAccess simpleAccess = UnoRuntime.queryInterface(XSimpleFileAccess.class, + fileacc); + if (simpleAccess.exists(fileURL)) { + simpleAccess.kill(fileURL); + } + + } catch (Exception e) { + System.out.println("Couldn't delete file '" + fileURL + "'"); + e.printStackTrace(); + delete = false; + } + return delete; + } + + /** + * This method copies via office a given file to a new one + * @param xMsf the multi service factory + * @param source the source file + * @param destination the destination file + * @return true at success + */ + public static boolean copyFile(XMultiServiceFactory xMsf, String source, String destination) { + boolean res = false; + try { + Object fileacc = xMsf.createInstance("com.sun.star.comp.ucb.SimpleFileAccess"); + XSimpleFileAccess simpleAccess = UnoRuntime.queryInterface(XSimpleFileAccess.class, + fileacc); + if (!simpleAccess.exists(destination)) { + simpleAccess.copy(source, destination); + } + + res = true; + } catch (Exception e) { + System.out.println("Couldn't copy file '" + source + "' -> '" + destination + "'"); + e.printStackTrace(); + res = false; + } + return res; + } + + private static void overwriteFile_impl( + XMultiServiceFactory xMsf, String oldF, String newF) + throws InteractiveAugmentedIOException + { + try { + Object fileacc = xMsf.createInstance("com.sun.star.comp.ucb.SimpleFileAccess"); + + XSimpleFileAccess simpleAccess = UnoRuntime.queryInterface(XSimpleFileAccess.class, + fileacc); + if (simpleAccess.exists(newF)) { + simpleAccess.kill(newF); + } + simpleAccess.copy(oldF, newF); + } catch (InteractiveAugmentedIOException e) { + throw e; + } catch (com.sun.star.uno.Exception ex) { + throw new RuntimeException("Could not copy " + oldF + " to " + newF, ex); + } + } + + /** + * Copies file to a new location using OpenOffice.org features. If the target + * file already exists, the file is deleted. + * + * @returns <code>true</code> if the file was successfully copied, + * <code>false</code> if some errors occurred (e.g. file is locked, used + * by another process). + */ + public static boolean tryOverwriteFile( + XMultiServiceFactory xMsf, String oldF, String newF) + { + try { + overwriteFile_impl(xMsf, oldF, newF); + } catch (InteractiveAugmentedIOException e) { + return false; + } + return true; + } + + + + public static boolean hasPropertyByName(XPropertySet props, String aName) { + Property[] list = props.getPropertySetInfo().getProperties(); + boolean res = false; + for (int i = 0; i < list.length; i++) { + String the_name = list[i].Name; + if (aName.equals(the_name)) { + res = true; + } + } + return res; + } + + /** + * + * This method returns the implementation name of a given object + * + */ + public static String getImplName(Object aObject) { + XServiceInfo xSI = UnoRuntime.queryInterface(XServiceInfo.class, aObject); + return xSI == null ? "Unknown, does not implement XServiceInfo" : xSI.getImplementationName(); + } + + /** + * + * This method checks if an Object is void + * + */ + public static boolean isVoid(Object aObject) { + if (aObject instanceof com.sun.star.uno.Any) { + com.sun.star.uno.Any oAny = (com.sun.star.uno.Any) aObject; + return oAny.getType().getTypeName().equals("void"); + } else { + return false; + } + + } + + /** + * Scan localhost for the next free port-number from a starting port + * on. If the starting port is smaller than 1024, port number starts with + * 10000 as default, because numbers < 1024 are never free on unix machines. + * @param startPort The port where scanning starts. + * @return The next free port. + */ + public static int getNextFreePort(int startPort) { + if (startPort < 1024) { + startPort = 10000; + } + for (int port = startPort; port < 65536; port++) { + System.out.println("Scan port " + port); + try { + // first trying to establish a server-socket on localhost + // fails if there is already a server running + ServerSocket sSock = new ServerSocket(port); + sSock.close(); + } catch (IOException e) { + System.out.println(" -> server: occupied port " + port); + continue; + } + try { + Socket sock = new Socket("localhost", port); + System.out.println(" -> socket: occupied port: " + port); + try { + sock.close(); + } catch (IOException ex) { + // ignore close exception + } + } catch (IOException e) { + System.out.println(" -> free port"); + return port; + } + } + return 65535; + } + + public static URL parseURL(XMultiServiceFactory xMSF, String url) { + URL[] rUrl = new URL[1]; + rUrl[0] = new URL(); + rUrl[0].Complete = url; + + XURLTransformer xTrans = null; + try { + Object inst = xMSF.createInstance("com.sun.star.util.URLTransformer"); + xTrans = UnoRuntime.queryInterface(XURLTransformer.class, inst); + } catch (com.sun.star.uno.Exception e) { + } + + if (xTrans != null) + xTrans.parseStrict(rUrl); + + return rUrl[0]; + } + + public static String getOfficeURL(XMultiServiceFactory msf) throws com.sun.star.uno.Exception { + Object settings = msf.createInstance("com.sun.star.util.PathSettings"); + XPropertySet settingProps = UnoRuntime.queryInterface(XPropertySet.class, settings); + String path = (String) settingProps.getPropertyValue("Module"); + return path; + } + + + + /** + * Get an array of all property names from the property set. With the include + * and exclude parameters the properties can be filtered. <br> + * Set excludePropertyAttribute = 0 and includePropertyAttribute = 0 + * to include all and exclude none. + * @param props The instance of XPropertySet + * @param includePropertyAttribute Properties without these attributes are filtered and will not be returned. + * @param excludePropertyAttribute Properties with these attributes are filtered and will not be returned. + * @param array of string names of properties that will be skipped + * @return A String array with all property names. + * @see com.sun.star.beans.XPropertySet + * @see com.sun.star.beans.Property + * @see com.sun.star.beans.PropertyAttribute + */ + public static String[] getFilteredPropertyNames(XPropertySet props, short includePropertyAttribute, + short excludePropertyAttribute, String[] skipList) { + Property[] the_props = props.getPropertySetInfo().getProperties(); + ArrayList<String> l = new ArrayList<String>(); + for (int i = 0; i < the_props.length; i++) { + if (Arrays.asList(skipList).contains(the_props[i].Name)) + continue; + boolean exclude = ((the_props[i].Attributes & excludePropertyAttribute) != 0); + boolean include = (includePropertyAttribute == 0) || + ((the_props[i].Attributes & includePropertyAttribute) != 0); + if (include && !exclude) { + l.add(the_props[i].Name); + } + } + Collections.sort(l); + String[] names = new String[l.size()]; + names = l.toArray(names); + return names; + } + + /** Causes the thread to sleep some time. + * This is the default call, which waits for 500ms. + */ + public static void shortWait() { + pause(utils.DEFAULT_SHORT_WAIT_MS); + } + + /** Causes the thread to sleep some time. + */ + public static void pause(int milliseconds) { + try { + Thread.sleep(milliseconds); + } catch (InterruptedException e) { + System.out.println("While waiting :" + e); + } + } + + public static void waitForEventIdle(XMultiServiceFactory xMSF) { + try { + XToolkitExperimental xToolkit = UnoRuntime.queryInterface( + XToolkitExperimental.class, + xMSF.createInstance("com.sun.star.awt.Toolkit")); + xToolkit.processEventsToIdle(); + } catch (com.sun.star.uno.Exception ex) { + throw new RuntimeException(ex); + } + } + + /** + * Validate the AppExecutionCommand. Returned is an error message, starting + * with "Error:", or a warning, if the command might work. + * @param appExecCommand The application execution command that is checked. + * @param os The operating system where the check runs. + * @return The error message, or OK, if no error was detected. + */ + public static String validateAppExecutionCommand(String appExecCommand, String os) { + String errorMessage = "OK"; + appExecCommand = appExecCommand.replace("\"", ""); + appExecCommand = appExecCommand.replace("'", ""); + StringTokenizer commandTokens = new StringTokenizer(appExecCommand, " \t"); + String officeExecCommand = "soffice"; + StringBuilder sb = new StringBuilder(); + // is there a 'soffice' in the command? 2do: eliminate case sensitivity on windows + int index = -1; + while (commandTokens.hasMoreTokens() && index == -1) { + sb.append(commandTokens.nextToken()).append(" "); + index = sb.indexOf(officeExecCommand); + } + if (index == -1) { + errorMessage = "Error: Your 'AppExecutionCommand' parameter does not " + + "contain '" + officeExecCommand + "'."; + } else { + String officeExecutable = sb.toString(); + // does the directory exist? + officeExecutable = officeExecutable.trim(); + String officePath = officeExecutable.substring(0, index); + File f = new File(officePath); + if (!f.exists() || !f.isDirectory()) { + errorMessage = "Error: Your 'AppExecutionCommand' parameter does not " + + "point to a valid system directory: " + officePath; + } else { + // is it an office installation? + f = new File(officeExecutable); + // one try for windows platform can't be wrong... + if (!f.exists() || !f.isFile()) { + f = new File(officeExecutable + ".exe"); + } + if (!f.exists() || !f.isFile()) { + errorMessage = "Error: Your 'AppExecutionCommand' parameter does not " + + "point to a valid office installation."; + } else { + // do we have the accept parameter? + boolean gotNoAccept = true; + while (commandTokens.hasMoreElements()) { + String officeParam = commandTokens.nextToken(); + if (officeParam.indexOf("--accept=") != -1) { + gotNoAccept = false; + errorMessage = validateConnectString(officeParam, true); + } + } + if (gotNoAccept) { + errorMessage = "Error: Your 'AppExecutionCommand' parameter does not " + + "contain a '--accept' parameter for connecting the office."; + } + } + } + } + return errorMessage; + } + + /** + * Validate the connection string. Returned is an error message, starting + * with "Error:", or a warning, if the command might work. + * @param connectString The connection string that is checked. + * @param checkAppExecutionCommand If the AppExecutionCommand is checked, the error message is different. + * @return The error message, or OK, if no error was detected. + */ + private static String validateConnectString(String connectString, boolean checkAppExecutionCommand) { + String acceptPrefix = ""; + if (checkAppExecutionCommand) { + acceptPrefix = "--accept="; + } + + String errorMessage = "OK"; + // a warning, if an unknown connection method is used + if (connectString.indexOf("socket") != -1) { + if (connectString.indexOf(acceptPrefix + "socket,host=") == -1 || + connectString.indexOf("port=") == -1) { + if (checkAppExecutionCommand) { + errorMessage = "Error: The '--accept' parameter contains a syntax error: It should be like: '--accept=socket,host=localhost,port=8100;urp;"; + } else { + errorMessage = "Error: The 'ConnectionString' parameter contains a syntax error: It should be like: 'socket,host=localhost,port=8100'"; + } + } + } else if (connectString.indexOf("pipe") != -1) { + if (connectString.indexOf(acceptPrefix + "pipe,name=") == -1) { + if (checkAppExecutionCommand) { + errorMessage = "Error: The '--accept' parameter contains a syntax error: It should be like: '--accept=pipe,name=myuniquename;urp;'"; + } else { + errorMessage = "Error: The 'ConnectionString' parameter contains a syntax error: It should be like: 'pipe,name=myuniquename'"; + } + } + } else { + if (checkAppExecutionCommand) { + errorMessage = "Warning: The '--accept' parameter contains an unknown connection method."; + } else { + errorMessage = "Warning: The 'ConnectionString' parameter contains an unknown connection method."; + } + } + return errorMessage; + } + + /** + * expand macrofied strings like <CODE>${$ORIGIN/bootstrap.ini:UserInstallation}</CODE> or + * <CODE>$_OS</CODE> + * @param xMSF the MultiServiceFactory + * @param expand the string to expand + * @throws java.lang.Exception was thrown on any exception + * @return return the expanded string + * @see com.sun.star.util.XMacroExpander + */ + public static String expandMacro(XMultiServiceFactory xMSF, String expand) { + try { + XPropertySet xPS = UnoRuntime.queryInterface(XPropertySet.class, xMSF); + XComponentContext xContext = UnoRuntime.queryInterface(XComponentContext.class, + xPS.getPropertyValue("DefaultContext")); + XMacroExpander xME = UnoRuntime.queryInterface(XMacroExpander.class, + xContext.getValueByName("/singletons/com.sun.star.util.theMacroExpander")); + return xME.expandMacros(expand); + } catch (Exception e) { + throw new RuntimeException("could not expand macro", e); + } + + } + + + + /** + * dispatches given <CODE>URL</CODE> to the document <CODE>XComponent</CODE> + * @param xMSF the <CODE>XMultiServiceFactory</CODE> + * @param xDoc the document where to dispatch + * @param URL the <CODE>URL</CODE> to dispatch + * @throws java.lang.Exception throws <CODE>java.lang.Exception</CODE> on any error + */ + public static void dispatchURL(XMultiServiceFactory xMSF, XComponent xDoc, String URL) throws java.lang.Exception { + XModel aModel = UnoRuntime.queryInterface(XModel.class, xDoc); + + XController xCont = aModel.getCurrentController(); + + dispatchURL(xMSF, xCont, URL); + + } + + /** + * dispatches given <CODE>URL</CODE> to the <CODE>XController</CODE> + * @param xMSF the <CODE>XMultiServiceFactory</CODE> + * @param xCont the <CODE>XController</CODE> to query for a XDispatchProvider + * @param URL the <CODE>URL</CODE> to dispatch + */ + private static void dispatchURL(XMultiServiceFactory xMSF, XController xCont, String URL) { + try { + + XDispatchProvider xDispProv = UnoRuntime.queryInterface(XDispatchProvider.class, xCont); + + XURLTransformer xParser = UnoRuntime.queryInterface( + XURLTransformer.class, + xMSF.createInstance("com.sun.star.util.URLTransformer")); + + // Because it's an in/out parameter we must use an array of URL objects. + URL[] aParseURL = new URL[1]; + aParseURL[0] = new URL(); + aParseURL[0].Complete = URL; + xParser.parseStrict(aParseURL); + + URL aURL = aParseURL[0]; + + XDispatch xDispatcher = xDispProv.queryDispatch(aURL, "", 0); + xDispatcher.dispatch(aURL, null); + + waitForEventIdle(xMSF); + + } catch (Exception e) { + throw new RuntimeException("Could not dispatch URL '" + URL + "'", e); + } + } + + /** returns a String which contains the current date and time<br> + * format: [DD.MM.YYYY - HH:MM:SS::mm] + * + ** @return a String which contains the current date and time + */ + public static String getDateTime() { + + Calendar cal = new GregorianCalendar(); + DecimalFormat dfmt = new DecimalFormat("00"); + String dateTime = dfmt.format(cal.get(Calendar.DAY_OF_MONTH)) + "." + + dfmt.format(cal.get(Calendar.MONTH) + 1) + "." + + dfmt.format(cal.get(Calendar.YEAR)) + " - " + + dfmt.format(cal.get(Calendar.HOUR_OF_DAY)) + ":" + + dfmt.format(cal.get(Calendar.MINUTE)) + ":" + + dfmt.format(cal.get(Calendar.SECOND)) + "," + + dfmt.format(cal.get(Calendar.MILLISECOND)); + return "[" + dateTime + "]"; + } + + /** + * Default short wait time for the Office + */ + public static final int DEFAULT_SHORT_WAIT_MS = 500; + + /// see rtl/math.hxx + public static boolean approxEqual( double a, double b ) + { + if( a == b ) + return true; + double x = a - b; + return (x < 0.0 ? -x : x) + < ((a < 0.0 ? -a : a) * (1.0 / (16777216.0 * 16777216.0))); + } +} |