update dev300-m58
[ooovba.git] / qadevOOo / runner / util / utils.java
blobaab620e993344ea22105614b60c11f684ab88367
1 /*************************************************************************
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * Copyright 2008 by Sun Microsystems, Inc.
7 * OpenOffice.org - a multi-platform office productivity suite
9 * $RCSfile: utils.java,v $
10 * $Revision: 1.17.2.3 $
12 * This file is part of OpenOffice.org.
14 * OpenOffice.org is free software: you can redistribute it and/or modify
15 * it under the terms of the GNU Lesser General Public License version 3
16 * only, as published by the Free Software Foundation.
18 * OpenOffice.org is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU Lesser General Public License version 3 for more details
22 * (a copy is included in the LICENSE file that accompanied this code).
24 * You should have received a copy of the GNU Lesser General Public License
25 * version 3 along with OpenOffice.org. If not, see
26 * <http://www.openoffice.org/license.html>
27 * for a copy of the LGPLv3 License.
29 ************************************************************************/
30 package util;
32 import com.sun.star.frame.XController;
33 import com.sun.star.frame.XDispatch;
34 import com.sun.star.frame.XDispatchProvider;
35 import com.sun.star.frame.XModel;
36 import com.sun.star.lang.XComponent;
37 import java.lang.System;
38 import java.util.StringTokenizer;
39 import java.io.*;
40 import java.util.ArrayList;
41 import java.io.RandomAccessFile;
42 import java.net.Socket;
43 import java.net.ServerSocket;
45 import com.sun.star.beans.XPropertySet;
46 import com.sun.star.beans.Property;
47 import com.sun.star.lang.XMultiServiceFactory;
48 import com.sun.star.uno.UnoRuntime;
49 import com.sun.star.ucb.XSimpleFileAccess;
50 import com.sun.star.lang.XServiceInfo;
52 import com.sun.star.util.URL;
53 import com.sun.star.util.XURLTransformer;
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;
62 import java.util.Collections;
63 import java.util.GregorianCalendar;
65 public class utils {
67 /**
69 * This method adds the DOCPTH to a given file
71 * @param sDocName the file which should be completed to the test doc path
72 * @return $TESTDOCPATH/sDocName
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);
80 System.out.println("docpth:" + docpth);
82 String pthSep = System.getProperty("file.separator");
84 if (docpth.equals("unkown")) {
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() {
91 public boolean accept(File dir, String name) {
92 return name.startsWith("qadevOOo");
94 });
96 if (list[0] != null) {
97 String tDoc = srcRoot.concat(pthSep).concat(list[0]).concat(pthSep).concat("testdocs");
99 if (new File(tDoc).exists()) {
100 docpth = tDoc;
106 if (docpth.startsWith("http:")) {
107 return docpth + "/" + sDocName;
109 String testdocPth = "";
111 if (docpth.equals("unkown")) {
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;
120 } else {
121 testdocPth = docpth + pthSep + sDocName;
123 return testdocPth;
128 * This method adds the DOCPTH to a given file
129 * and changes the format to an file URL
132 public static String getFullTestURL(String sDocName) {
133 String fullDocPath = getFullTestDocName(sDocName);
134 if (fullDocPath.startsWith("http:")) {
135 return fullDocPath;
137 if (fullDocPath.startsWith("file:")) {
138 return fullDocPath;
140 String prefix = null;
142 // Windows: \\\\margritte\\qaapi\\workspace\\qadev\\testdocs/emptyChart.sds
143 if (fullDocPath.startsWith("\\\\")) {
144 prefix = "file:";
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:///";
157 if (!fullDocPath.endsWith("/")) {
158 File aFile = new File(fullDocPath);
159 if (aFile.isDirectory()) {
160 fullDocPath += "/";
163 String fulldocURL = prefix + fullDocPath;
164 return fulldocURL;
169 * This method changes a given URL to a valid file URL
172 public static String getFullURL(String sDocName) {
173 String fullDocPath = sDocName;
174 fullDocPath = fullDocPath.replace('\\', '/');
176 if (fullDocPath.startsWith("http:")) {
177 return fullDocPath;
179 if (fullDocPath.startsWith("ftp:")) {
180 return fullDocPath;
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 // }
194 else
196 prefix = "file:///";
200 if (!fullDocPath.endsWith("/")) {
201 File aFile = new File(fullDocPath);
202 if (aFile.isDirectory()) {
203 fullDocPath += "/";
206 String fulldocURL = prefix + fullDocPath;
208 return fulldocURL;
213 * This method creates folders needed
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();
228 return;
233 * This method get the version for a given TestBase/platform combination
236 public static String getVersion(String aFile, String aPlatform, String aTestbase) {
237 if ((aFile == null) || (aPlatform == null) || (aTestbase == null)) {
238 return "/";
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();
248 res = "=/";
249 while ((!res.startsWith(aPlatform)) || (res.startsWith("["))) {
250 res = raf.readLine();
252 raf.close();
253 if (res.startsWith("[")) {
254 res = "/";
256 return res.substring(res.indexOf("=") + 1);
258 } catch (Exception e) {
259 System.out.println("Couldn't find version");
260 return "/";
266 * This method get's the user dir of the connected office
269 public static String getOfficeUserPath(XMultiServiceFactory msf) {
270 String userPath = null;
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();
280 // strip the returned folder to the user dir
281 if (userPath.charAt(userPath.length() - 1) == '/') {
282 userPath = userPath.substring(0, userPath.length() - 1);
284 int index = userPath.lastIndexOf('/');
285 if (index != -1) {
286 userPath = userPath.substring(0, index);
289 return userPath;
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
302 public static String getOfficeSettingsValue(XMultiServiceFactory msf, String setting) {
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");
314 settingPath = (String) pthSettings.getPropertyValue(setting);
316 } catch (Exception e) {
317 System.out.println("Couldn't get stting value for " + setting);
318 e.printStackTrace();
320 return settingPath;
323 public static void setOfficeSettingsValue(XMultiServiceFactory msf, String setting, String value) {
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");
335 pthSettings.setPropertyValue(setting, value);
337 } catch (Exception e) {
338 System.out.println("Couldn't set '" + setting + "' to value '" + value + "'");
339 e.printStackTrace();
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.
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");
356 // remove ending file separator
357 if (tempDir.endsWith(System.getProperty("file.separator"))) {
358 tempDir = tempDir.substring(0, tempDir.length() - 1);
361 return tempDir;
366 * This method get's the temp dir of the connected office
369 public static String getOfficeTemp(XMultiServiceFactory msf) {
370 String tmpDir = util.utils.getUsersTempDir();
371 try {
372 String tmp = (String) getOfficeSettingsValue(msf, "Temp");
373 if (!tmp.endsWith(System.getProperty("file.separator"))) {
374 tmp += System.getProperty("file.separator");
376 tmpDir = getFullURL(tmp);
377 } catch (Exception e) {
378 System.out.println("Couldn't get Office TEMP");
379 e.printStackTrace();
381 return tmpDir;
385 * Gets StarOffice temp directory without 'file:///' prefix.
386 * For example is usefull for Registry URL specifying.
387 * @msf Office factory for accessing its settings.
388 * @return SOffice temporary directory in form for example
389 * 'd:/Office60/user/temp/'.
391 public static String getOfficeTempDir(XMultiServiceFactory msf) {
393 String dir = getOfficeTemp(msf);
395 int idx = dir.indexOf("file:///");
397 if (idx < 0) {
398 return dir;
401 dir = dir.substring("file:///".length());
403 idx = dir.indexOf(":");
405 // is the last character a '/' or a '\'?
406 boolean lastCharSet = dir.endsWith("/") || dir.endsWith("\\");
408 if (idx < 0) { // linux or solaris
409 dir = "/" + dir;
410 dir += lastCharSet ? "" : "/";
411 } else { // windows
412 dir += lastCharSet ? "" : "\\";
415 return dir;
419 * Gets StarOffice temp directory without 'file:///' prefix.
420 * and System dependend file separator
422 public static String getOfficeTempDirSys(XMultiServiceFactory msf) {
424 String dir = getOfficeTemp(msf);
425 String sysDir = "";
427 int idx = dir.indexOf("file://");
429 // remove leading 'file://'
430 if (idx < 0) {
431 sysDir = dir;
432 } else {
433 sysDir = dir.substring("file://".length());
436 // append '/' if not there (e.g. linux)
437 if (sysDir.charAt(sysDir.length() - 1) != '/') {
438 sysDir += "/";
441 // remove leading '/' and replace others with '\' on windows machines
442 if (sysDir.indexOf(":") != -1) {
443 sysDir = sysDir.substring(1);
444 sysDir = sysDir.replace('/', '\\');
446 return sysDir;
450 * converts a fileURL to a system URL
451 * @param a file URL
452 * @return a system URL
454 public static String getSystemURL(String fileURL) {
455 String sysDir = "";
457 int idx = fileURL.indexOf("file://");
459 // remove leading 'file://'
460 if (idx < 0) {
461 sysDir = fileURL;
462 } else {
463 sysDir = fileURL.substring("file://".length());
466 // remove leading '/' and replace others with '\' on windows machines
467 if (sysDir.indexOf(":") != -1) {
468 sysDir = sysDir.substring(1);
469 sysDir = sysDir.replace('/', '\\');
471 return sysDir;
475 * This method check via Office the existance of the given file URL
476 * @param msf the multiservice factory
477 * @param fileURL the file which existance should be checked
478 * @return true if the file exists, else false
480 public static boolean fileExists(XMultiServiceFactory msf, String fileURL) {
481 boolean exists = false;
482 try {
484 Object fileacc = msf.createInstance("com.sun.star.comp.ucb.SimpleFileAccess");
485 XSimpleFileAccess simpleAccess = (XSimpleFileAccess) UnoRuntime.queryInterface(XSimpleFileAccess.class,
486 fileacc);
487 if (simpleAccess.exists(fileURL)) {
488 exists = true;
491 } catch (Exception e) {
492 System.out.println("Couldn't access file '" + fileURL + "'");
493 e.printStackTrace();
494 exists = false;
496 return exists;
500 * This method deletes via office the given file URL. It checks the existance
501 * of <CODE>fileURL</CODE>. If exists it will be deletet.
502 * @param msf the multiservice factory
503 * @param fileURL the file to delete
504 * @return true if the file could be deletet or the file does not exist
506 public static boolean deleteFile(XMultiServiceFactory xMsf, String fileURL) {
507 boolean delete = true;
508 try {
510 Object fileacc = xMsf.createInstance("com.sun.star.comp.ucb.SimpleFileAccess");
511 XSimpleFileAccess simpleAccess = (XSimpleFileAccess) UnoRuntime.queryInterface(XSimpleFileAccess.class,
512 fileacc);
513 if (simpleAccess.exists(fileURL)) {
514 simpleAccess.kill(fileURL);
517 } catch (Exception e) {
518 System.out.println("Couldn't delete file '" + fileURL + "'");
519 e.printStackTrace();
520 delete = false;
522 return delete;
526 * This method copies via office a given file to a new one
527 * @param msf the multi service factory
528 * @param oldF the source file
529 * @param newF the destination file
530 * @return true at success
532 public static boolean copyFile(XMultiServiceFactory xMsf, String source, String destinaion) {
533 boolean res = false;
534 try {
535 Object fileacc = xMsf.createInstance("com.sun.star.comp.ucb.SimpleFileAccess");
536 XSimpleFileAccess simpleAccess = (XSimpleFileAccess) UnoRuntime.queryInterface(XSimpleFileAccess.class,
537 fileacc);
538 if (!simpleAccess.exists(destinaion)) {
539 simpleAccess.copy(source, destinaion);
542 res = true;
543 } catch (Exception e) {
544 System.out.println("Couldn't copy file '" + source + "' -> '" + destinaion + "'");
545 e.printStackTrace();
546 res = false;
548 return res;
552 * Copies file to a new location using SOffice features. If the target
553 * file already exists, the file is deleted.
555 * @returns <code>true</code> if the file was successfully copied,
556 * <code>false</code> if some errors occured (e.g. file is locked, used
557 * by another process).
559 public static boolean overwriteFile(XMultiServiceFactory xMsf, String oldF, String newF) {
560 boolean res = false;
561 try {
562 Object fileacc = xMsf.createInstance("com.sun.star.comp.ucb.SimpleFileAccess");
564 XSimpleFileAccess simpleAccess = (XSimpleFileAccess) UnoRuntime.queryInterface(XSimpleFileAccess.class,
565 fileacc);
566 if (simpleAccess.exists(newF)) {
567 simpleAccess.kill(newF);
569 simpleAccess.copy(oldF, newF);
570 res = true;
571 } catch (com.sun.star.ucb.InteractiveAugmentedIOException e) {
572 return false;
573 } catch (com.sun.star.uno.Exception e) {
574 System.out.println("Couldn't create a service.");
575 e.printStackTrace();
578 return res;
581 public static boolean hasPropertyByName(XPropertySet props, String aName) {
582 Property[] list = props.getPropertySetInfo().getProperties();
583 boolean res = false;
584 for (int i = 0; i < list.length; i++) {
585 String the_name = list[i].Name;
586 if (aName.equals(the_name)) {
587 res = true;
590 return res;
595 * This method returns the implementation name of a given object
598 public static String getImplName(Object aObject) {
599 String res = "Error getting Implementation name";
600 try {
601 XServiceInfo xSI = (XServiceInfo) UnoRuntime.queryInterface(XServiceInfo.class, aObject);
602 res = xSI.getImplementationName();
603 } catch (Exception e) {
604 res = "Error getting Implementation name ( " + e + " )";
607 return res;
612 * This method checks if an Object is void
615 public static boolean isVoid(Object aObject) {
616 if (aObject instanceof com.sun.star.uno.Any) {
617 com.sun.star.uno.Any oAny = (com.sun.star.uno.Any) aObject;
618 return (oAny.getType().getTypeName().equals("void"));
619 } else {
620 return false;
627 * This method replaces a substring with another
630 public static String replacePart(String all, String toReplace, String replacement) {
631 return replaceAll13(all, toReplace, replacement);
635 * Scan localhost for the next free port-number from a starting port
636 * on. If the starting port is smaller than 1024, port number starts with
637 * 10000 as default, because numbers < 1024 are never free on unix machines.
638 * @param startPort The port where scanning starts.
639 * @return The next free port.
641 public static int getNextFreePort(int startPort) {
642 if (startPort < 1024) {
643 startPort = 10000;
645 for (int port = startPort; port < 65536; port++) {
646 System.out.println("Scan port " + port);
647 try {
648 // first trying to establish a server-socket on localhost
649 // fails if there is already a server running
650 ServerSocket sSock = new ServerSocket(port);
651 sSock.close();
652 } catch (IOException e) {
653 System.out.println(" -> server: occupied port " + port);
654 continue;
656 try {
657 // now trying to establish a client-socket
658 // fails if there is no server on any connectable machine
659 Socket sock = new Socket("localhost", port);
660 System.out.println(" -> socket: occupied port: " + port);
661 } catch (IOException e) {
662 System.out.println(" -> free port");
663 return port;
666 return 65535;
669 public static URL parseURL(XMultiServiceFactory xMSF, String url) {
670 URL[] rUrl = new URL[1];
671 rUrl[0] = new URL();
672 rUrl[0].Complete = url;
674 XURLTransformer xTrans = null;
675 try {
676 Object inst = xMSF.createInstance("com.sun.star.util.URLTransformer");
677 xTrans = (XURLTransformer) UnoRuntime.queryInterface(XURLTransformer.class, inst);
678 } catch (com.sun.star.uno.Exception e) {
681 xTrans.parseStrict(rUrl);
683 return rUrl[0];
686 public static String getOfficeURL(XMultiServiceFactory msf) {
687 try {
688 Object settings = msf.createInstance("com.sun.star.util.PathSettings");
689 XPropertySet settingProps = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, settings);
690 String path = (String) settingProps.getPropertyValue("Module");
691 return path;
692 } catch (Exception e) {
693 System.out.println("Couldn't get Office Settings ");
694 e.printStackTrace();
696 return null;
699 /** returns the path to the office binary folder
701 * @param msf The XMultiSeriveFactory
702 * @return the path to the office binrary or an empty string on any error
704 public static String getOfficeBinPath(XMultiServiceFactory msf) {
705 String sysBinDir = "";
706 try {
707 sysBinDir = utils.getSystemURL(utils.expandMacro(msf, "$SYSBINDIR"));
708 } catch (java.lang.Exception e) {
711 return sysBinDir;
715 * Get an array of all property names from the property set. With the include
716 * and exclude parameters the properties can be filtered. <br>
717 * Set excludePropertyAttribute = 0 and includePropertyAttribute = 0
718 * to include all and exclude none.
719 * @param props The instance of XPropertySet
720 * @param includePropertyAttribute Properties without these attributes are filtered and will not be returned.
721 * @param excludePropertyAttribute Properties with these attributes are filtered and will not be returned.
722 * @return A String array with all property names.
723 * @see com.sun.star.beans.XPropertySet
724 * @see com.sun.star.beans.Property
725 * @see com.sun.star.beans.PropertyAttribute
727 public static String[] getFilteredPropertyNames(XPropertySet props, short includePropertyAttribute,
728 short excludePropertyAttribute) {
729 Property[] the_props = props.getPropertySetInfo().getProperties();
730 ArrayList l = new ArrayList();
731 for (int i = 0; i < the_props.length; i++) {
732 boolean exclude = ((the_props[i].Attributes & excludePropertyAttribute) != 0);
733 boolean include = (includePropertyAttribute == 0) ||
734 ((the_props[i].Attributes & includePropertyAttribute) != 0);
735 if (include && !exclude) {
736 l.add(the_props[i].Name);
739 Collections.sort(l);
740 String[] names = new String[l.size()];
741 names = (String[]) l.toArray(names);
742 return names;
745 /** Causes the thread to sleep some time.
746 * It can be used f.e. like:
747 * util.utils.shortWait(tParam.getInt("ShortWait"));
749 public static void shortWait(int milliseconds) {
750 try {
751 Thread.currentThread().sleep(milliseconds);
752 } catch (InterruptedException e) {
753 System.out.println("While waiting :" + e);
758 * Validate the AppExecutionCommand. Returned is an error message, starting
759 * with "Error:", or a warning, if the command might work.
760 * @param appExecCommand The application execution command that is checked.
761 * @param os The operating system where the check runs.
762 * @return The error message, or OK, if no error was detected.
764 public static String validateAppExecutionCommand(String appExecCommand, String os) {
765 String errorMessage = "OK";
766 appExecCommand = replaceAll13(appExecCommand, "\"", "");
767 appExecCommand = replaceAll13(appExecCommand, "'", "");
768 StringTokenizer commandTokens = new StringTokenizer(appExecCommand, " \t");
769 String officeExecutable = "";
770 String officeExecCommand = "soffice";
771 // is there a 'soffice' in the command? 2do: eliminate case sensitivity on windows
772 int index = -1;
773 while (commandTokens.hasMoreTokens() && index == -1) {
774 officeExecutable += commandTokens.nextToken() + " ";
775 index = officeExecutable.indexOf(officeExecCommand);
777 if (index == -1) {
778 errorMessage = "Error: Your 'AppExecutionCommand' parameter does not " +
779 "contain '" + officeExecCommand + "'.";
780 } else {
781 // does the directory exist?
782 officeExecutable = officeExecutable.trim();
783 String officePath = officeExecutable.substring(0, index);
784 File f = new File(officePath);
785 if (!f.exists() || !f.isDirectory()) {
786 errorMessage = "Error: Your 'AppExecutionCommand' parameter does not " +
787 "point to a valid system directory: " + officePath;
788 } else {
789 // is it an office installation?
790 f = new File(officeExecutable);
791 // one try for windows platform can't be wrong...
792 if (!f.exists() || !f.isFile()) {
793 f = new File(officeExecutable + ".exe");
795 if (!f.exists() || !f.isFile()) {
796 errorMessage = "Error: Your 'AppExecutionCommand' parameter does not " +
797 "point to a valid office installation.";
798 } else {
799 // do we have the accept parameter?
800 boolean gotNoAccept = true;
801 while (commandTokens.hasMoreElements()) {
802 String officeParam = commandTokens.nextToken();
803 if (officeParam.indexOf("-accept=") != -1) {
804 gotNoAccept = false;
805 errorMessage = validateConnectString(officeParam, true);
808 if (gotNoAccept) {
809 errorMessage = "Error: Your 'AppExecutionCommand' parameter does not " +
810 "contain a '-accept' parameter for connecting the office.";
815 return errorMessage;
819 * Validate the connection string. Returned is an error message, starting
820 * with "Error:", or a warning, if the command might work.
821 * @param connectString The connection string that is checked.
822 * @param checkAppExecutionCommand If the AppExecutionCommand is checked, the error messages willbe different.
823 * @return The error message, or OK, if no error was detected.
825 public static String validateConnectString(String connectString, boolean checkAppExecutionCommand) {
826 String acceptPrefix = "";
827 if (checkAppExecutionCommand) {
828 acceptPrefix = "-accept=";
831 String errorMessage = "OK";
832 // a warning, if an unknown connection method is used
833 if (connectString.indexOf("socket") != -1) {
834 if (connectString.indexOf(acceptPrefix + "socket,host=") == -1 ||
835 connectString.indexOf("port=") == -1) {
836 if (checkAppExecutionCommand) {
837 errorMessage = "Error: The '-accept' parameter contains a syntax error: It should be like: '-accept=socket,host=localhost,port=8100;urp;";
838 } else {
839 errorMessage = "Error: The 'ConnectionString' parameter contains a syntax error: It should be like: 'socket,host=localhost,port=8100'";
842 } else if (connectString.indexOf("pipe") != -1) {
843 if (connectString.indexOf(acceptPrefix + "pipe,name=") == -1) {
844 if (checkAppExecutionCommand) {
845 errorMessage = "Error: The '-accept' parameter contains a syntax error: It should be like: '-accept=pipe,name=myuniquename;urp;'";
846 } else {
847 errorMessage = "Error: The 'ConnectionString' parameter contains a syntax error: It should be like: 'pipe,name=myuniquename'";
850 } else {
851 if (checkAppExecutionCommand) {
852 errorMessage = "Warning: The '-accept' parameter contains an unknown connection method.";
853 } else {
854 errorMessage = "Warning: The 'ConnectionString' parameter contains an unknown connection method.";
857 return errorMessage;
861 * String.replaceAll() ist available since Java 1.4 but the runner must be buldabale with Java 1.3
862 * @param originalString
863 * @param searchString
864 * @param replaceString
865 * @return modified string
867 public static String replaceAll13(String originalString, String searchString, String replaceString) {
869 StringBuffer changeStringBuffer = new StringBuffer(originalString);
870 int searchLength = searchString.length();
871 int replaceLength = replaceString.length();
872 int index = originalString.indexOf(searchString);
873 while (index != -1) {
874 changeStringBuffer = changeStringBuffer.replace(index, index + searchLength, replaceString);
875 originalString = changeStringBuffer.toString();
876 index = originalString.indexOf(searchString, index + replaceLength);
878 return originalString;
882 * expand macrofied strings like <CODE>${$ORIGIN/bootstrap.ini:UserInstallation}</CODE> or
883 * <CODE>$_OS</CODE>
884 * @param xMSF the MultiServiceFactory
885 * @param expand the string to expand
886 * @throws java.lang.Exception was thrown on any exception
887 * @return return the expanded string
888 * @see com.sun.star.util.theMacroExpander
890 public static String expandMacro(XMultiServiceFactory xMSF, String expand) throws java.lang.Exception {
891 try {
892 XPropertySet xPS = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, xMSF);
893 XComponentContext xContext = (XComponentContext) UnoRuntime.queryInterface(XComponentContext.class,
894 xPS.getPropertyValue("DefaultContext"));
895 XMacroExpander xME = (XMacroExpander) UnoRuntime.queryInterface(XMacroExpander.class,
896 xContext.getValueByName("/singletons/com.sun.star.util.theMacroExpander"));
897 return xME.expandMacros(expand);
898 } catch (Exception e) {
899 throw new Exception("could not expand macro: " + e.toString(), e);
905 * returns the platform of the office.<br>
906 * Since the runner and the office could run on different platform this function delivers the
907 * platform the office is running.
908 * @param xMSF the XMultiServiceFactory
909 * @return unxsols, unxsoli, unxlngi, wntmsci
911 public static String getOfficeOS(XMultiServiceFactory xMSF) {
912 String platform = "unkown";
914 try {
915 String theOS = expandMacro(xMSF, "$_OS");
917 if (theOS.equals("Windows")) {
918 platform = "wntmsci";
919 } else if (theOS.equals("Linux")) {
920 platform = "unxlngi";
921 } else {
922 if (theOS.equals("Solaris")) {
923 String theArch = expandMacro(xMSF, "$_ARCH");
924 if (theArch.equals("SPARC")) {
925 platform = "unxsols";
926 } else if (theArch.equals("x86")) {
927 platform = "unxsoli";
931 } catch (Exception ex) {
933 return platform;
937 * dispatches given <CODE>URL</CODE> to the document <CODE>XComponent</CODE>
938 * @param xMSF the <CODE>XMultiServiceFactory</CODE>
939 * @param xDoc the document where to dispatch
940 * @param URL the <CODE>URL</CODE> to dispatch
941 * @throws java.lang.Exception throws <CODE>java.lang.Exception</CODE> on any error
943 public static void dispatchURL(XMultiServiceFactory xMSF, XComponent xDoc, String URL) throws java.lang.Exception {
944 XModel aModel = (XModel) UnoRuntime.queryInterface(XModel.class, xDoc);
946 XController xCont = aModel.getCurrentController();
948 dispatchURL(xMSF, xCont, URL);
953 * dispatches given <CODE>URL</CODE> to the <CODE>XController</CODE>
954 * @param xMSF the <CODE>XMultiServiceFactory</CODE>
955 * @param xComp the <CODE>XController</CODE> to query for a XDispatchProvider
956 * @param URL the <CODE>URL</CODE> to dispatch
957 * @throws java.lang.Exception throws <CODE>java.lang.Exception</CODE> on any error
959 public static void dispatchURL(XMultiServiceFactory xMSF, XController xCont, String URL) throws java.lang.Exception {
960 try {
962 XDispatchProvider xDispProv = (XDispatchProvider) UnoRuntime.queryInterface(XDispatchProvider.class, xCont);
964 XURLTransformer xParser = (com.sun.star.util.XURLTransformer) UnoRuntime.queryInterface(
965 XURLTransformer.class,
966 xMSF.createInstance("com.sun.star.util.URLTransformer"));
968 // Because it's an in/out parameter we must use an array of URL objects.
969 URL[] aParseURL = new URL[1];
970 aParseURL[0] = new URL();
971 aParseURL[0].Complete = URL;
972 xParser.parseStrict(aParseURL);
974 URL aURL = aParseURL[0];
976 XDispatch xDispatcher = xDispProv.queryDispatch(aURL, "", 0);
977 xDispatcher.dispatch(aURL, null);
979 utils.shortWait(3000);
981 } catch (Exception e) {
982 throw new Exception("ERROR: could not dispatch URL '" + URL + "': " + e.toString());
986 /** returns a String which contains the current date and time<br>
987 * format: [DD.MM.YYYY - HH:MM:SS::mm]
989 ** @return a String which contains the current date and time
991 public static String getDateTime() {
993 Calendar cal = new GregorianCalendar();
994 DecimalFormat dfmt = new DecimalFormat("00");
995 String dateTime = dfmt.format(cal.get(Calendar.DAY_OF_MONTH)) + "." +
996 dfmt.format(cal.get(Calendar.MONTH) + 1) + "." +
997 dfmt.format(cal.get(Calendar.YEAR)) + " - " +
998 dfmt.format(cal.get(Calendar.HOUR_OF_DAY)) + ":" +
999 dfmt.format(cal.get(Calendar.MINUTE)) + ":" +
1000 dfmt.format(cal.get(Calendar.SECOND)) + "," +
1001 dfmt.format(cal.get(Calendar.MILLISECOND));
1002 return "[" + dateTime + "]";