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