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 package util; 23 24 import com.sun.star.frame.XController; 25 import com.sun.star.frame.XDispatch; 26 import com.sun.star.frame.XDispatchProvider; 27 import com.sun.star.frame.XModel; 28 import com.sun.star.lang.XComponent; 29 import java.lang.System; 30 import java.util.StringTokenizer; 31 import java.io.*; 32 import java.util.ArrayList; 33 import java.io.RandomAccessFile; 34 import java.net.Socket; 35 import java.net.ServerSocket; 36 import java.net.URI; 37 import java.net.URISyntaxException; 38 39 import com.sun.star.beans.XPropertySet; 40 import com.sun.star.beans.Property; 41 import com.sun.star.lang.XMultiServiceFactory; 42 import com.sun.star.uno.UnoRuntime; 43 import com.sun.star.ucb.InteractiveAugmentedIOException; 44 import com.sun.star.ucb.XSimpleFileAccess; 45 import com.sun.star.lang.XServiceInfo; 46 47 import com.sun.star.util.URL; 48 import com.sun.star.util.XURLTransformer; 49 50 import com.sun.star.uno.AnyConverter; 51 import com.sun.star.uno.Type; 52 import com.sun.star.uno.XComponentContext; 53 import com.sun.star.util.XMacroExpander; 54 import java.text.DecimalFormat; 55 import java.util.Calendar; 56 57 import java.util.Collections; 58 import java.util.GregorianCalendar; 59 60 public class utils { 61 62 /** 63 * 64 * This method adds the DOCPTH to a given file 65 * 66 * @param sDocName the file which should be completed to the test doc path 67 * @return $TESTDOCPATH/sDocName 68 */ getFullTestDocName(String sDocName)69 public static String getFullTestDocName(String sDocName) { 70 String docpth = System.getProperty("DOCPTH"); 71 if (docpth.endsWith("\\") || docpth.endsWith("/")) { 72 docpth = docpth.substring(0, docpth.length() - 1); 73 } 74 75 System.out.println("docpth:" + docpth); 76 77 String pthSep = System.getProperty("file.separator"); 78 79 if (docpth.equals("unknown")) { 80 System.out.println("try to get tDoc from $SRC_ROOT/qadevOOo"); 81 String srcRoot = System.getProperty(PropertyName.SRC_ROOT); 82 if (srcRoot != null) { 83 File srcR = new File(srcRoot); 84 String[] list = srcR.list(new FilenameFilter() { 85 86 public boolean accept(File dir, String name) { 87 return name.startsWith("qadevOOo"); 88 } 89 }); 90 91 if (list[0] != null) { 92 String tDoc = srcRoot.concat(pthSep).concat(list[0]).concat(pthSep).concat("testdocs"); 93 94 if (new File(tDoc).exists()) { 95 docpth = tDoc; 96 } 97 } 98 } 99 } 100 101 if (docpth.startsWith("http:")) { 102 return docpth + "/" + sDocName; 103 } 104 String testdocPth = ""; 105 106 if (docpth.equals("unknown")) { 107 System.out.println("try to get tDoc from OBJDSCS"); 108 String objdscPth = System.getProperty("OBJDSCS"); 109 if (objdscPth != null) { 110 int i = objdscPth.indexOf("objdsc"); 111 String arcPth = objdscPth.substring(0, i - 1); 112 testdocPth = arcPth + pthSep + "doc" + pthSep + "java" + 113 pthSep + "testdocs" + pthSep + sDocName; 114 } 115 } else { 116 testdocPth = docpth + pthSep + sDocName; 117 } 118 return testdocPth; 119 } 120 121 /** 122 * 123 * This method adds the DOCPTH to a given file 124 * and changes the format to an file URL 125 * 126 */ getFullTestURL(String sDocName)127 public static String getFullTestURL(String sDocName) { 128 String fullDocPath = getFullTestDocName(sDocName); 129 if (fullDocPath.startsWith("http:")) { 130 return fullDocPath; 131 } 132 if (fullDocPath.startsWith("file:")) { 133 return fullDocPath; 134 } 135 String prefix = null; 136 137 // Windows: \\\\margritte\\qaapi\\workspace\\qadev\\testdocs/emptyChart.sds 138 if (fullDocPath.startsWith("\\\\")) { 139 prefix = "file:"; 140 } 141 142 fullDocPath = fullDocPath.replace('\\', '/'); 143 if (prefix == null) { 144 if (fullDocPath.startsWith("//")) { 145 prefix = "file:/"; 146 } else if (fullDocPath.startsWith("/")) { 147 prefix = "file://"; 148 } else { 149 prefix = "file:///"; 150 } 151 } 152 if (!fullDocPath.endsWith("/")) { 153 File aFile = new File(fullDocPath); 154 if (aFile.isDirectory()) { 155 fullDocPath += "/"; 156 } 157 } 158 String fulldocURL = prefix + fullDocPath; 159 return fulldocURL; 160 } 161 162 /** 163 * 164 * This method changes a given URL to a valid file URL 165 * 166 */ getFullURL(String sDocName)167 public static String getFullURL(String sDocName) { 168 String fullDocPath = sDocName; 169 fullDocPath = fullDocPath.replace('\\', '/'); 170 171 if (fullDocPath.startsWith("http:")) { 172 return fullDocPath; 173 } 174 if (fullDocPath.startsWith("ftp:")) { 175 return fullDocPath; 176 } 177 String prefix = ""; 178 if (!fullDocPath.startsWith("file:///")) { 179 if (fullDocPath.startsWith("//")) { 180 prefix = "file:"; 181 } else { 182 if (fullDocPath.startsWith("/")) { 183 prefix = "file://"; 184 // if (helper.OSHelper.isLinuxIntel()) 185 // { 186 // prefix = "file:/"; 187 // } 188 } 189 else 190 { 191 prefix = "file:///"; 192 } 193 } 194 } 195 if (!fullDocPath.endsWith("/")) { 196 File aFile = new File(fullDocPath); 197 if (aFile.isDirectory()) { 198 fullDocPath += "/"; 199 } 200 } 201 String fulldocURL = prefix + fullDocPath; 202 203 return fulldocURL; 204 } 205 206 /** 207 * 208 * This method creates folders needed 209 * 210 */ make_Directories(String first, String path)211 public static void make_Directories(String first, String path) { 212 String already_done = null; 213 String fs = System.getProperty("file.separator"); 214 StringTokenizer path_tokenizer = new StringTokenizer(path, fs, false); 215 already_done = first; 216 while (path_tokenizer.hasMoreTokens()) { 217 String part = path_tokenizer.nextToken(); 218 File new_dir = new File(already_done + File.separatorChar + part); 219 already_done = new_dir.toString(); 220 //create the directory 221 new_dir.mkdirs(); 222 } 223 return; 224 } 225 226 /** 227 * 228 * This method get the version for a given TestBase/platform combination 229 * 230 */ getVersion(String aFile, String aPlatform, String aTestbase)231 public static String getVersion(String aFile, String aPlatform, String aTestbase) { 232 if ((aFile == null) || (aPlatform == null) || (aTestbase == null)) { 233 return "/"; 234 } 235 236 File the_file = new File(aFile); 237 try { 238 RandomAccessFile raf = new RandomAccessFile(the_file, "r"); 239 String res = ""; 240 while (!res.equals("[" + aTestbase.toUpperCase() + "]")) { 241 res = raf.readLine(); 242 } 243 res = "=/"; 244 while ((!res.startsWith(aPlatform)) || (res.startsWith("["))) { 245 res = raf.readLine(); 246 } 247 raf.close(); 248 if (res.startsWith("[")) { 249 res = "/"; 250 } 251 return res.substring(res.indexOf("=") + 1); 252 253 } catch (Exception e) { 254 System.out.println("Couldn't find version"); 255 return "/"; 256 } 257 } 258 259 /** 260 * 261 * This method gets the user dir of the connected office 262 * 263 */ getOfficeUserPath(XMultiServiceFactory msf)264 public static String getOfficeUserPath(XMultiServiceFactory msf) { 265 String userPath = null; 266 267 // get a folder which is located in the user dir 268 try { 269 userPath = (String) getOfficeSettingsValue(msf, "UserConfig"); 270 } catch (Exception e) { 271 System.out.println("Couldn't get Office User Path"); 272 e.printStackTrace(); 273 } 274 275 // strip the returned folder to the user dir 276 if (userPath.charAt(userPath.length() - 1) == '/') { 277 userPath = userPath.substring(0, userPath.length() - 1); 278 } 279 int index = userPath.lastIndexOf('/'); 280 if (index != -1) { 281 userPath = userPath.substring(0, index); 282 } 283 284 return userPath; 285 } 286 287 /** 288 * In the office there are some settings available. This function 289 * returns the value of the given setting name. For Example the setting name "Temp" 290 * "Temp" returns the temp folder of the office instance. 291 * @param msf a XMultiServiceFactory 292 * @param setting the name of the setting the value should be returned. 293 * For example "Temp" returns the temp folder of the current office instance. 294 * @see com.sun.star.util.PathSettings 295 * @return the value as String 296 */ getOfficeSettingsValue(XMultiServiceFactory msf, String setting)297 public static String getOfficeSettingsValue(XMultiServiceFactory msf, String setting) { 298 299 String settingPath = null; 300 try { 301 Object settings = msf.createInstance("com.sun.star.comp.framework.PathSettings"); 302 XPropertySet pthSettings = null; 303 try { 304 pthSettings = (XPropertySet) AnyConverter.toObject( 305 new Type(XPropertySet.class), settings); 306 } catch (com.sun.star.lang.IllegalArgumentException iae) { 307 System.out.println("### couldn't get Office Settings"); 308 } 309 settingPath = (String) pthSettings.getPropertyValue(setting); 310 311 } catch (Exception e) { 312 System.out.println("Couldn't get setting value for " + setting); 313 e.printStackTrace(); 314 } 315 return settingPath; 316 } 317 setOfficeSettingsValue(XMultiServiceFactory msf, String setting, String value)318 public static void setOfficeSettingsValue(XMultiServiceFactory msf, String setting, String value) { 319 320 String settingPath = null; 321 try { 322 Object settings = msf.createInstance("com.sun.star.comp.framework.PathSettings"); 323 XPropertySet pthSettings = null; 324 try { 325 pthSettings = (XPropertySet) AnyConverter.toObject( 326 new Type(XPropertySet.class), settings); 327 } catch (com.sun.star.lang.IllegalArgumentException iae) { 328 System.out.println("### couldn't get Office Settings"); 329 } 330 pthSettings.setPropertyValue(setting, value); 331 332 } catch (Exception e) { 333 System.out.println("Couldn't set '" + setting + "' to value '" + value + "'"); 334 e.printStackTrace(); 335 } 336 } 337 338 /** 339 * This method returns the temp directory of the user. 340 * Since Java 1.4 it is not possible to read environment variables. To workaround 341 * this, the Java parameter -D could be used. 342 */ getUsersTempDir()343 public static String getUsersTempDir() { 344 String tempDir = System.getProperty("my.temp"); 345 if (tempDir == null) { 346 tempDir = System.getProperty("my.tmp"); 347 if (tempDir == null) { 348 tempDir = System.getProperty("java.io.tmpdir"); 349 } 350 } 351 // remove ending file separator 352 if (tempDir.endsWith(System.getProperty("file.separator"))) { 353 tempDir = tempDir.substring(0, tempDir.length() - 1); 354 } 355 356 return tempDir; 357 } 358 359 /** 360 * 361 * This method gets the temp dir of the connected office 362 * 363 */ getOfficeTemp(XMultiServiceFactory msf)364 public static String getOfficeTemp(XMultiServiceFactory msf) { 365 String url = getOfficeUserPath(msf) + "/test-temp/"; 366 try { 367 new File(new URI(url)).mkdir(); 368 } catch (URISyntaxException e) { 369 throw new RuntimeException(e); 370 } 371 return url; 372 } 373 374 /** 375 * Gets OpenOffice temp directory without 'file:///' prefix. 376 * For example is useful for Registry URL specifying. 377 * @msf Office factory for accessing its settings. 378 * @return SOffice temporary directory in form for example 379 * 'd:/Office60/user/temp/'. 380 */ getOfficeTempDir(XMultiServiceFactory msf)381 public static String getOfficeTempDir(XMultiServiceFactory msf) { 382 383 String dir = getOfficeTemp(msf); 384 385 int idx = dir.indexOf("file:///"); 386 387 if (idx < 0) { 388 return dir; 389 } 390 391 dir = dir.substring("file:///".length()); 392 393 idx = dir.indexOf(":"); 394 395 // is the last character a '/' or a '\'? 396 boolean lastCharSet = dir.endsWith("/") || dir.endsWith("\\"); 397 398 if (idx < 0) { // linux or solaris 399 dir = "/" + dir; 400 dir += lastCharSet ? "" : "/"; 401 } else { // windows 402 dir += lastCharSet ? "" : "\\"; 403 } 404 405 return dir; 406 } 407 408 /** 409 * Gets OpenOffice temp directory without 'file:///' prefix. 410 * and System dependent file separator 411 */ getOfficeTempDirSys(XMultiServiceFactory msf)412 public static String getOfficeTempDirSys(XMultiServiceFactory msf) { 413 414 String dir = getOfficeTemp(msf); 415 String sysDir = ""; 416 417 int idx = dir.indexOf("file://"); 418 419 // remove leading 'file://' 420 if (idx < 0) { 421 sysDir = dir; 422 } else { 423 sysDir = dir.substring("file://".length()); 424 } 425 426 // append '/' if not there (e.g. linux) 427 if (sysDir.charAt(sysDir.length() - 1) != '/') { 428 sysDir += "/"; 429 } 430 431 // remove leading '/' and replace others with '\' on Windows machines 432 if (sysDir.indexOf(":") != -1) { 433 sysDir = sysDir.substring(1); 434 sysDir = sysDir.replace('/', '\\'); 435 } 436 return sysDir; 437 } 438 439 /** 440 * converts a fileURL to a system URL 441 * @param fileURL a file URL 442 * @return a system URL 443 */ getSystemURL(String fileURL)444 public static String getSystemURL(String fileURL) { 445 String sysDir = ""; 446 447 int idx = fileURL.indexOf("file://"); 448 449 // remove leading 'file://' 450 if (idx < 0) { 451 sysDir = fileURL; 452 } else { 453 sysDir = fileURL.substring("file://".length()); 454 } 455 456 // remove leading '/' and replace others with '\' on Windows machines 457 if (sysDir.indexOf(":") != -1) { 458 sysDir = sysDir.substring(1); 459 sysDir = sysDir.replace('/', '\\'); 460 } 461 return sysDir; 462 } 463 464 /** 465 * This method check via Office the existence of the given file URL 466 * @param msf the multiservice factory 467 * @param fileURL the file which existence should be checked 468 * @return true if the file exists, else false 469 */ fileExists(XMultiServiceFactory msf, String fileURL)470 public static boolean fileExists(XMultiServiceFactory msf, String fileURL) { 471 boolean exists = false; 472 try { 473 474 Object fileacc = msf.createInstance("com.sun.star.comp.ucb.SimpleFileAccess"); 475 XSimpleFileAccess simpleAccess = (XSimpleFileAccess) UnoRuntime.queryInterface(XSimpleFileAccess.class, 476 fileacc); 477 if (simpleAccess.exists(fileURL)) { 478 exists = true; 479 } 480 481 } catch (Exception e) { 482 System.out.println("Couldn't access file '" + fileURL + "'"); 483 e.printStackTrace(); 484 exists = false; 485 } 486 return exists; 487 } 488 489 /** 490 * This method deletes via office the given file URL. It checks the existence 491 * of <CODE>fileURL</CODE>. If exists it will be deleted. 492 * @param xMsf the multiservice factory 493 * @param fileURL the file to delete 494 * @return true if the file could be deleted or the file does not exist 495 */ deleteFile(XMultiServiceFactory xMsf, String fileURL)496 public static boolean deleteFile(XMultiServiceFactory xMsf, String fileURL) { 497 boolean delete = true; 498 try { 499 500 Object fileacc = xMsf.createInstance("com.sun.star.comp.ucb.SimpleFileAccess"); 501 XSimpleFileAccess simpleAccess = (XSimpleFileAccess) UnoRuntime.queryInterface(XSimpleFileAccess.class, 502 fileacc); 503 if (simpleAccess.exists(fileURL)) { 504 simpleAccess.kill(fileURL); 505 } 506 507 } catch (Exception e) { 508 System.out.println("Couldn't delete file '" + fileURL + "'"); 509 e.printStackTrace(); 510 delete = false; 511 } 512 return delete; 513 } 514 515 /** 516 * This method copies via office a given file to a new one 517 * @param xMsf the multi service factory 518 * @param source the source file 519 * @param destination the destination file 520 * @return true at success 521 */ copyFile(XMultiServiceFactory xMsf, String source, String destinaion)522 public static boolean copyFile(XMultiServiceFactory xMsf, String source, String destinaion) { 523 boolean res = false; 524 try { 525 Object fileacc = xMsf.createInstance("com.sun.star.comp.ucb.SimpleFileAccess"); 526 XSimpleFileAccess simpleAccess = (XSimpleFileAccess) UnoRuntime.queryInterface(XSimpleFileAccess.class, 527 fileacc); 528 if (!simpleAccess.exists(destinaion)) { 529 simpleAccess.copy(source, destinaion); 530 } 531 532 res = true; 533 } catch (Exception e) { 534 System.out.println("Couldn't copy file '" + source + "' -> '" + destinaion + "'"); 535 e.printStackTrace(); 536 res = false; 537 } 538 return res; 539 } 540 overwriteFile_impl( XMultiServiceFactory xMsf, String oldF, String newF)541 private static void overwriteFile_impl( 542 XMultiServiceFactory xMsf, String oldF, String newF) 543 throws InteractiveAugmentedIOException 544 { 545 try { 546 Object fileacc = xMsf.createInstance("com.sun.star.comp.ucb.SimpleFileAccess"); 547 548 XSimpleFileAccess simpleAccess = (XSimpleFileAccess) UnoRuntime.queryInterface(XSimpleFileAccess.class, 549 fileacc); 550 if (simpleAccess.exists(newF)) { 551 simpleAccess.kill(newF); 552 } 553 simpleAccess.copy(oldF, newF); 554 } catch (InteractiveAugmentedIOException e) { 555 throw e; 556 } catch (com.sun.star.uno.Exception e) { 557 System.out.println("Couldn't copy " + oldF + " to " + newF + ":"); 558 e.printStackTrace(); 559 throw new RuntimeException(e); 560 } 561 } 562 563 /** 564 * Copies file to a new location using OpenOffice.org features. If the target 565 * file already exists, the file is deleted. 566 * 567 * @returns <code>true</code> if the file was successfully copied, 568 * <code>false</code> if some errors occurred (e.g. file is locked, used 569 * by another process). 570 */ tryOverwriteFile( XMultiServiceFactory xMsf, String oldF, String newF)571 public static boolean tryOverwriteFile( 572 XMultiServiceFactory xMsf, String oldF, String newF) 573 { 574 try { 575 overwriteFile_impl(xMsf, oldF, newF); 576 } catch (InteractiveAugmentedIOException e) { 577 return false; 578 } 579 return true; 580 } 581 doOverwriteFile( XMultiServiceFactory xMsf, String oldF, String newF)582 public static void doOverwriteFile( 583 XMultiServiceFactory xMsf, String oldF, String newF) 584 { 585 try { 586 overwriteFile_impl(xMsf, oldF, newF); 587 } catch (InteractiveAugmentedIOException e) { 588 throw new RuntimeException(e); 589 } 590 } 591 hasPropertyByName(XPropertySet props, String aName)592 public static boolean hasPropertyByName(XPropertySet props, String aName) { 593 Property[] list = props.getPropertySetInfo().getProperties(); 594 boolean res = false; 595 for (int i = 0; i < list.length; i++) { 596 String the_name = list[i].Name; 597 if (aName.equals(the_name)) { 598 res = true; 599 } 600 } 601 return res; 602 } 603 604 /** 605 * 606 * This method returns the implementation name of a given object 607 * 608 */ getImplName(Object aObject)609 public static String getImplName(Object aObject) { 610 String res = "Error getting Implementation name"; 611 try { 612 XServiceInfo xSI = (XServiceInfo) UnoRuntime.queryInterface(XServiceInfo.class, aObject); 613 res = xSI.getImplementationName(); 614 } catch (Exception e) { 615 res = "Error getting Implementation name ( " + e + " )"; 616 } 617 618 return res; 619 } 620 621 /** 622 * 623 * This method checks if an Object is void 624 * 625 */ isVoid(Object aObject)626 public static boolean isVoid(Object aObject) { 627 if (aObject instanceof com.sun.star.uno.Any) { 628 com.sun.star.uno.Any oAny = (com.sun.star.uno.Any) aObject; 629 return (oAny.getType().getTypeName().equals("void")); 630 } else { 631 return false; 632 } 633 634 } 635 636 /** 637 * 638 * This method replaces a substring with another 639 * 640 */ replacePart(String all, String toReplace, String replacement)641 public static String replacePart(String all, String toReplace, String replacement) { 642 return replaceAll13(all, toReplace, replacement); 643 } 644 645 /** 646 * Scan localhost for the next free port-number from a starting port 647 * on. If the starting port is smaller than 1024, port number starts with 648 * 10000 as default, because numbers < 1024 are never free on unix machines. 649 * @param startPort The port where scanning starts. 650 * @return The next free port. 651 */ getNextFreePort(int startPort)652 public static int getNextFreePort(int startPort) { 653 if (startPort < 1024) { 654 startPort = 10000; 655 } 656 for (int port = startPort; port < 65536; port++) { 657 System.out.println("Scan port " + port); 658 try { 659 // first trying to establish a server-socket on localhost 660 // fails if there is already a server running 661 ServerSocket sSock = new ServerSocket(port); 662 sSock.close(); 663 } catch (IOException e) { 664 System.out.println(" -> server: occupied port " + port); 665 continue; 666 } 667 try { 668 // now trying to establish a client-socket 669 // fails if there is no server on any connectable machine 670 Socket sock = new Socket("localhost", port); 671 System.out.println(" -> socket: occupied port: " + port); 672 } catch (IOException e) { 673 System.out.println(" -> free port"); 674 return port; 675 } 676 } 677 return 65535; 678 } 679 parseURL(XMultiServiceFactory xMSF, String url)680 public static URL parseURL(XMultiServiceFactory xMSF, String url) { 681 URL[] rUrl = new URL[1]; 682 rUrl[0] = new URL(); 683 rUrl[0].Complete = url; 684 685 XURLTransformer xTrans = null; 686 try { 687 Object inst = xMSF.createInstance("com.sun.star.util.URLTransformer"); 688 xTrans = (XURLTransformer) UnoRuntime.queryInterface(XURLTransformer.class, inst); 689 } catch (com.sun.star.uno.Exception e) { 690 } 691 692 xTrans.parseStrict(rUrl); 693 694 return rUrl[0]; 695 } 696 getOfficeURL(XMultiServiceFactory msf)697 public static String getOfficeURL(XMultiServiceFactory msf) { 698 try { 699 Object settings = msf.createInstance("com.sun.star.util.PathSettings"); 700 XPropertySet settingProps = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, settings); 701 String path = (String) settingProps.getPropertyValue("Module"); 702 return path; 703 } catch (Exception e) { 704 System.out.println("Couldn't get Office Settings "); 705 e.printStackTrace(); 706 } 707 return null; 708 } 709 710 /** returns the path to the office binary folder 711 * 712 * @param msf The XMultiSeriveFactory 713 * @return the path to the office binary or an empty string on any error 714 */ getOfficeBinPath(XMultiServiceFactory msf)715 public static String getOfficeBinPath(XMultiServiceFactory msf) { 716 String sysBinDir = ""; 717 try { 718 sysBinDir = utils.getSystemURL(utils.expandMacro(msf, "$SYSBINDIR")); 719 } catch (java.lang.Exception e) { 720 } 721 722 return sysBinDir; 723 } 724 725 /** 726 * Get an array of all property names from the property set. With the include 727 * and exclude parameters the properties can be filtered. <br> 728 * Set excludePropertyAttribute = 0 and includePropertyAttribute = 0 729 * to include all and exclude none. 730 * @param props The instance of XPropertySet 731 * @param includePropertyAttribute Properties without these attributes are filtered and will not be returned. 732 * @param excludePropertyAttribute Properties with these attributes are filtered and will not be returned. 733 * @return A String array with all property names. 734 * @see com.sun.star.beans.XPropertySet 735 * @see com.sun.star.beans.Property 736 * @see com.sun.star.beans.PropertyAttribute 737 */ getFilteredPropertyNames(XPropertySet props, short includePropertyAttribute, short excludePropertyAttribute)738 public static String[] getFilteredPropertyNames(XPropertySet props, short includePropertyAttribute, 739 short excludePropertyAttribute) { 740 Property[] the_props = props.getPropertySetInfo().getProperties(); 741 ArrayList l = new ArrayList(); 742 for (int i = 0; i < the_props.length; i++) { 743 boolean exclude = ((the_props[i].Attributes & excludePropertyAttribute) != 0); 744 boolean include = (includePropertyAttribute == 0) || 745 ((the_props[i].Attributes & includePropertyAttribute) != 0); 746 if (include && !exclude) { 747 l.add(the_props[i].Name); 748 } 749 } 750 Collections.sort(l); 751 String[] names = new String[l.size()]; 752 names = (String[]) l.toArray(names); 753 return names; 754 } 755 756 /** Causes the thread to sleep some time. 757 * It can be used f.e. like: 758 * util.utils.shortWait(tParam.getInt("ShortWait")); 759 */ shortWait(int milliseconds)760 public static void shortWait(int milliseconds) { 761 try { 762 Thread.currentThread().sleep(milliseconds); 763 } catch (InterruptedException e) { 764 System.out.println("While waiting :" + e); 765 } 766 } 767 768 /** 769 * Validate the AppExecutionCommand. Returned is an error message, starting 770 * with "Error:", or a warning, if the command might work. 771 * @param appExecCommand The application execution command that is checked. 772 * @param os The operating system where the check runs. 773 * @return The error message, or OK, if no error was detected. 774 */ validateAppExecutionCommand(String appExecCommand, String os)775 public static String validateAppExecutionCommand(String appExecCommand, String os) { 776 String errorMessage = "OK"; 777 appExecCommand = replaceAll13(appExecCommand, "\"", ""); 778 appExecCommand = replaceAll13(appExecCommand, "'", ""); 779 StringTokenizer commandTokens = new StringTokenizer(appExecCommand, " \t"); 780 String officeExecutable = ""; 781 String officeExecCommand = "soffice"; 782 // is there a 'soffice' in the command? TODO: eliminate case sensitivity on Windows 783 int index = -1; 784 while (commandTokens.hasMoreTokens() && index == -1) { 785 officeExecutable += commandTokens.nextToken() + " "; 786 index = officeExecutable.indexOf(officeExecCommand); 787 } 788 if (index == -1) { 789 errorMessage = "Error: Your 'AppExecutionCommand' parameter does not " + 790 "contain '" + officeExecCommand + "'."; 791 } else { 792 // does the directory exist? 793 officeExecutable = officeExecutable.trim(); 794 String officePath = officeExecutable.substring(0, index); 795 File f = new File(officePath); 796 if (!f.exists() || !f.isDirectory()) { 797 errorMessage = "Error: Your 'AppExecutionCommand' parameter does not " + 798 "point to a valid system directory: " + officePath; 799 } else { 800 // is it an office installation? 801 f = new File(officeExecutable); 802 // one try for Windows platform can't be wrong... 803 if (!f.exists() || !f.isFile()) { 804 f = new File(officeExecutable + ".exe"); 805 } 806 if (!f.exists() || !f.isFile()) { 807 errorMessage = "Error: Your 'AppExecutionCommand' parameter does not " + 808 "point to a valid office installation."; 809 } else { 810 // do we have the accept parameter? 811 boolean gotNoAccept = true; 812 while (commandTokens.hasMoreElements()) { 813 String officeParam = commandTokens.nextToken(); 814 if (officeParam.indexOf("-accept=") != -1) { 815 gotNoAccept = false; 816 errorMessage = validateConnectString(officeParam, true); 817 } 818 } 819 if (gotNoAccept) { 820 errorMessage = "Error: Your 'AppExecutionCommand' parameter does not " + 821 "contain a '-accept' parameter for connecting the office."; 822 } 823 } 824 } 825 } 826 return errorMessage; 827 } 828 829 /** 830 * Validate the connection string. Returned is an error message, starting 831 * with "Error:", or a warning, if the command might work. 832 * @param connectString The connection string that is checked. 833 * @param checkAppExecutionCommand If the AppExecutionCommand is checked, the error messages willbe different. 834 * @return The error message, or OK, if no error was detected. 835 */ validateConnectString(String connectString, boolean checkAppExecutionCommand)836 public static String validateConnectString(String connectString, boolean checkAppExecutionCommand) { 837 String acceptPrefix = ""; 838 if (checkAppExecutionCommand) { 839 acceptPrefix = "-accept="; 840 } 841 842 String errorMessage = "OK"; 843 // a warning, if an unknown connection method is used 844 if (connectString.indexOf("socket") != -1) { 845 if (connectString.indexOf(acceptPrefix + "socket,host=") == -1 || 846 connectString.indexOf("port=") == -1) { 847 if (checkAppExecutionCommand) { 848 errorMessage = "Error: The '-accept' parameter contains a syntax error: It should be like: '-accept=socket,host=localhost,port=8100;urp;"; 849 } else { 850 errorMessage = "Error: The 'ConnectionString' parameter contains a syntax error: It should be like: 'socket,host=localhost,port=8100'"; 851 } 852 } 853 } else if (connectString.indexOf("pipe") != -1) { 854 if (connectString.indexOf(acceptPrefix + "pipe,name=") == -1) { 855 if (checkAppExecutionCommand) { 856 errorMessage = "Error: The '-accept' parameter contains a syntax error: It should be like: '-accept=pipe,name=myuniquename;urp;'"; 857 } else { 858 errorMessage = "Error: The 'ConnectionString' parameter contains a syntax error: It should be like: 'pipe,name=myuniquename'"; 859 } 860 } 861 } else { 862 if (checkAppExecutionCommand) { 863 errorMessage = "Warning: The '-accept' parameter contains an unknown connection method."; 864 } else { 865 errorMessage = "Warning: The 'ConnectionString' parameter contains an unknown connection method."; 866 } 867 } 868 return errorMessage; 869 } 870 871 /** 872 * String.replaceAll() ist available since Java 1.4 but the runner must be buldabale with Java 1.3 873 * @param originalString 874 * @param searchString 875 * @param replaceString 876 * @return modified string 877 */ replaceAll13(String originalString, String searchString, String replaceString)878 public static String replaceAll13(String originalString, String searchString, String replaceString) { 879 880 StringBuffer changeStringBuffer = new StringBuffer(originalString); 881 int searchLength = searchString.length(); 882 int replaceLength = replaceString.length(); 883 int index = originalString.indexOf(searchString); 884 while (index != -1) { 885 changeStringBuffer = changeStringBuffer.replace(index, index + searchLength, replaceString); 886 originalString = changeStringBuffer.toString(); 887 index = originalString.indexOf(searchString, index + replaceLength); 888 } 889 return originalString; 890 } 891 892 /** 893 * expand macrofied strings like <CODE>${$ORIGIN/bootstrap.ini:UserInstallation}</CODE> or 894 * <CODE>$_OS</CODE> 895 * @param xMSF the MultiServiceFactory 896 * @param expand the string to expand 897 * @throws java.lang.Exception was thrown on any exception 898 * @return return the expanded string 899 * @see com.sun.star.util.XMacroExpander 900 */ expandMacro(XMultiServiceFactory xMSF, String expand)901 public static String expandMacro(XMultiServiceFactory xMSF, String expand) throws java.lang.Exception { 902 try { 903 XPropertySet xPS = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, xMSF); 904 XComponentContext xContext = (XComponentContext) UnoRuntime.queryInterface(XComponentContext.class, 905 xPS.getPropertyValue("DefaultContext")); 906 XMacroExpander xME = (XMacroExpander) UnoRuntime.queryInterface(XMacroExpander.class, 907 xContext.getValueByName("/singletons/com.sun.star.util.theMacroExpander")); 908 return xME.expandMacros(expand); 909 } catch (Exception e) { 910 throw new Exception("could not expand macro: " + e.toString(), e); 911 } 912 913 } 914 915 /** 916 * returns the platform of the office.<br> 917 * Since the runner and the office could run on different platform this function delivers the 918 * platform the office is running. 919 * @param xMSF the XMultiServiceFactory 920 * @return unxsols, unxsoli, unxlngi, wntmsci 921 */ getOfficeOS(XMultiServiceFactory xMSF)922 public static String getOfficeOS(XMultiServiceFactory xMSF) { 923 String platform = "unknown"; 924 925 try { 926 String theOS = expandMacro(xMSF, "$_OS"); 927 928 if (theOS.equals("Windows")) { 929 platform = "wntmsci"; 930 } else if (theOS.equals("Linux")) { 931 platform = "unxlngi"; 932 } else { 933 if (theOS.equals("Solaris")) { 934 String theArch = expandMacro(xMSF, "$_ARCH"); 935 if (theArch.equals("SPARC")) { 936 platform = "unxsols"; 937 } else if (theArch.equals("x86")) { 938 platform = "unxsoli"; 939 } 940 } 941 } 942 } catch (Exception ex) { 943 } 944 return platform; 945 } 946 947 /** 948 * dispatches given <CODE>URL</CODE> to the document <CODE>XComponent</CODE> 949 * @param xMSF the <CODE>XMultiServiceFactory</CODE> 950 * @param xDoc the document where to dispatch 951 * @param URL the <CODE>URL</CODE> to dispatch 952 * @throws java.lang.Exception throws <CODE>java.lang.Exception</CODE> on any error 953 */ dispatchURL(XMultiServiceFactory xMSF, XComponent xDoc, String URL)954 public static void dispatchURL(XMultiServiceFactory xMSF, XComponent xDoc, String URL) throws java.lang.Exception { 955 XModel aModel = (XModel) UnoRuntime.queryInterface(XModel.class, xDoc); 956 957 XController xCont = aModel.getCurrentController(); 958 959 dispatchURL(xMSF, xCont, URL); 960 961 } 962 963 /** 964 * dispatches given <CODE>URL</CODE> to the <CODE>XController</CODE> 965 * @param xMSF the <CODE>XMultiServiceFactory</CODE> 966 * @param xCont the <CODE>XController</CODE> to query for a XDispatchProvider 967 * @param URL the <CODE>URL</CODE> to dispatch 968 * @throws java.lang.Exception throws <CODE>java.lang.Exception</CODE> on any error 969 */ dispatchURL(XMultiServiceFactory xMSF, XController xCont, String URL)970 public static void dispatchURL(XMultiServiceFactory xMSF, XController xCont, String URL) throws java.lang.Exception { 971 try { 972 973 XDispatchProvider xDispProv = (XDispatchProvider) UnoRuntime.queryInterface(XDispatchProvider.class, xCont); 974 975 XURLTransformer xParser = (com.sun.star.util.XURLTransformer) UnoRuntime.queryInterface( 976 XURLTransformer.class, 977 xMSF.createInstance("com.sun.star.util.URLTransformer")); 978 979 // Because it's an in/out parameter we must use an array of URL objects. 980 URL[] aParseURL = new URL[1]; 981 aParseURL[0] = new URL(); 982 aParseURL[0].Complete = URL; 983 xParser.parseStrict(aParseURL); 984 985 URL aURL = aParseURL[0]; 986 987 XDispatch xDispatcher = xDispProv.queryDispatch(aURL, "", 0); 988 xDispatcher.dispatch(aURL, null); 989 990 utils.shortWait(3000); 991 992 } catch (Exception e) { 993 throw new Exception("ERROR: could not dispatch URL '" + URL + "': " + e.toString()); 994 } 995 } 996 997 /** returns a String which contains the current date and time<br> 998 * format: [DD.MM.YYYY - HH:MM:SS::mm] 999 * 1000 ** @return a String which contains the current date and time 1001 */ getDateTime()1002 public static String getDateTime() { 1003 1004 Calendar cal = new GregorianCalendar(); 1005 DecimalFormat dfmt = new DecimalFormat("00"); 1006 String dateTime = dfmt.format(cal.get(Calendar.DAY_OF_MONTH)) + "." + 1007 dfmt.format(cal.get(Calendar.MONTH) + 1) + "." + 1008 dfmt.format(cal.get(Calendar.YEAR)) + " - " + 1009 dfmt.format(cal.get(Calendar.HOUR_OF_DAY)) + ":" + 1010 dfmt.format(cal.get(Calendar.MINUTE)) + ":" + 1011 dfmt.format(cal.get(Calendar.SECOND)) + "," + 1012 dfmt.format(cal.get(Calendar.MILLISECOND)); 1013 return "[" + dateTime + "]"; 1014 } 1015 } 1016