From ed5640d8b587fbcfed7dd7967f3de04b37a76f26 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sun, 7 Apr 2024 11:06:44 +0200 Subject: Adding upstream version 4:7.4.7. Signed-off-by: Daniel Baumann --- .../filter/detection/typeDetection/Helper.java | 431 ++++++++++++++++ .../detection/typeDetection/TypeDetection.java | 546 +++++++++++++++++++++ .../detection/typeDetection/TypeDetection.props | 31 ++ .../filter/detection/typeDetection/files.csv | 117 +++++ .../filter/detection/typeDetection/makefile.mk | 109 ++++ .../detection/typeDetection/preselectedFilter.csv | 6 + .../detection/typeDetection/preselectedType.csv | 6 + .../filter/detection/typeDetection/serviceName.csv | 6 + .../filter/misc/FinalizedMandatoryTest.java | 304 ++++++++++++ .../filter/misc/TypeDetection6FileFormat.java | 127 +++++ .../filter/misc/TypeDetection6FileFormat.xcu | 42 ++ 11 files changed, 1725 insertions(+) create mode 100644 filter/qa/complex/filter/detection/typeDetection/Helper.java create mode 100644 filter/qa/complex/filter/detection/typeDetection/TypeDetection.java create mode 100644 filter/qa/complex/filter/detection/typeDetection/TypeDetection.props create mode 100644 filter/qa/complex/filter/detection/typeDetection/files.csv create mode 100644 filter/qa/complex/filter/detection/typeDetection/makefile.mk create mode 100644 filter/qa/complex/filter/detection/typeDetection/preselectedFilter.csv create mode 100644 filter/qa/complex/filter/detection/typeDetection/preselectedType.csv create mode 100644 filter/qa/complex/filter/detection/typeDetection/serviceName.csv create mode 100644 filter/qa/complex/filter/misc/FinalizedMandatoryTest.java create mode 100644 filter/qa/complex/filter/misc/TypeDetection6FileFormat.java create mode 100644 filter/qa/complex/filter/misc/TypeDetection6FileFormat.xcu (limited to 'filter/qa/complex') diff --git a/filter/qa/complex/filter/detection/typeDetection/Helper.java b/filter/qa/complex/filter/detection/typeDetection/Helper.java new file mode 100644 index 000000000..23eb07fc4 --- /dev/null +++ b/filter/qa/complex/filter/detection/typeDetection/Helper.java @@ -0,0 +1,431 @@ +/* + * 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 complex.filter.detection.typeDetection; + +import com.sun.star.beans.PropertyValue; +import com.sun.star.io.NotConnectedException; +import com.sun.star.io.XInputStream; + +import helper.StreamSimulator; + +import java.io.*; +import java.net.URL; +import java.net.URLConnection; +import java.util.Iterator; +import java.util.HashMap; +import java.util.StringTokenizer; +import java.util.ArrayList; + +import lib.TestParameters; +import share.LogWriter; +import util.PropertyName; +import util.utils; + + + +/** Helper class for "TypeDetection" + * This class do file handling. + */ +public class Helper { + + /** The runner log writer + * @member m_log for log purposes + * @member m_sTestDocPath directory for searching files to load + * @member m_vFiles list of all files described in "files.csv" + * @member m_hFileURLs contains the position of a file name in the m_vFiles Vector + * @member m_hFileTypes contains the position of a file type in the m_vFiles Vector + * @member m_param the test parameters + */ + + private final LogWriter m_log; + + private final String m_sTestDocPath; + + private final ArrayList> m_vFiles; + + private final HashMap m_hFileURLs = new HashMap(); + + private final HashMap m_hFileTypes = new HashMap(); + + private final TestParameters m_param; + + /** + * construct a new instance of this class + * It creates the "todo" list and position lists for URL and + * and Type inside the "todo" list + * + * @param param the test parameters + * + * @param log the log writer + */ + + public Helper(TestParameters param, LogWriter log) { + + m_param = param; + m_log = log; + + + // get all files from the given directory + m_sTestDocPath = (String)param.get("TestDocumentPath"); + + // get all files from "files.csv" + m_vFiles = getToDoList((String)m_param.get("csv.files")); + + createFilesList(); + } + + + /** Reads a comma separated file (CSV). Every line of the file is + * represented by an Vector entry. Every data entry of a row is + * also stored in a Vector. So the returned value is a + * Vector[][] where the first dimension represents a row + * and the second dimension includes the data values. + * @param csvFileName the name of the csv file + * @return Vector filled with Vector filled with data of a row + */ + public ArrayList> getToDoList(String csvFileName){ + + try { + + ArrayList> vAll = new ArrayList>(); + ArrayList vFields = new ArrayList(); + + // get content of file + ArrayList content = getCSVFileContent(csvFileName); + + // remove superfluous content like "#" started lines + content = removeSuperfluousContent(content); + + // replace all place holders in file + content = replacePlaceHolder(content); + + // create Enumeration + Iterator contentEnum = content.iterator(); + + // the first line contains field names of the columns + // split line by ";" + StringTokenizer fields = new StringTokenizer( + contentEnum.next(),";"); + int fieldCount = 0; + while (fields.hasMoreElements()){ + vFields.add(fields.nextToken()); + fieldCount++; + } + + // fill vData with data of CSV-row + while (contentEnum.hasNext()){ + ArrayList vData = new ArrayList(); + + StringTokenizer data = new StringTokenizer( + contentEnum.next(),";", true); + + // example: data = "firstData;secondData;;forthData" + // => three tokens => missing one data because the imagine + // "thirdData" was not received by data.nextToken() + // Therefore here comes a special handling for empty data + boolean nextIsData = false; + int dataCount = 0; + while (data.hasMoreTokens()) { + String myToken = data.nextToken(); + // if the "thirdData" will be received, myToken=";" but + // vData must add an empty String + if (myToken.equals(";")){ + if (nextIsData ) { + vData.add(""); + dataCount++; + nextIsData = false; + } + nextIsData = true; + } else { + vData.add(myToken); + dataCount++; + nextIsData = false; + } + } + for (int i=dataCount; i < fieldCount; i++) vData.add(""); + vAll.add(vData); + } + + + return vAll; + + } catch(ClassCastException e) { + e.printStackTrace(); + } + return null; + } + + /** The csv files "files", "preselectedFilter", "preselectedType" and + * "serviceName" are delivered beside this class. This function seeks for + * the csv files and read them. + * @param csvFileName the name of the csv file + * @return a Vector containing the content of the file. if the file + * cannot be read + */ + + private ArrayList getCSVFileContent(String csvFileName) { + try { + ArrayList content = new ArrayList(); + BufferedReader br; + String line; + if ( m_param.getBool(PropertyName.DEBUG_IS_ACTIVE) ) { + System.out.println("Looking for "+csvFileName); + } + + URL url = getClassURL(csvFileName); + + if (url != null) { + URLConnection connection = url.openConnection(); + InputStream in = connection.getInputStream(); + + br = new BufferedReader(new InputStreamReader(in)); + try { + while( ( line = br.readLine() ) != null ) { + content.add( line ); + } + } catch (IOException e) { + br.close(); + return null; + } + br.close(); + return content; + } + + }catch (IOException e) { + }catch(NullPointerException e) { + return null; + } + return null; + } + + /** returns a XInputStream of given file + * @param filePath the path to the file which should be loaded + * @return the XInputStream, if the + * file cannot be read + * @throws NotConnectedException was thrown if it was not possible to open filePath + */ + public XInputStream getFileStream( String filePath ) + throws NotConnectedException { + return new StreamSimulator(filePath, true, m_param); + } + + /** replaces place holder in preselectedFilter. + * Because of filter names depend on StarOffice version like + * "StarOffice 6.0 Textdokument" or ""StarSuite 7 Textdokument" + * The filter names must be changed. The place holder will be replaced + * by an equivalent in "typeDetection.props" + * @param content the content of a csv file + * @return changed file content + */ + private ArrayList replacePlaceHolder(ArrayList content){ + + ArrayList vReturn = new ArrayList(); + + ArrayList placeHolders = new ArrayList(); + Iterator paramsIter = m_param.keySet().iterator(); + String placeHolder = (String)m_param.get("placeHolder"); + + // get all place holders from typeDetection.csv + while (paramsIter.hasNext()){ + String holderKey = paramsIter.next(); + if (holderKey.startsWith(placeHolder)){ + placeHolders.add(holderKey); + } + } + + // replace all occurrences of place holders in 'CSVData' + Iterator cont = content.iterator(); + + while( cont.hasNext() ) { + + String line = cont.next(); + String newLine = line; + Iterator holders = placeHolders.iterator(); + + while( holders.hasNext() ) { + + String holder = holders.next(); + int startPos = line.indexOf(holder); + + if (startPos > -1){ + try{ + String holderValue = (String) m_param.get(holder); + + newLine = newLine.substring(0,startPos) + holderValue + + newLine.substring(startPos + holder.length()); + + } catch (java.lang.IndexOutOfBoundsException e){ + m_log.println("ERROR: problems while creating placeholder" + + " replaced list: "+ e); + } + } + } + vReturn.add(newLine); + } + return vReturn; + } + + /** Removes lines of an ascii file content which starts with "#" + * or are empty + * @param content content of a csv file + * @return a stripped Vector + */ + private ArrayList removeSuperfluousContent(ArrayList content){ + ArrayList newContent = new ArrayList(); + Iterator cont = content.iterator(); + while( cont.hasNext() ) { + String line = cont.next(); + if (( ! line.startsWith( "#" ))&& ( line.length() != 0 )) { + newContent.add( line ); + } + } + return newContent; + } + + /** returns a MediaDescriptor filled with given properties and + * values. + * @param propNames String Array of property names + * @param values Object Array of property values + * @return PropertyValue[] + * @see com.sun.star.beans.PropertyValue + * @see com.sun.star.document.MediaDescriptor + */ + public 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 ; + } + + /** Appends system file separator if needed + * @param s the system path + * @return system path with ending system file separator + */ + public String ensureEndingFileSep(String s){ + if(s != null && !s.equals("") && !s.endsWith(File.separator)){ + s = s.trim() + File.separator; + }else if(s == null) + s = ""; + return s; + } + + /** Returns the file URL for the given file name assembled by + * "TestDocumentPath" of typeDetection.props and "fileURL" of files.csv + * @param fileAlias the alias name of the file + * @return file URL + * @throws FileAliasNotFoundException was thrown if alias does not exist + */ + public String getURLforfileAlias(String fileAlias) + throws FileAliasNotFoundException{ + try{ + String fileURL = m_hFileURLs.get(fileAlias).toString(); + return utils.getFullURL(ensureEndingFileSep(m_sTestDocPath) + fileURL); + } catch (NullPointerException e){ + throw new FileAliasNotFoundException(fileAlias, e); + } + + } + + /** Returns the file type for the given file name containing in files.csv + * @param fileAlias the alias name of the file + * @return file type + * @throws FileAliasNotFoundException was thrown if not alias was thrown + */ + public String getTypeforfileAlias(String fileAlias) + throws FileAliasNotFoundException{ + try{ + return m_hFileTypes.get(fileAlias).toString(); + } catch (NullPointerException e){ + throw new FileAliasNotFoundException(fileAlias, e); + } + } + + /** + * Fills the Hashtable m_hFileURLs with all file names and their URL + * and the Hashtable m_hFileTypes with all file names and their file + * type name. This information is extracted from "files.csv" + * This is for faster access to get fileURL and fileType of fileAlias + */ + private void createFilesList(){ + for (int i = 0; i < m_vFiles.size();i++){ + ArrayList toDo = m_vFiles.get(i); + m_hFileURLs.put(toDo.get(0), toDo.get(1)); + m_hFileTypes.put(toDo.get(0), toDo.get(2)); + } + } + + + /** Validate the returned file type for the file alias with the + * possible file types + * @param currentFileType the returned file type + * @param fileTypes all possible file types + * @return true if valid + */ + public boolean checkFileType(String currentFileType, String fileTypes){ + + StringTokenizer data = new StringTokenizer(fileTypes,":", true); + + boolean found = false; + while (data.hasMoreElements()) { + + String actualFileType = data.nextElement().toString(); + + found = found || currentFileType.equals(actualFileType); + } + return found; + } + + /** creates an input/output parameter of PropertyValue[]. + * @return PropertyValue[][] + * @param PropVal a PropertyValue + */ + public PropertyValue[][] createInOutPropertyValue(PropertyValue[] PropVal){ + PropertyValue[][] dummy = new PropertyValue[1][]; + dummy[0] = PropVal; + return dummy; + } + + private URL getClassURL(String fileName){ + String PackagePath = this.getClass().getPackage().getName().replace('.','/'); + return this.getClass().getResource("/" + PackagePath +"/" + fileName); + } + + public String getClassURLString(String fileName){ + return getClassURL(fileName).toString().replaceAll("file:",""); + } + + +} + +/** This exception should be thrown if a method seeks for an invalid alias name */ +class FileAliasNotFoundException extends java.lang.Exception{ + /** throws error message with wrong alias name + * @param fileAlias the alias name + */ + public FileAliasNotFoundException(String fileAlias, Throwable cause){ + super("Could not get '"+fileAlias +"'", cause); + } +} diff --git a/filter/qa/complex/filter/detection/typeDetection/TypeDetection.java b/filter/qa/complex/filter/detection/typeDetection/TypeDetection.java new file mode 100644 index 000000000..2c7a6934a --- /dev/null +++ b/filter/qa/complex/filter/detection/typeDetection/TypeDetection.java @@ -0,0 +1,546 @@ +/* + * 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 complex.filter.detection.typeDetection; + +import com.sun.star.beans.PropertyValue; +import com.sun.star.document.XTypeDetection; +import com.sun.star.io.NotConnectedException; +import com.sun.star.io.XInputStream; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XInterface; +import complexlib.ComplexTestCase; +import java.io.File; + +import java.util.Iterator; +import java.util.ArrayList; +import util.utils; + + + +/** Check "TypeDetection" + *

+ * This test will check the file type detection. This will be done by filling + * properties of a MediaDescriptor. + * + * In the test method checkByURLonly the + * MediaDescriptor was filled at once with the URL of a test + * file. At second it was filled with a XInputStream from test + * file. In both subtests the returned file type must match with an expected + * type. + * + * In the test method checkPreselectedType the + * MediaDescriptor was filled with the URL of the test file and + * with the name of a type which should be used. The returned type of the + * TypeDetection must match with an expected type. + * + * In the test method checkPreselectedFilter the + * MediaDescriptor was filled with the URL of the test file and + * with the name of a filter which should be used. The returned type of the + * TypeDetection must match with an expected type. + * + * In the test method checkPreselectedDocService the + * MediaDescriptor was filled with the URL of the test file and + * with the name of a document service which should be used. The returned type + * of the TypeDetection must match with an expected type. + * + * + * To get information on which test file should support which type, filter and + * document service, this information was collected from configuration files: + *

+ *

+ *

+ * typeDetection.props

+ * At first there will be the typeDetection.props. Here the following + * properties should be set (with example values): + * + * TestDocumentPath=file:///path/to/my/testdocuments + * placeHolder=% + * %SO6productname=StarOffice + * %SO6formatversion=6.0 + * + * TestDocumentPath: this is the path to your test documents. If + * you have grouped your documents ie. by writer, calc, ... then it should be + * the root path. To specify the particular sub folders you have to use + * csv.files + *

+ * files.csv: In this file all test documents are listed. + * Syntax: fileAlias;fileURL;defaultURLFileType;StreamFileTypes + * Example: + * + * Writer6_1;Writer/Writer6.sxw;writer_StarOffice_XML_Writer;writer_StarOffice_XML_Writer + * text1;Writer/Text.txt:generic_Text:generic_Text + * + * The first example shows you the following: + * Writer6_1 is a free chosen name + * Writer/Writer6.sxw is the document path. This will be assembled + * by TestDocumentPath from typeDetection.props. + * writer_StarOffice_XML_Writer: this is the default file type of + * this file + * + * The second example displays two document types for + * XInputStream (generic_Text). These + * two document types are listed by a colon ':' as separator. + * This is needed because XInputStream can detect a text file as + * generic_Text. + *

+ * + *

+ * preselectedFilter.csv

+ * In this file you can choose a special + * filter to detect the document. This makes sense ie. for csv-files: You can + * open csv files as Writer or as Calc. To check this case you have to specify + * in csv.files a fileAlias like ?csv_writer? and ?csv_calc? with + * the same fileURL and its specific defaultFileType. + * The returned file type by TypeDetection must be equal to the + * corresponding defaultFileType from csv.files + * + * Syntax: fileAlias;FilterName;FilterOptions;FilterData + * Example: Writer6_1;%SO6productname %SO6formatversion Textdocument; + * + * The example shows the following: + * Writer6_1 is the same as in csv.files + * %SO6productname %SO6formatversion Textdokument is the filter + * name which should be used. Here we have a special: %SO6productname + * %SO6formatversion will be replaced by the equals of + * typeDetection.props. The filter names depends on the Office + * name and version. So a future Office could be called ?StarSuite 8?. + * FilterOptions is not relevant for this filter. But ie. for csv + * filter this entry could be used to specify the separator of the csv file. + * FilterData if filter needs some FilterData arguments you can + * specify them here + * + *

+ *

+ * preselectedType.csv

+ * In this file you can preselect the type + * TypeDetection should use. + * The file type returned by TypeDetection must be equal to the + * preselected file type. + * Note: If you try to use invalid types you will get a failed test because + * TypeDetection tries to find out the type itself. + * + * Syntax: fileAlias;fileType + * Example: Writer6_1;writer_StarOffice_XML_Writer + * + * This example shows the following: + * Writer6_1 is the same as in csv.files + * writer_StarOffice_XML_Writer is the file type which was used as + * parameter in MediaDescriptor. This type must be returned from + * TypeDetection + * + *

+ *

+ * serviceName.csv

In this file you can preselect a service name + * to detect the file type. The file type returned by + * TypeDetection must be equal to the corresponding + * defaultFileType from csv.files + * + * Syntax: fileAlias;serviceName + * Example: Writer6_1;com.sun.star.text.FormatDetector + * + * This example shows the following: + * Writer6_1 is the same as in csv.files + * com.sun.star.text.FormatDetector is the service name which was + * used as parameter in MediaDescriptor. + * + * + *

+ * All these files will be copied by make file beside of + * typeDetection.class. + * @see com.sun.star.document.XTypeDetection + * @see com.sun.star.document.MediaDescriptor + */ +public class TypeDetection extends ComplexTestCase { + + /** + * @member m_xDetection the object to test + * @member helper instance of helper class + */ + + static XTypeDetection m_xDetection; + static Helper helper = null; + + /** + * A function to tell the framework, which test functions are available. + * @return All test methods. + */ + @Override + public String[] getTestMethodNames() { + return new String[]{"checkByURLonly", + "checkPreselectedType", + "checkPreselectedFilter", + "checkPreselectedDocService", + "checkStreamLoader", + "checkStreamLoader"}; + + } + + /** Create the environment for following tests. + * Use either a component loader from desktop or + * from frame + * @throws Exception Exception + */ + public void before() throws Exception { + + // create TypeDetection + XMultiServiceFactory xMSF = param.getMSF(); + assure("Could not get XMultiServiceFactory", xMSF != null); + + Object oInterface = xMSF.createInstance( + "com.sun.star.document.TypeDetection"); + + if (oInterface == null) { + failed("Service wasn't created") ; + } + + XInterface oObj = (XInterface) oInterface ; + log.println("ImplName: "+utils.getImplName(oObj)); + + m_xDetection = UnoRuntime.queryInterface(XTypeDetection.class, oInterface); + Iterator k = param.keySet().iterator(); + while (k.hasNext()){ + String kName = k.next(); + log.println(kName + ":" + param.get(kName).toString()); + } + // create instance of helper class + helper = new Helper(param, log); + + } + + /** + * close the environment + */ + public void after() { + } + + /** + * The MediaDescriptor was filled with the URL of a file. The + * type of the file is known and must be returned by + * MediaDescriptor + * + * Syntax of files.csv: + * fileAlias;fileURL;fileType + * + */ + public void checkByURLonly() { + try{ + log.println("### checkByURLonly() ###"); + ArrayList> CSVData = helper.getToDoList( + (String)param.get("csv.files")); + Iterator> allToDos = CSVData.iterator(); + + while (allToDos.hasNext()){ + ArrayList toDo = allToDos.next(); + + String fileAlias = toDo.get(0); + String fileURL = toDo.get(1); + String URLfileType = toDo.get(2); + String StreamfileType = toDo.get(3); + + fileURL = utils.getFullURL(helper.ensureEndingFileSep( + (String)param.get("TestDocumentPath")) + fileURL); + + log.println("actual '"+ fileAlias + + "' ['" + URLfileType + "']: '" + fileURL); + + checkMediaDescriptorURL(fileAlias, fileURL, URLfileType); + checkMediaDescriptorXInputStream(fileAlias, fileURL, StreamfileType); + } + + } catch (ClassCastException e){ + failed(e.toString(), ContinueWithTest.YES); + } + } + + /** To check the TypeDetection by URL the MediaDescriptor + * was filled at first with the URL only, at second with XInputStream + * only. The TypeDetection must return the expected value + * @param fileAlias the alias name of the test file + * @param fileURL the URL of the test file + * @param fileType the expected type of the test file + * @see com.sun.star.document.MediaDescriptor + */ + private void checkMediaDescriptorURL( + String fileAlias, String fileURL, String fileType){ + + PropertyValue[] MediaDescriptor = helper.createMediaDescriptor( + new String[] {"URL"}, + new Object[] {fileURL}); + log.println("check only by URL..."); + + String type = m_xDetection.queryTypeByDescriptor( + helper.createInOutPropertyValue(MediaDescriptor), true); + + boolean fileTypeOK = helper.checkFileType(type, fileType); + + assure("\nURL-test : " + fileAlias + ":\n\treturned type: '" + type + + "'\n\texpected type: '" + fileType + "'",fileTypeOK ,ContinueWithTest.YES); + } + + /** Fills a MediaDescriptor with a XInputStream of the test + * file given by URL. + * Then the MediaDescriptor was used as parameter for TypeDetection. + * The TypeDetection must return expected type + * @param fileAlias the alias name of the test file + * @param fileURL the URL of the test file + * @param fileType the expected type of the test file + * @see com.sun.star.document.MediaDescriptor + * @see com.sun.star.io.XInputStream + */ + private void checkMediaDescriptorXInputStream( + String fileAlias, String fileURL, String fileType){ + + XInputStream xStream = null; + + try{ + xStream = helper.getFileStream( fileURL ); + } catch (NotConnectedException e) { + failed("Could not get XInputStream from file :'" + fileURL + "'",ContinueWithTest.YES); + return; + } + + PropertyValue[] MediaDescriptor = helper.createMediaDescriptor( + new String[] {"InputStream"}, + new Object[] {xStream}); + log.println("check only by XInputStream..."); + + String type = m_xDetection.queryTypeByDescriptor( + helper.createInOutPropertyValue(MediaDescriptor), true); + + boolean fileTypeOK = helper.checkFileType(type, fileType); + + assure("\nXInputStream-test: " + fileAlias + ":\n\treturned type: '" + type + + "'\n\texpected type: '" + fileType + "'", fileTypeOK, ContinueWithTest.YES); + + } + + /** + * The MediaDescriptor was filled with the URL of a file. The + * type of the file is known and must be returned by + * MediaDescriptor + * + * Syntax of files.csv: + * fileAlias;fileURL;fileType + * + */ + public void checkPreselectedType() { + try{ + log.println("### checkPreselectedType() ###"); + + ArrayList> CSVData = helper.getToDoList( + (String)param.get("csv.preselectedType")); + Iterator> allToDos = CSVData.iterator(); + + while (allToDos.hasNext()){ + try{ + ArrayList toDo = allToDos.next(); + + String fileAlias = toDo.get(0); + String fileURL = helper.getURLforfileAlias(fileAlias); + String preselectFileType = toDo.get(1); + String expectedFileType = toDo.get(2); + + PropertyValue[] MediaDescriptor = helper.createMediaDescriptor( + new String[] {"URL", "MediaType"}, + new Object[] {fileURL, preselectFileType}); + log.println("check '" + fileAlias + "' with MediaType: '" + + preselectFileType + "'"); + + String type = m_xDetection.queryTypeByDescriptor( + helper.createInOutPropertyValue(MediaDescriptor), true); + + boolean fileTypeOK = helper.checkFileType(type, expectedFileType); + + assure("\n" + fileAlias + ":\n\treturned type: '" + type + + "'\n\texpected type: '" + expectedFileType + "'", + fileTypeOK, ContinueWithTest.YES); + + } catch (FileAliasNotFoundException e){ + failed(e.toString(),ContinueWithTest.YES); + } + + } + + } catch (ClassCastException e){ + failed(e.toString(), ContinueWithTest.YES); + } + } + + + /** + * Check loading from a stream. The source for the stream is the + * first fileAlias that matches "*.txt" in the file list + * of the given directory. + */ + public void checkPreselectedFilter() { + try{ + log.println("### checkPreselectedFilter() ###"); + + ArrayList> CSVData = helper.getToDoList( + (String)param.get("csv.preselectedFilter")); + Iterator> allToDos = CSVData.iterator(); + + while (allToDos.hasNext()){ + try{ + ArrayList toDo = allToDos.next(); + + String fileAlias = toDo.get(0); + String fileURL = helper.getURLforfileAlias(fileAlias); + String filterName = toDo.get(1); + String filterOptions = toDo.get(2); + String filterData = toDo.get(3); + String expectedType = toDo.get(4); + + PropertyValue[] MediaDescriptor = helper.createMediaDescriptor( + new String[] {"URL","FilterName", + "FilterOptions","FilterData"}, + new Object[] {fileURL, filterName, + filterOptions, filterData}); + + log.println("check '" + fileAlias + "' with filter: '" + + filterName + "'"); + + String type = m_xDetection.queryTypeByDescriptor( + helper.createInOutPropertyValue(MediaDescriptor), true); + + boolean fileTypeOK = helper.checkFileType(type, expectedType); + + assure("\n" + fileAlias + ":\n\treturned type: '" + type + + "'\n\texpected type: '" + expectedType + "'", + fileTypeOK,ContinueWithTest.YES); + + } catch (FileAliasNotFoundException e){ + failed(e.toString(),ContinueWithTest.YES); + } + + } + + } catch (ClassCastException e){ + failed(e.toString(), ContinueWithTest.YES); + } + } + + /** + * Check URL encoding. The first fileAlias that matches "*.sxw" + * is used as source for several encodings. + */ + public void checkPreselectedDocService() { + try{ + log.println("### checkPreselectedDocService() ###"); + + ArrayList> CSVData = helper.getToDoList((String)param.get("csv.serviceName")); + Iterator> allToDos = CSVData.iterator(); + + while (allToDos.hasNext()){ + try{ + ArrayList toDo = allToDos.next(); + + String fileAlias = toDo.get(0); + String fileURL = helper.getURLforfileAlias(fileAlias); + String serviceName = toDo.get(1); + String fileType = helper.getTypeforfileAlias(fileAlias); + + PropertyValue[] MediaDescriptor = helper.createMediaDescriptor( + new String[] {"URL", "DocumentService"}, + new Object[] {fileURL, serviceName}); + log.println("check " + fileAlias); + + String type = m_xDetection.queryTypeByDescriptor( + helper.createInOutPropertyValue(MediaDescriptor), true); + + boolean fileTypeOK = helper.checkFileType(type, fileType); + + assure("\n" + fileAlias + ":\n\treturned type: '" + type + + "'\t\nexpected type: '" + fileType + "'", + fileTypeOK, ContinueWithTest.YES); + + } catch (FileAliasNotFoundException e){ + failed(e.toString(),ContinueWithTest.YES); + } + + } + + } catch (ClassCastException e){ + failed(e.toString(), ContinueWithTest.YES); + } + } + + public void checkStreamLoader(){ + try{ + + /* + * As files, use the typeDetection.props and one of the csv files. + * Those can, via dmake, simply set rights on others. + * + */ + log.println("### checkStreamLoader() ###"); + String[] urls = new String[] { + helper.getClassURLString("TypeDetection.props"), + helper.getClassURLString("files.csv") }; + + for (int j=0; jcom.sun.star.document.FilterFactory and + * com.sun.star.document.TypeDetection. + * + * Each of these services represent a container of PropertyValue[]. + * The PropertyValue[] contains among others the properties called + * Finalized and Mandatory. If the property + * Finalized is set to true, a filter can be removed + * but will not be able to be changed. + * If the property Mandatory is set to true, the filter + * can not be removed. + * + * Every filter, which is registered to the office, will be tested. For every filter-test + * a new instance of the mentioned services will be created. + + * During the test the property UIName + * will be changed and the service will be flushed. The test checks for expected exceptions: + * If the property Finalized equals + * true the tests check if an Exception must be thrown. + * The next step of the test is the removal of the filter was removed, then the service + * will be flushed. The test checks for expected exceptions: If the property + * Mandatory equals true, an Exception must + * be thrown. + * This test results false state if there is no filter available with: + * Finalized=true + * Finalized=false + * Mandatory=true + * Mandatory=false + */ +public class FinalizedMandatoryTest +{ + + XMultiServiceFactory xMSF; + + /** Create the environment for following tests. + * Use either a component loader from desktop or + * from frame + * @throws Exception Exception + */ + @Before public void before() throws Exception + { + + // create TypeDetection + xMSF = getMSF(); + assertNotNull("Could not get XMultiServiceFactory", xMSF); + + } + + /** + * Creates an instance for the given serviceName + * @param serviceName the name of the service which should be created + * @throws Exception was thrown if creation fails + * @return XInterface of service + */ + private XInterface getTestObject(String serviceName) throws Exception + { + + Object oInterface = xMSF.createInstance(serviceName); + + assertNotNull("Service wasn't created", oInterface); + return (XInterface) oInterface; + } + + /** + * call the function checkReadonlySupport to test com.sun.star.document.FilterFactory + * @see com.sun.star.document.FilterFactory + */ + @Test public void checkReadonlySupportFilterFactory() throws Exception + { + checkReadonlySupport("com.sun.star.document.FilterFactory"); + } + + /* + * call the function checkReadonlySupport to test com.sun.star.document.TypeDetection + * @see com.sun.star.document.TypeDetection + */ + @Test public void checkReadonlySupportTypeDetection() throws Exception + { + checkReadonlySupport("com.sun.star.document.TypeDetection"); + } + + /* + * test the given service serviceName. + * For every filter a new instance was created and the tests started. + * @param serviceName the name of the service to test + */ + private void checkReadonlySupport(String serviceName) throws Exception + { + System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); + System.out.println("testing service '" + serviceName + "'"); + + XInterface oObj = null; + oObj = getTestObject(serviceName); + System.out.println("ImplName: " + util.utils.getImplName(oObj)); + + boolean mandatoryTrue = false; + boolean mandatoryFalse = false; + boolean finalizedTrue = false; + boolean finalizedFalse = false; + + + XNameAccess xNA = UnoRuntime.queryInterface(XNameAccess.class, oObj); + String[] filterNames = xNA.getElementNames(); + + // XNameContainer; XNameReplace + String filterName = filterNames[0]; + Object[] instance = null; + + for (int i = 0; i < filterNames.length; i++) + { + System.out.println("------------------------------------------------"); + filterName = filterNames[i]; + System.out.println(filterName); + + // testobject must new created for every test. + // We change in a loop the container and try to flush this changes. + // If we get an expected exception this container is corrupt. It's + // similar to a document which could not be saved because of invalid + // content. While you don't remove the invalid content you will never + // be able to save the document. Same here. + oObj = getTestObject(serviceName); + + xNA = UnoRuntime.queryInterface(XNameAccess.class, oObj); + XNameContainer xNC = UnoRuntime.queryInterface(XNameContainer.class, oObj); + XNameReplace xNR = UnoRuntime.queryInterface(XNameReplace.class, oObj); + XFlushable xFlush = UnoRuntime.queryInterface(XFlushable.class, oObj); + + instance = (Object[]) xNA.getByName(filterName); + PropertyValue[] props = (PropertyValue[]) instance; + + printPropertyValues(props); + + boolean isMandatory = ((Boolean) getPropertyValueValue(props, "Mandatory")).booleanValue(); + boolean isFinalized = ((Boolean) getPropertyValueValue(props, "Finalized")).booleanValue(); + + // memory if every state is available + mandatoryTrue |= isMandatory; + mandatoryFalse |= !isMandatory; + + finalizedTrue |= isFinalized; + finalizedFalse |= !isFinalized; + + //change the filter + setPropertyValueValue((PropertyValue[]) instance, "UIName", "dummy"); + + // 1a.) try to change the filter in the container + xNR.replaceByName(filterName, instance); + + // 1b.) try to write the changed filter to the configuration. + // This must result in an exception if the filter is finalized. + boolean flushError = false; + try + { + xFlush.flush(); + } + catch (WrappedTargetRuntimeException e) + { + flushError = true; + assertTrue("Unexpected exception while flushing changed filter '" + filterName + "'", isFinalized); + } + assertTrue("Expected exception was not thrown while flushing changed filter '" + filterName + "' Finalized:" + isFinalized, + !(flushError ^ isFinalized)); + + + + // 2a.) try to remove the filter from the container + xNC.removeByName(filterName); + // 1b.) try to write the changed filter to the configuration. + // This must result in an exception if the filter is mandatory + flushError = false; + try + { + xFlush.flush(); + } + catch (WrappedTargetRuntimeException e) + { + flushError = true; + assertTrue("Unexpected exception while flushing removed filter '" + filterName + "'", isMandatory); + } + assertTrue("Expected exception was not thrown while flushing removed filter '" + filterName + "' Mandatory:" + isMandatory, + !(flushError ^ isMandatory)); + } + String preMsg = "Could not find filter with state "; + String postMsg = " Please check if such filter is installed!"; + assertTrue(preMsg + "'Mandatory=true'" + postMsg, mandatoryTrue); + assertTrue(preMsg + "'Mandatory=false'" + postMsg, mandatoryFalse); + assertTrue(preMsg + "'Finalized=true'" + postMsg, finalizedTrue); + assertTrue(preMsg + "'Finalized=false'" + postMsg, finalizedFalse); + } + + /** + * print all properties with its values to logger. For debug purposes. + * @see stats.SimpleLogWriter + * @see com.sun.star.beans.PropertyValue + * @param props Sequence of PropertyValue + */ + protected void printPropertyValues(PropertyValue[] props) + { + int i = 0; + while (i < props.length) + { + System.out.println(props[i].Name + ":" + props[i].Value.toString()); + i++; + } + if (i < props.length) + { + System.out.println(props[i].Name + ":" + props[i].Value.toString()); + } + } + + /** + * returns the value of the specified (pName) property from a sequence of PropertyValue + * @param props a sequence of PropertyValue + * @param pName the name of the property the value should be returned + * @return the value of the property + */ + protected Object getPropertyValueValue(PropertyValue[] props, String pName) + { + int i = 0; + while (i < props.length && !props[i].Name.equals(pName)) + { + i++; + } + return i < props.length ? props[i].Value : null; + } + + /** + * set a value of the specified (pName) property inside a sequence of PropertyValue + * @param props sequence of PropertyValue + * @param pName name of the property which should be changed + * @param pValue the value the property should be assigned + */ + protected void setPropertyValueValue(PropertyValue[] props, String pName, Object pValue) + { + int i = 0; + while (i < props.length && !props[i].Name.equals(pName)) + { + i++; + } + props[i].Value = pValue; + } + + private XMultiServiceFactory getMSF() + { + return UnoRuntime.queryInterface(XMultiServiceFactory.class, connection.getComponentContext().getServiceManager()); + } + + // setup and close connections + @BeforeClass + public static void setUpConnection() throws Exception + { + System.out.println("setUpConnection()"); + connection.setUp(); + } + + @AfterClass + public static void tearDownConnection() + throws InterruptedException, com.sun.star.uno.Exception + { + System.out.println("tearDownConnection()"); + connection.tearDown(); + } + private static final OfficeConnection connection = new OfficeConnection(); +} diff --git a/filter/qa/complex/filter/misc/TypeDetection6FileFormat.java b/filter/qa/complex/filter/misc/TypeDetection6FileFormat.java new file mode 100644 index 000000000..009fd52cf --- /dev/null +++ b/filter/qa/complex/filter/misc/TypeDetection6FileFormat.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 complex.filter.misc; + +import com.sun.star.container.XNameAccess; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XInterface; + +import util.utils; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.openoffice.test.OfficeConnection; +import static org.junit.Assert.*; + + +public class TypeDetection6FileFormat +{ + + XMultiServiceFactory xMSF; + + /** Create the environment for following tests. + * Use either a component loader from desktop or + * from frame + * @throws Exception Exception + */ + @Before public void before() throws Exception + { + xMSF = getMSF(); + assertNotNull("Could not get XMultiServiceFactory", xMSF); + } + + /** + * call the function checkFileFormatSupport to test com.sun.star.document.FilterFactory + * @see com.sun.star.document.FilterFactory + */ + @Test public void checkFilterFactory() throws Exception + { + checkFileFormatSupport("com.sun.star.document.FilterFactory"); + } + + /** + * call the function checkFileFormatSupport to test com.sun.star.document.TypeDetection + * @see com.sun.star.document.TypeDetection + */ + @Test public void checkTypeDetection() throws Exception + { + checkFileFormatSupport("com.sun.star.document.TypeDetection"); + } + + /** + * test the given service serviceName. + * The serve was created and the filter 'TypeDetection6FileFormat' was searched + * @param serviceName the name of the service to test + */ + private void checkFileFormatSupport(String serviceName) throws Exception + { + System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"); + System.out.println("testing service '" + serviceName + "'"); + + XInterface oObj = null; + oObj = getTestObject(serviceName); + System.out.println("ImplName: " + utils.getImplName(oObj)); + XNameAccess xNA = UnoRuntime.queryInterface(XNameAccess.class, oObj); + String msg = "Could not find filter 'TypeDetection6FileFormat'!"; + msg += "\nMaybe 'TypeDetection6FileFormat.xcu' is not registered."; + assertTrue(msg, xNA.hasByName("TypeDetection6FileFormat")); + } + + /** + * Creates an instance for the given serviceName + * @param serviceName the name of the service which should be created + * @throws Exception was thrown if creation fails + * @return XInterface of service + */ + public XInterface getTestObject(String serviceName) throws Exception + { + + Object oInterface = xMSF.createInstance(serviceName); + + if (oInterface == null) + { + fail("Service wasn't created"); + throw new Exception("could not create service '" + serviceName + "'"); + } + return (XInterface) oInterface; + } + + private XMultiServiceFactory getMSF() + { + return UnoRuntime.queryInterface(XMultiServiceFactory.class, connection.getComponentContext().getServiceManager()); + } + + // setup and close connections + @BeforeClass public static void setUpConnection() throws Exception { + System.out.println("setUpConnection()"); + connection.setUp(); + } + + @AfterClass public static void tearDownConnection() + throws InterruptedException, com.sun.star.uno.Exception + { + System.out.println("tearDownConnection()"); + connection.tearDown(); + } + + private static final OfficeConnection connection = new OfficeConnection(); + +} diff --git a/filter/qa/complex/filter/misc/TypeDetection6FileFormat.xcu b/filter/qa/complex/filter/misc/TypeDetection6FileFormat.xcu new file mode 100644 index 000000000..2206e6942 --- /dev/null +++ b/filter/qa/complex/filter/misc/TypeDetection6FileFormat.xcu @@ -0,0 +1,42 @@ + + + + + + + TypeDetection 6 FileFormat + TypeDetection 6 FileFormat + + + 1,,,,,, + + + + + + + FilterFactory 6 FileFormat + FilterFactory 6 FileFormat + + + 0,TypeDetection6FileFormat,,,,, + + + + -- cgit v1.2.3