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 30 import helper.StreamSimulator; 31 import java.io.*; 32 import java.net.URL; 33 import java.net.URLConnection; 34 import java.util.Enumeration; 35 import java.util.Hashtable; 36 import java.util.StringTokenizer; 37 import java.util.Vector; 38 import lib.TestParameters; 39 import share.LogWriter; 40 import util.utils; 41 42 43 44 /** Helper class for "TypeDetection" 45 * This class do file hanlding. 46 */ 47 public class Helper { 48 49 /** The runner log writer 50 * @member m_log for log purposes 51 * @member m_sTestDocPath directory for seraching files to load 52 * @member m_vFiles list of all files describet in "files.csv" 53 * @member m_hFileURLs contains the postition of a file name in the m_vFiles Vector 54 * @member m_hFileTypes contains the postition of a file type in the m_vFiles Vector 55 * @member m_param the test parameters 56 */ 57 58 LogWriter m_log = null; 59 60 String m_sTestDocPath = null; 61 62 Vector m_vFiles = null; 63 64 Hashtable m_hFileURLs = new Hashtable(); 65 66 Hashtable m_hFileTypes = new Hashtable(); 67 68 TestParameters m_param = null; 69 70 /** 71 * construct a new instance of this class 72 * It creates the "todo" list and position lists for <code>URL</code> and 73 * and <code>Type</code> inside the "todo" list 74 * 75 * @param param the test parameters 76 * 77 * @param log the log writer 78 */ 79 Helper(TestParameters param, LogWriter log)80 public Helper(TestParameters param, LogWriter log) { 81 82 m_param = param; 83 m_log = log; 84 85 86 // get all files from the given directory 87 m_sTestDocPath = (String)param.get("TestDocumentPath"); 88 89 // get all files from "files.csv" 90 m_vFiles = getToDoList((String)m_param.get("csv.files")); 91 92 createFilesList(); 93 } 94 95 96 /** Reads a comma separated file (CSV). Every line of the file is 97 * repesented by an <code>Vector</code> entry. Every data entry of a row is 98 * also stored in a <code>Vector</code>. So the returned value is a 99 * <code>Vector[][]</code> where the first dimension represents a row 100 * and the second dimenesion inclueds the data values. 101 * @param csvFileName the name of the csv file 102 * @return Vector filled with Vector filled with data of a row 103 */ getToDoList(String csvFileName)104 public Vector getToDoList(String csvFileName){ 105 106 try { 107 108 Vector vAll = new Vector(); 109 Vector vFields = new Vector(); 110 111 // get content of file 112 Vector content = getCSVFileContent(csvFileName); 113 114 // remove superfluous content like "#" started lines 115 content = removeSuperfluousContent(content); 116 117 // replace all place holders in file 118 content = replacePlaceHolder(content); 119 120 // create Enumeration 121 Enumeration contentEnum = content.elements(); 122 123 // the first line contains field names of the columns 124 // split line by ";" 125 StringTokenizer fields = new StringTokenizer( 126 contentEnum.nextElement().toString(),";"); 127 int fieldCount = 0; 128 while (fields.hasMoreElements()){ 129 vFields.add(fields.nextElement()); 130 fieldCount++; 131 } 132 133 // fill vData with data of CSV-row 134 while (contentEnum.hasMoreElements()){ 135 Vector vData = new Vector(); 136 137 StringTokenizer data = new StringTokenizer( 138 contentEnum.nextElement().toString(),";", true); 139 140 // example: data = "firstData;secondData;;forthData" 141 // => three tokens => missing one data because the imagine 142 // "thirdData" was not recieved by data.nextToken() 143 // Therefore here comes a special handling for empty datas 144 boolean nextIsData = false; 145 int dataCount = 0; 146 while (data.hasMoreTokens()) { 147 Object myToken = data.nextToken(); 148 // if the "thirdData" will be recieved, myToken=";" but 149 // vData must add an empty String 150 if (myToken.equals(";")){ 151 if (nextIsData ) { 152 vData.add(""); 153 dataCount++; 154 nextIsData = false; 155 } 156 nextIsData = true; 157 } else { 158 vData.add(myToken.toString()); 159 dataCount++; 160 nextIsData = false; 161 } 162 } 163 for (int i=dataCount; i < fieldCount; i++) vData.add(""); 164 vAll.add(vData); 165 } 166 167 168 return vAll; 169 170 } catch(ClassCastException e) { 171 e.printStackTrace(); 172 } 173 return null; 174 } 175 176 /** The csv files "files", "preselectedFilter", "preselectedType" and 177 * "serviceName" are delivered beside this class. This function seeks for 178 * the csv files and read them. 179 * @param csvFileName the name of the csv file 180 * @return a Vector containing the content of the file. <null/> if the file 181 * cannot be read 182 */ 183 getCSVFileContent(String csvFileName)184 public Vector getCSVFileContent(String csvFileName) { 185 try { 186 Vector content = new Vector(); 187 BufferedReader br; 188 String line; 189 if ( m_param.DebugIsActive ) { 190 System.out.println("Looking for "+csvFileName); 191 } 192 193 URL url = getClassURL(csvFileName); 194 195 if (url != null) { 196 URLConnection connection = url.openConnection(); 197 InputStream in = connection.getInputStream(); 198 199 br = new BufferedReader(new InputStreamReader(in)); 200 try { 201 while( ( line = br.readLine() ) != null ) { 202 content.addElement( line ); 203 } 204 } catch (IOException e) { 205 br.close(); 206 return null; 207 } 208 br.close(); 209 return content; 210 } 211 212 }catch (IOException e) { 213 }catch(java.lang.NullPointerException e) { 214 return null; 215 } 216 return null; 217 } 218 219 /** returns a XInputStream of given file 220 * @param filePath the path to the file which shoud be loaded 221 * @return the XInputStream, <null/> if the 222 * file cannot be read 223 * @throws NotConnectedException was thrown if it was not possible to open <CODE>filePath</CODE> 224 */ getFileStream( String filePath )225 public XInputStream getFileStream( String filePath ) 226 throws NotConnectedException { 227 return new StreamSimulator(filePath, true, m_param); 228 } 229 230 /** replaces place holder in preselectedFilter. 231 * Because of filter names depend on StarOffice version like 232 * "StarOffice 6.0 Textdokument" or ""StarSuite 7 Textdokument" 233 * The filter names must be changed. The place holder will be replaced 234 * by an equivalent in "typeDetection.props" 235 * @param content the content of a csv file 236 * @return changed file content 237 */ replacePlaceHolder(Vector content)238 private Vector replacePlaceHolder(Vector content){ 239 240 Vector vReturn = new Vector(); 241 242 Vector placeHolders = new Vector(); 243 Enumeration m_params = m_param.keys(); 244 String placeHolder = (String)m_param.get("placeHolder"); 245 246 // get all place holdes from typeDetection.csv 247 while (m_params.hasMoreElements()){ 248 String holderKey = (String) m_params.nextElement(); 249 if (holderKey.startsWith(placeHolder)){ 250 placeHolders.add(holderKey); 251 } 252 } 253 254 // replace all occurrences of place holders in 'CSVData' 255 Enumeration cont = content.elements(); 256 257 while( cont.hasMoreElements() ) { 258 259 String line = (String) cont.nextElement(); 260 String newLine = line; 261 Enumeration holders = placeHolders.elements(); 262 263 while( holders.hasMoreElements() ) { 264 265 String holder = (String) holders.nextElement(); 266 int startPos = line.indexOf(holder); 267 268 if (startPos > -1){ 269 try{ 270 String holderValue = (String) m_param.get(holder); 271 272 newLine = newLine.substring(0,startPos) + holderValue + 273 newLine.substring(startPos + holder.length()); 274 275 } catch (java.lang.IndexOutOfBoundsException e){ 276 m_log.println("ERROR: problems while creating placeholder" + 277 " replaced list: "+ e); 278 } 279 } 280 } 281 vReturn.add(newLine); 282 } 283 return vReturn; 284 } 285 286 /** Removes lines of an ascii file content which starts with "#" 287 * or are empty 288 * @param content content of a csv fi�e 289 * @return a stripped Vector 290 */ removeSuperfluousContent(Vector content)291 public Vector removeSuperfluousContent(Vector content){ 292 try{ 293 Vector newContent = new Vector(); 294 Enumeration cont = content.elements(); 295 while( cont.hasMoreElements() ) { 296 String line = (String) cont.nextElement(); 297 if (( ! line.startsWith( "#" ))&& ( line.length() != 0 )) { 298 newContent.addElement( line ); 299 } 300 } 301 return newContent; 302 } catch (ClassCastException e){ 303 return null; 304 } 305 } 306 307 /** returns a <code>MediaDescripto</code> filled with given properties and 308 * values. 309 * @param propNames String Array of propertie names 310 * @param values Objecr Array of propertie values 311 * @return <code>PropertyValue[]<code> 312 * @see com.sun.star.beans.PropertyValue 313 * @see com.sun.star.document.MediaDescriptor 314 */ createMediaDescriptor(String[] propNames, Object[] values)315 public PropertyValue[] createMediaDescriptor(String[] propNames, Object[] values) { 316 PropertyValue[] props = new PropertyValue[propNames.length] ; 317 318 for (int i = 0; i < props.length; i++) { 319 props[i] = new PropertyValue() ; 320 props[i].Name = propNames[i] ; 321 if (values != null && i < values.length) { 322 props[i].Value = values[i] ; 323 } 324 } 325 326 return props ; 327 } 328 329 /** Appends system file separator if needed 330 * @param s the system path 331 * @return system path with ending system file separator 332 */ ensureEndingFileSep(String s)333 public String ensureEndingFileSep(String s){ 334 if(s != null && !s.equals("") && !s.endsWith(File.separator)){ 335 s = s.trim() + File.separator; 336 }else if(s == null) 337 s = ""; 338 return s; 339 } 340 341 /** Returns the file URL for the given file name assembled by 342 * "TestDocumentPath" of typeDetection.props and "fileURL" of files.csv 343 * @param fileAlias the alias name of the file 344 * @return file URL 345 * @throws FileAliasNotFoundException was thrown if alias does not exist 346 */ getURLforfileAlias(String fileAlias)347 public String getURLforfileAlias(String fileAlias) 348 throws FileAliasNotFoundException{ 349 try{ 350 String fileURL = (String) m_hFileURLs.get(fileAlias).toString(); 351 return utils.getFullURL(ensureEndingFileSep(m_sTestDocPath) + fileURL); 352 } catch (java.lang.NullPointerException e){ 353 throw new FileAliasNotFoundException(fileAlias); 354 } 355 356 } 357 358 /** Returns the file type for the given file name containing in files.csv 359 * @param fileAlias the alias name of the file 360 * @return file type 361 * @throws FileAliasNotFoundException was thrown if not alias was thorwn 362 */ getTypeforfileAlias(String fileAlias)363 public String getTypeforfileAlias(String fileAlias) 364 throws FileAliasNotFoundException{ 365 try{ 366 return (String) m_hFileTypes.get(fileAlias).toString(); 367 } catch (java.lang.NullPointerException e){ 368 throw new FileAliasNotFoundException(fileAlias); 369 } 370 } 371 372 /** 373 * Filles the Hashtable m_hFileURLs with all file names and their URL 374 * and the Hashtable m_hFilesTypes with all file names and thier file 375 * typ name. This informations are extracted from "files.csv" 376 * This is for faster acccess to get fileURL and fileType of fileAlias 377 */ createFilesList()378 public void createFilesList(){ 379 for (int i = 0; i < m_vFiles.size();i++){ 380 Vector toDo = (Vector) m_vFiles.get(i); 381 m_hFileURLs.put((String) toDo.get(0).toString(), 382 (String) toDo.get(1).toString()); 383 m_hFileTypes.put((String) toDo.get(0).toString(), 384 (String) toDo.get(2).toString()); 385 } 386 } 387 388 389 /** Validate the returned file type for the file alias with the 390 * possible file types 391 * @param currentFileType the returned file type 392 * @param fileTypes all possible file types 393 * @return true if valid 394 */ checkFileType(String currentFileType, String fileTypes)395 public boolean checkFileType(String currentFileType, String fileTypes){ 396 397 StringTokenizer data = new StringTokenizer(fileTypes,":", true); 398 399 boolean found = false; 400 while (data.hasMoreElements()) { 401 402 String actualFileType = data.nextElement().toString(); 403 404 found = found || currentFileType.equals(actualFileType); 405 } 406 return found; 407 } 408 409 /** creates an input/output parameter of <code>PropertyValue[]<code>. 410 * @return PropertyValue[][] 411 * @param PropVal a PropertyValue 412 */ createInOutPropertyValue(PropertyValue[] PropVal)413 public PropertyValue[][] createInOutPropertyValue(PropertyValue[] PropVal){ 414 PropertyValue[][] dummy = new PropertyValue[1][]; 415 dummy[0] = PropVal; 416 return dummy; 417 } 418 getClassURL(String fileName)419 public URL getClassURL(String fileName){ 420 String PackagePath = this.getClass().getPackage().getName().replace('.','/'); 421 return this.getClass().getResource("/" + PackagePath +"/" + fileName); 422 } 423 getClassURLString(String fileName)424 public String getClassURLString(String fileName){ 425 return getClassURL(fileName).toString().replaceAll("file:",""); 426 } 427 428 429 } 430 431 /** This exeception should be thrown if a method seeks for an invalid alias name */ 432 class FileAliasNotFoundException extends java.lang.Exception{ 433 /** throws error message with wrong alias name 434 * @param fileAlias the alias name 435 */ FileAliasNotFoundException(String fileAlias)436 public FileAliasNotFoundException(String fileAlias){ 437 super("Could not get '"+fileAlias +"'"); 438 } 439 } 440