xref: /trunk/main/filter/qa/complex/filter/detection/typeDetection/Helper.java (revision 6fd2419af095b9e12baf06e33db2129edf4d719b)
1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 
24 package complex.filter.detection.typeDetection;
25 
26 import com.sun.star.beans.PropertyValue;
27 import com.sun.star.io.NotConnectedException;
28 import com.sun.star.io.XInputStream;
29 import com.sun.star.lang.XMultiServiceFactory;
30 
31 import helper.StreamSimulator;
32 import java.io.*;
33 import java.net.URL;
34 import java.net.URLConnection;
35 import java.util.ArrayList;
36 import java.util.Enumeration;
37 import java.util.Hashtable;
38 import java.util.StringTokenizer;
39 import java.util.Properties;
40 import lib.TestParameters;
41 import share.LogWriter;
42 import util.utils;
43 
44 import org.openoffice.test.Argument;
45 
46 /** Helper class for "TypeDetection"
47  * This class do file hanlding.
48  */
49 public class Helper {
50 
51     /** The runner log writer
52      * @member m_sTestDocPath   directory for searching files to load
53      * @member m_vFiles         list of all files described in "files.csv"
54      * @member m_hFileURLs      contains the position of a file name in the m_vFiles ArrayList
55      * @member m_hFileTypes     contains the position of a file type in the m_vFiles ArrayList
56      */
57 
58     String m_sTestDocPath = null;
59 
60     ArrayList<ArrayList<String>> m_vFiles = null;
61 
62     Hashtable m_hFileURLs = new Hashtable();
63 
64     Hashtable m_hFileTypes = new Hashtable();
65 
66     XMultiServiceFactory m_xMSF;
67 
68     /**
69      * construct a new instance of this class
70      * It creates the "todo" list and position lists for <code>URL</code> and
71      * and <code>Type</code> inside the "todo" list
72      *
73      * @param   param the test parameters
74      *
75      * @param   log the log writer
76      */
77 
Helper(XMultiServiceFactory xMSF)78     public Helper(XMultiServiceFactory xMSF) throws IOException {
79 
80         m_xMSF = xMSF;
81 
82         // get all files from the given directory
83         m_sTestDocPath = Argument.get("tdoc");
84 
85         // get all files from "files.csv"
86         m_vFiles = getToDoList(Argument.get("files.csv"));
87 
88         createFilesList();
89     }
90 
91 
92      /** Reads a comma separated file (CSV). Every line of the file is
93       * represented by an <code>ArrayList</code> entry. Every data entry of a row is
94       * also stored in a <code>ArrayList</code>. So the returned value is a
95       * <code>ArrayList<ArrayList<>></code> where the first dimension represents a row
96       * and the second dimension includes the data values.
97       * @param csvFileName the name of the csv file
98       * @return ArrayList filled with ArrayList filled with data of a row
99       */
getToDoList(String csvFileName)100      public ArrayList<ArrayList<String>> getToDoList(String csvFileName) throws IOException {
101 
102          ArrayList<ArrayList<String>> vAll = new ArrayList<>();
103          ArrayList<String> vFields = new ArrayList<>();
104 
105          // get content of file
106          ArrayList<String> content = getCSVFileContent(csvFileName);
107 
108          // remove superfluous content like "#" started lines
109          content = removeSuperfluousContent(content);
110 
111          // replace all place holders in file
112          content = replacePlaceHolder(content);
113 
114          // the first line contains field names of the columns
115          // split line by ";"
116          StringTokenizer fields = new StringTokenizer(
117              content.get(0), ";");
118          int fieldCount = 0;
119          while (fields.hasMoreElements()){
120              vFields.add((String)fields.nextElement());
121              fieldCount++;
122          }
123 
124          // fill vData with data of CSV-row
125          for (int row = 1; row < content.size(); row++){
126              ArrayList<String> vData = new ArrayList<>();
127              String[] tokens = content.get(row).split(";");
128              for (String token : tokens) {
129                  vData.add(token);
130              }
131              for (int i = tokens.length; i < fieldCount; i++)
132                   vData.add("");
133              vAll.add(vData);
134          }
135 
136          return vAll;
137      }
138 
139      /** The csv files "files", "preselectedFilter", "preselectedType" and
140       * "serviceName" are read with this class. This function seeks for
141       * the csv files and read them.
142       * @param csvFileName the name of the csv file
143       * @return an ArrayList<String> containing the content of the file.
144       */
getCSVFileContent(String csvFileName)145     private static ArrayList<String> getCSVFileContent(String csvFileName) throws IOException {
146         ArrayList<String> content = new ArrayList<>();
147         if ( Boolean.parseBoolean(Argument.get("DEBUG_IS_ACTIVE")) ) {
148             System.out.println("Looking for "+csvFileName);
149         }
150         String line;
151         try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(csvFileName), "UTF-8"))) {
152             while ( ( line = reader.readLine() ) != null ) {
153                 content.add( line );
154             }
155             return content;
156         }
157     }
158 
159     /** returns a XInputStream of given file
160      * @param filePath the path to the file which should be loaded
161      * @return the XInputStream, <null/> if the
162      * file cannot be read
163      * @throws NotConnectedException was thrown if it was not possible to open <CODE>filePath</CODE>
164      */
getFileStream( String filePath )165     public XInputStream getFileStream( String filePath )
166                                                 throws NotConnectedException {
167         return new StreamSimulator(filePath, true, m_xMSF);
168     }
169 
170     /** replaces place holder in preselectedFilter.
171      * Because of filter names depend on StarOffice version like
172      * "StarOffice 6.0 Textdokument" or ""StarSuite 7 Textdokument"
173      * The filter names must be changed. The place holder will be replaced
174      * by an equivalent in "typeDetection.props"
175      * @param content the content of a csv file
176      * @return changed file content
177      */
replacePlaceHolder(ArrayList<String> content)178     private static ArrayList<String> replacePlaceHolder(ArrayList<String> content) throws IOException {
179 
180         ArrayList<String> vReturn = new ArrayList<>();
181 
182         ArrayList<String> placeHolders = new ArrayList<>();
183         Properties properties = new Properties();
184         try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(Argument.get("properties")), "UTF-8"))) {
185             properties.load(reader);
186         }
187         Enumeration keys = properties.keys();
188         String placeHolder = properties.getProperty("placeHolder");
189 
190         // get all placeholders from typeDetection.csv
191         while (keys.hasMoreElements()){
192             String holderKey = (String) keys.nextElement();
193             if (holderKey.startsWith(placeHolder)){
194                 placeHolders.add(holderKey);
195             }
196         }
197 
198         // replace all occurrences of placeholders in 'CSVData'
199         for( String line : content ) {
200 
201             String newLine = line;
202 
203             for( String holder : placeHolders ) {
204 
205                 int startPos = line.indexOf(holder);
206 
207                 if (startPos > -1){
208                     try{
209                         String holderValue = properties.getProperty(holder);
210 
211                         newLine = newLine.substring(0,startPos) + holderValue +
212                                 newLine.substring(startPos + holder.length());
213 
214                     } catch (java.lang.IndexOutOfBoundsException e){
215                         System.out.println("ERROR: problems while creating placeholder" +
216                                     " replaced list: "+ e);
217                     }
218                 }
219            }
220            vReturn.add(newLine);
221         }
222         return vReturn;
223     }
224 
225     /** Removes lines of an ascii file content which starts with "#"
226      * or are empty
227      * @param content content of a csv file
228      * @return a stripped ArrayList<String>
229      */
removeSuperfluousContent(ArrayList<String> content)230     private static ArrayList<String> removeSuperfluousContent(ArrayList<String> content){
231         ArrayList<String> newContent = new ArrayList<>();
232         for( String line : content ) {
233             if (( ! line.startsWith( "#" ))&& ( line.length() != 0 )) {
234                 newContent.add( line );
235             }
236         }
237         return newContent;
238     }
239 
240     /** returns a <code>MediaDescriptor</code> filled with given properties and
241      * values.
242      * @param propNames String Array of property names
243      * @param values Object Array of property values
244      * @return <code>PropertyValue[]<code>
245      * @see com.sun.star.beans.PropertyValue
246      * @see com.sun.star.document.MediaDescriptor
247      */
createMediaDescriptor(String[] propNames, Object[] values)248     public static PropertyValue[] createMediaDescriptor(String[] propNames, Object[] values) {
249         PropertyValue[] props = new PropertyValue[propNames.length] ;
250 
251         for (int i = 0; i < props.length; i++) {
252             props[i] = new PropertyValue() ;
253             props[i].Name = propNames[i] ;
254             if (values != null && i < values.length) {
255                 props[i].Value = values[i] ;
256             }
257         }
258 
259         return props ;
260     }
261 
262     /** Appends system file separator if needed
263      * @param s the system path
264      * @return system path with ending system file separator
265      */
ensureEndingFileSep(String s)266     public static String ensureEndingFileSep(String s){
267         if(s != null && !s.equals("") && !s.endsWith(File.separator)){
268             s = s.trim() + File.separator;
269         }else if(s == null)
270             s = "";
271         return s;
272     }
273 
274     /** Returns the file URL for the given file name assembled by
275      * "TestDocumentPath" of typeDetection.props and "fileURL" of files.csv
276      * @param fileAlias the alias name of the file
277      * @return file URL
278      * @throws FileAliasNotFoundException was thrown if alias does not exist
279      */
getURLforfileAlias(String fileAlias)280     public String getURLforfileAlias(String fileAlias)
281                                         throws FileAliasNotFoundException{
282         try{
283             String fileURL = (String) m_hFileURLs.get(fileAlias).toString();
284             return utils.getFullURL(ensureEndingFileSep(m_sTestDocPath) + fileURL);
285         } catch (java.lang.NullPointerException e){
286             throw new FileAliasNotFoundException(fileAlias);
287         }
288     }
289 
290     /** Returns the file type for the given file name containing in files.csv
291      * @param fileAlias the alias name of the file
292      * @return file type
293      * @throws FileAliasNotFoundException was thrown if not alias was thrown
294      */
getTypeforfileAlias(String fileAlias)295     public String getTypeforfileAlias(String fileAlias)
296                                         throws FileAliasNotFoundException{
297         try{
298             return (String) m_hFileTypes.get(fileAlias).toString();
299         } catch (java.lang.NullPointerException e){
300             throw new FileAliasNotFoundException(fileAlias);
301        }
302     }
303 
304     /**
305      *  Fills the Hashtable m_hFileURLs with all file names and their URL
306      *  and the Hashtable m_hFilesTypes with all file names and their file
307      *  type name. This informations are extracted from "files.csv"
308      *  This is for faster access to get fileURL and fileType of fileAlias
309      */
createFilesList()310     private void createFilesList(){
311         for (int i = 0; i < m_vFiles.size();i++){
312             ArrayList<String> toDo = m_vFiles.get(i);
313             m_hFileURLs.put(toDo.get(0), toDo.get(1));
314             m_hFileTypes.put(toDo.get(0), toDo.get(2));
315         }
316     }
317 
318 
319     /**  Validate the returned file type for the file alias with the
320      *  possible file types
321      * @param currentFileType the returned file type
322      * @param fileTypes all possible file types
323      * @return true if valid
324      */
checkFileType(String currentFileType, String fileTypes)325     public static boolean checkFileType(String currentFileType, String fileTypes){
326 
327         StringTokenizer data = new StringTokenizer(fileTypes,":", true);
328 
329         boolean found = false;
330         while (data.hasMoreElements()) {
331 
332             String actualFileType = data.nextElement().toString();
333 
334             found = found || currentFileType.equals(actualFileType);
335         }
336         return found;
337     }
338 
339     /** creates an input/output parameter of <code>PropertyValue[]<code>.
340      * @return PropertyValue[][]
341      * @param PropVal a PropertyValue
342      */
createInOutPropertyValue(PropertyValue[] PropVal)343     public static PropertyValue[][] createInOutPropertyValue(PropertyValue[] PropVal){
344         PropertyValue[][] dummy = new PropertyValue[1][];
345         dummy[0] = PropVal;
346         return dummy;
347     }
348 }
349 
350 /** This exception should be thrown if a method seeks for an invalid alias name */
351 class FileAliasNotFoundException extends java.lang.Exception{
352     /** throws error message with wrong alias name
353      * @param fileAlias the alias name
354      */
FileAliasNotFoundException(String fileAlias)355     public FileAliasNotFoundException(String fileAlias){
356         super("Could not get '"+fileAlias +"'");
357     }
358 }
359