bump product version to 4.1.6.2
[LibreOffice.git] / qadevOOo / runner / util / utils.java
blobc91b42bc068ed6eb39623d8ca7baceffc806c4d6
1 /*
2 * This file is part of the LibreOffice project.
4 * This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 * This file incorporates work covered by the following license notice:
10 * Licensed to the Apache Software Foundation (ASF) under one or more
11 * contributor license agreements. See the NOTICE file distributed
12 * with this work for additional information regarding copyright
13 * ownership. The ASF licenses this file to you under the Apache
14 * License, Version 2.0 (the "License"); you may not use this file
15 * except in compliance with the License. You may obtain a copy of
16 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
18 package util;
20 import com.sun.star.frame.XController;
21 import com.sun.star.frame.XDispatch;
22 import com.sun.star.frame.XDispatchProvider;
23 import com.sun.star.frame.XModel;
24 import com.sun.star.lang.XComponent;
25 import java.lang.System;
26 import java.util.StringTokenizer;
27 import java.io.*;
28 import java.util.ArrayList;
29 import java.io.RandomAccessFile;
30 import java.net.Socket;
31 import java.net.ServerSocket;
32 import java.net.URI;
33 import java.net.URISyntaxException;
35 import com.sun.star.beans.XPropertySet;
36 import com.sun.star.beans.Property;
37 import com.sun.star.lang.XMultiServiceFactory;
38 import com.sun.star.uno.UnoRuntime;
39 import com.sun.star.ucb.InteractiveAugmentedIOException;
40 import com.sun.star.ucb.XSimpleFileAccess;
41 import com.sun.star.lang.XServiceInfo;
43 import com.sun.star.util.URL;
44 import com.sun.star.util.XURLTransformer;
46 import com.sun.star.uno.AnyConverter;
47 import com.sun.star.uno.Type;
48 import com.sun.star.uno.XComponentContext;
49 import com.sun.star.util.XMacroExpander;
50 import java.text.DecimalFormat;
51 import java.util.Calendar;
53 import java.util.Collections;
54 import java.util.GregorianCalendar;
56 public class utils {
58 /**
60 * This method adds the DOCPTH to a given file
62 * @param sDocName the file which should be completed to the test doc path
63 * @return $TESTDOCPATH/sDocName
65 public static String getFullTestDocName(String sDocName) {
66 String docpth = System.getProperty("DOCPTH");
67 if (docpth.endsWith("\\") || docpth.endsWith("/")) {
68 docpth = docpth.substring(0, docpth.length() - 1);
71 System.out.println("docpth:" + docpth);
73 String pthSep = System.getProperty("file.separator");
75 if (docpth.equals("unknown")) {
76 System.out.println("try to get tDoc from $SRC_ROOT/qadevOOo");
77 String srcRoot = System.getProperty(PropertyName.SRC_ROOT);
78 if (srcRoot != null) {
79 File srcR = new File(srcRoot);
80 String[] list = srcR.list(new FilenameFilter() {
82 public boolean accept(File dir, String name) {
83 return name.startsWith("qadevOOo");
85 });
87 if (list[0] != null) {
88 String tDoc = srcRoot.concat(pthSep).concat(list[0]).concat(pthSep).concat("testdocs");
90 if (new File(tDoc).exists()) {
91 docpth = tDoc;
97 if (docpth.startsWith("http:")) {
98 return docpth + "/" + sDocName;
100 String testdocPth = "";
102 if (docpth.equals("unknown")) {
103 System.out.println("try to get tDoc from OBJDSCS");
104 String objdscPth = System.getProperty("OBJDSCS");
105 if (objdscPth != null) {
106 int i = objdscPth.indexOf("objdsc");
107 String arcPth = objdscPth.substring(0, i - 1);
108 testdocPth = arcPth + pthSep + "doc" + pthSep + "java" +
109 pthSep + "testdocs" + pthSep + sDocName;
111 } else {
112 testdocPth = docpth + pthSep + sDocName;
114 return testdocPth;
119 * This method adds the DOCPTH to a given file
120 * and changes the format to an file URL
123 public static String getFullTestURL(String sDocName) {
124 String fullDocPath = getFullTestDocName(sDocName);
125 if (fullDocPath.startsWith("http:")) {
126 return fullDocPath;
128 if (fullDocPath.startsWith("file:")) {
129 return fullDocPath;
131 String prefix = null;
133 // Windows: \\\\margritte\\qaapi\\workspace\\qadev\\testdocs/emptyChart.sds
134 if (fullDocPath.startsWith("\\\\")) {
135 prefix = "file:";
138 fullDocPath = fullDocPath.replace('\\', '/');
139 if (prefix == null) {
140 if (fullDocPath.startsWith("//")) {
141 prefix = "file:/";
142 } else if (fullDocPath.startsWith("/")) {
143 prefix = "file://";
144 } else {
145 prefix = "file:///";
148 if (!fullDocPath.endsWith("/")) {
149 File aFile = new File(fullDocPath);
150 if (aFile.isDirectory()) {
151 fullDocPath += "/";
154 String fulldocURL = prefix + fullDocPath;
155 return fulldocURL;
160 * This method changes a given URL to a valid file URL
163 public static String getFullURL(String sDocName) {
164 String fullDocPath = sDocName;
165 fullDocPath = fullDocPath.replace('\\', '/');
167 if (fullDocPath.startsWith("http:")) {
168 return fullDocPath;
170 if (fullDocPath.startsWith("ftp:")) {
171 return fullDocPath;
173 String prefix = "";
174 if (!fullDocPath.startsWith("file:///")) {
175 if (fullDocPath.startsWith("//")) {
176 prefix = "file:";
177 } else {
178 if (fullDocPath.startsWith("/")) {
179 prefix = "file://";
180 // if (helper.OSHelper.isLinuxIntel())
181 // {
182 // prefix = "file:/";
183 // }
185 else
187 prefix = "file:///";
191 if (!fullDocPath.endsWith("/")) {
192 File aFile = new File(fullDocPath);
193 if (aFile.isDirectory()) {
194 fullDocPath += "/";
197 String fulldocURL = prefix + fullDocPath;
199 return fulldocURL;
204 * This method creates folders needed
207 public static void make_Directories(String first, String path) {
208 String already_done = null;
209 String fs = System.getProperty("file.separator");
210 StringTokenizer path_tokenizer = new StringTokenizer(path, fs, false);
211 already_done = first;
212 while (path_tokenizer.hasMoreTokens()) {
213 String part = path_tokenizer.nextToken();
214 File new_dir = new File(already_done + File.separatorChar + part);
215 already_done = new_dir.toString();
216 //create the directory
217 new_dir.mkdirs();
219 return;
224 * This method get the version for a given TestBase/platform combination
227 public static String getVersion(String aFile, String aPlatform, String aTestbase) {
228 if ((aFile == null) || (aPlatform == null) || (aTestbase == null)) {
229 return "/";
232 File the_file = new File(aFile);
233 try {
234 RandomAccessFile raf = new RandomAccessFile(the_file, "r");
235 String res = "";
236 while (!res.equals("[" + aTestbase.toUpperCase() + "]")) {
237 res = raf.readLine();
239 res = "=/";
240 while ((!res.startsWith(aPlatform)) || (res.startsWith("["))) {
241 res = raf.readLine();
243 raf.close();
244 if (res.startsWith("[")) {
245 res = "/";
247 return res.substring(res.indexOf("=") + 1);
249 } catch (Exception e) {
250 System.out.println("Couldn't find version");
251 return "/";
257 * This method get's the user dir of the connected office
260 public static String getOfficeUserPath(XMultiServiceFactory msf) {
261 String userPath = null;
263 // get a folder located in the user dir
264 try {
265 userPath = getOfficeSettingsValue(msf, "UserConfig");
266 } catch (Exception e) {
267 System.out.println("Couldn't get Office User Path");
268 e.printStackTrace();
271 // strip the returned folder to the user dir
272 if (userPath.charAt(userPath.length() - 1) == '/') {
273 userPath = userPath.substring(0, userPath.length() - 1);
275 int index = userPath.lastIndexOf('/');
276 if (index != -1) {
277 userPath = userPath.substring(0, index);
280 return userPath;
284 * In the office there are some sttetings available. This function
285 * returns the value of the given setting name. For Example the setting name "Temp"
286 * "Temp" returns the temp folder of the office instance.
287 * @param msf a XMultiServiceFactory
288 * @param setting the name of the setting the value should be returned.
289 * For example "Temp" reutrns the temp folder of the current office instance.
290 * @see com.sun.star.util.PathSettings
291 * @return the value as String
293 public static String getOfficeSettingsValue(XMultiServiceFactory msf, String setting) {
295 String settingPath = null;
296 try {
297 Object settings = msf.createInstance("com.sun.star.comp.framework.PathSettings");
298 XPropertySet pthSettings = null;
299 try {
300 pthSettings = (XPropertySet) AnyConverter.toObject(
301 new Type(XPropertySet.class), settings);
302 } catch (com.sun.star.lang.IllegalArgumentException iae) {
303 System.out.println("### couldn't get Office Settings");
305 settingPath = (String) pthSettings.getPropertyValue(setting);
307 } catch (Exception e) {
308 System.out.println("Couldn't get stting value for " + setting);
309 e.printStackTrace();
311 return settingPath;
314 public static void setOfficeSettingsValue(XMultiServiceFactory msf, String setting, String value) {
316 try {
317 Object settings = msf.createInstance("com.sun.star.comp.framework.PathSettings");
318 XPropertySet pthSettings = null;
319 try {
320 pthSettings = (XPropertySet) AnyConverter.toObject(
321 new Type(XPropertySet.class), settings);
322 } catch (com.sun.star.lang.IllegalArgumentException iae) {
323 System.out.println("### couldn't get Office Settings");
325 pthSettings.setPropertyValue(setting, value);
327 } catch (Exception e) {
328 System.out.println("Couldn't set '" + setting + "' to value '" + value + "'");
329 e.printStackTrace();
334 * This method returns the temp dicrectory of the user.
335 * Since Java 1.4 it is not possible to read environment variables. To workaround
336 * this, the Java parameter -D could be used.
338 public static String getUsersTempDir() {
339 String tempDir = System.getProperty("my.temp");
340 if (tempDir == null) {
341 tempDir = System.getProperty("my.tmp");
342 if (tempDir == null) {
343 tempDir = System.getProperty("java.io.tmpdir");
346 // remove ending file separator
347 if (tempDir.endsWith(System.getProperty("file.separator"))) {
348 tempDir = tempDir.substring(0, tempDir.length() - 1);
351 return tempDir;
356 * This method get's the temp dir of the connected office
359 public static String getOfficeTemp(XMultiServiceFactory msf) {
360 String url = getOfficeUserPath(msf) + "/test-temp/";
361 try {
362 new File(new URI(url)).mkdir();
363 } catch (URISyntaxException e) {
364 throw new RuntimeException(e);
366 return url;
370 * Gets StarOffice temp directory without 'file:///' prefix.
371 * For example is useful for Registry URL specifying.
372 * @msf Office factory for accessing its settings.
373 * @return SOffice temporary directory in form for example
374 * 'd:/Office60/user/temp/'.
376 public static String getOfficeTempDir(XMultiServiceFactory msf) {
378 String dir = getOfficeTemp(msf);
380 int idx = dir.indexOf("file:///");
382 if (idx < 0) {
383 return dir;
386 dir = dir.substring("file:///".length());
388 idx = dir.indexOf(":");
390 // is the last character a '/' or a '\'?
391 boolean lastCharSet = dir.endsWith("/") || dir.endsWith("\\");
393 if (idx < 0) { // linux or solaris
394 dir = "/" + dir;
395 dir += lastCharSet ? "" : "/";
396 } else { // windows
397 dir += lastCharSet ? "" : "\\";
400 return dir;
404 * Gets StarOffice temp directory without 'file:///' prefix.
405 * and System dependend file separator
407 public static String getOfficeTempDirSys(XMultiServiceFactory msf) {
409 String dir = getOfficeTemp(msf);
410 String sysDir = "";
412 int idx = dir.indexOf("file://");
414 // remove leading 'file://'
415 if (idx < 0) {
416 sysDir = dir;
417 } else {
418 sysDir = dir.substring("file://".length());
421 // append '/' if not there (e.g. linux)
422 if (sysDir.charAt(sysDir.length() - 1) != '/') {
423 sysDir += "/";
426 // remove leading '/' and replace others with '\' on windows machines
427 if (sysDir.indexOf(":") != -1) {
428 sysDir = sysDir.substring(1);
429 sysDir = sysDir.replace('/', '\\');
431 return sysDir;
435 * converts a fileURL to a system URL
436 * @param fileURL a file URL
437 * @return a system URL
439 public static String getSystemURL(String fileURL) {
440 String sysDir = "";
442 int idx = fileURL.indexOf("file://");
444 // remove leading 'file://'
445 if (idx < 0) {
446 sysDir = fileURL;
447 } else {
448 sysDir = fileURL.substring("file://".length());
451 // remove leading '/' and replace others with '\' on windows machines
452 if (sysDir.indexOf(":") != -1) {
453 sysDir = sysDir.substring(1);
454 sysDir = sysDir.replace('/', '\\');
456 return sysDir;
460 * This method check via Office the existance of the given file URL
461 * @param msf the multiservice factory
462 * @param fileURL the file which existance should be checked
463 * @return true if the file exists, else false
465 public static boolean fileExists(XMultiServiceFactory msf, String fileURL) {
466 boolean exists = false;
467 try {
469 Object fileacc = msf.createInstance("com.sun.star.comp.ucb.SimpleFileAccess");
470 XSimpleFileAccess simpleAccess = UnoRuntime.queryInterface(XSimpleFileAccess.class,
471 fileacc);
472 if (simpleAccess.exists(fileURL)) {
473 exists = true;
476 } catch (Exception e) {
477 System.out.println("Couldn't access file '" + fileURL + "'");
478 e.printStackTrace();
479 exists = false;
481 return exists;
485 * This method deletes via office the given file URL. It checks the existance
486 * of <CODE>fileURL</CODE>. If exists it will be deletet.
487 * @param xMsf the multiservice factory
488 * @param fileURL the file to delete
489 * @return true if the file could be deletet or the file does not exist
491 public static boolean deleteFile(XMultiServiceFactory xMsf, String fileURL) {
492 boolean delete = true;
493 try {
495 Object fileacc = xMsf.createInstance("com.sun.star.comp.ucb.SimpleFileAccess");
496 XSimpleFileAccess simpleAccess = UnoRuntime.queryInterface(XSimpleFileAccess.class,
497 fileacc);
498 if (simpleAccess.exists(fileURL)) {
499 simpleAccess.kill(fileURL);
502 } catch (Exception e) {
503 System.out.println("Couldn't delete file '" + fileURL + "'");
504 e.printStackTrace();
505 delete = false;
507 return delete;
511 * This method copies via office a given file to a new one
512 * @param xMsf the multi service factory
513 * @param source the source file
514 * @param destinaion the destination file
515 * @return true at success
517 public static boolean copyFile(XMultiServiceFactory xMsf, String source, String destinaion) {
518 boolean res = false;
519 try {
520 Object fileacc = xMsf.createInstance("com.sun.star.comp.ucb.SimpleFileAccess");
521 XSimpleFileAccess simpleAccess = UnoRuntime.queryInterface(XSimpleFileAccess.class,
522 fileacc);
523 if (!simpleAccess.exists(destinaion)) {
524 simpleAccess.copy(source, destinaion);
527 res = true;
528 } catch (Exception e) {
529 System.out.println("Couldn't copy file '" + source + "' -> '" + destinaion + "'");
530 e.printStackTrace();
531 res = false;
533 return res;
536 private static void overwriteFile_impl(
537 XMultiServiceFactory xMsf, String oldF, String newF)
538 throws InteractiveAugmentedIOException
540 try {
541 Object fileacc = xMsf.createInstance("com.sun.star.comp.ucb.SimpleFileAccess");
543 XSimpleFileAccess simpleAccess = UnoRuntime.queryInterface(XSimpleFileAccess.class,
544 fileacc);
545 if (simpleAccess.exists(newF)) {
546 simpleAccess.kill(newF);
548 simpleAccess.copy(oldF, newF);
549 } catch (InteractiveAugmentedIOException e) {
550 throw e;
551 } catch (com.sun.star.uno.Exception e) {
552 System.out.println("Couldn't copy " + oldF + " to " + newF + ":");
553 e.printStackTrace();
554 throw new RuntimeException(e);
559 * Copies file to a new location using OpenOffice.org features. If the target
560 * file already exists, the file is deleted.
562 * @returns <code>true</code> if the file was successfully copied,
563 * <code>false</code> if some errors occurred (e.g. file is locked, used
564 * by another process).
566 public static boolean tryOverwriteFile(
567 XMultiServiceFactory xMsf, String oldF, String newF)
569 try {
570 overwriteFile_impl(xMsf, oldF, newF);
571 } catch (InteractiveAugmentedIOException e) {
572 return false;
574 return true;
577 public static void doOverwriteFile(
578 XMultiServiceFactory xMsf, String oldF, String newF)
580 try {
581 overwriteFile_impl(xMsf, oldF, newF);
582 } catch (InteractiveAugmentedIOException e) {
583 throw new RuntimeException(e);
587 public static boolean hasPropertyByName(XPropertySet props, String aName) {
588 Property[] list = props.getPropertySetInfo().getProperties();
589 boolean res = false;
590 for (int i = 0; i < list.length; i++) {
591 String the_name = list[i].Name;
592 if (aName.equals(the_name)) {
593 res = true;
596 return res;
601 * This method returns the implementation name of a given object
604 public static String getImplName(Object aObject) {
605 String res = "Error getting Implementation name";
606 try {
607 XServiceInfo xSI = UnoRuntime.queryInterface(XServiceInfo.class, aObject);
608 res = xSI.getImplementationName();
609 } catch (Exception e) {
610 res = "Error getting Implementation name ( " + e + " )";
613 return res;
618 * This method checks if an Object is void
621 public static boolean isVoid(Object aObject) {
622 if (aObject instanceof com.sun.star.uno.Any) {
623 com.sun.star.uno.Any oAny = (com.sun.star.uno.Any) aObject;
624 return (oAny.getType().getTypeName().equals("void"));
625 } else {
626 return false;
633 * This method replaces a substring with another
636 public static String replacePart(String all, String toReplace, String replacement) {
637 return replaceAll13(all, toReplace, replacement);
641 * Scan localhost for the next free port-number from a starting port
642 * on. If the starting port is smaller than 1024, port number starts with
643 * 10000 as default, because numbers < 1024 are never free on unix machines.
644 * @param startPort The port where scanning starts.
645 * @return The next free port.
647 public static int getNextFreePort(int startPort) {
648 if (startPort < 1024) {
649 startPort = 10000;
651 for (int port = startPort; port < 65536; port++) {
652 System.out.println("Scan port " + port);
653 try {
654 // first trying to establish a server-socket on localhost
655 // fails if there is already a server running
656 ServerSocket sSock = new ServerSocket(port);
657 sSock.close();
658 } catch (IOException e) {
659 System.out.println(" -> server: occupied port " + port);
660 continue;
662 try {
663 new Socket("localhost", port);
664 System.out.println(" -> socket: occupied port: " + port);
665 } catch (IOException e) {
666 System.out.println(" -> free port");
667 return port;
670 return 65535;
673 public static URL parseURL(XMultiServiceFactory xMSF, String url) {
674 URL[] rUrl = new URL[1];
675 rUrl[0] = new URL();
676 rUrl[0].Complete = url;
678 XURLTransformer xTrans = null;
679 try {
680 Object inst = xMSF.createInstance("com.sun.star.util.URLTransformer");
681 xTrans = UnoRuntime.queryInterface(XURLTransformer.class, inst);
682 } catch (com.sun.star.uno.Exception e) {
685 xTrans.parseStrict(rUrl);
687 return rUrl[0];
690 public static String getOfficeURL(XMultiServiceFactory msf) {
691 try {
692 Object settings = msf.createInstance("com.sun.star.util.PathSettings");
693 XPropertySet settingProps = UnoRuntime.queryInterface(XPropertySet.class, settings);
694 String path = (String) settingProps.getPropertyValue("Module");
695 return path;
696 } catch (Exception e) {
697 System.out.println("Couldn't get Office Settings ");
698 e.printStackTrace();
700 return null;
703 /** returns the path to the office binary folder
705 * @param msf The XMultiSeriveFactory
706 * @return the path to the office binrary or an empty string on any error
708 public static String getOfficeBinPath(XMultiServiceFactory msf) {
709 String sysBinDir = "";
710 try {
711 sysBinDir = utils.getSystemURL(utils.expandMacro(msf, "$SYSBINDIR"));
712 } catch (java.lang.Exception e) {
715 return sysBinDir;
719 * Get an array of all property names from the property set. With the include
720 * and exclude parameters the properties can be filtered. <br>
721 * Set excludePropertyAttribute = 0 and includePropertyAttribute = 0
722 * to include all and exclude none.
723 * @param props The instance of XPropertySet
724 * @param includePropertyAttribute Properties without these attributes are filtered and will not be returned.
725 * @param excludePropertyAttribute Properties with these attributes are filtered and will not be returned.
726 * @return A String array with all property names.
727 * @see com.sun.star.beans.XPropertySet
728 * @see com.sun.star.beans.Property
729 * @see com.sun.star.beans.PropertyAttribute
731 public static String[] getFilteredPropertyNames(XPropertySet props, short includePropertyAttribute,
732 short excludePropertyAttribute) {
733 Property[] the_props = props.getPropertySetInfo().getProperties();
734 ArrayList<String> l = new ArrayList<String>();
735 for (int i = 0; i < the_props.length; i++) {
736 boolean exclude = ((the_props[i].Attributes & excludePropertyAttribute) != 0);
737 boolean include = (includePropertyAttribute == 0) ||
738 ((the_props[i].Attributes & includePropertyAttribute) != 0);
739 if (include && !exclude) {
740 l.add(the_props[i].Name);
743 Collections.sort(l);
744 String[] names = new String[l.size()];
745 names = l.toArray(names);
746 return names;
749 /** Causes the thread to sleep some time.
750 * It can be used f.e. like:
751 * util.utils.shortWait(tParam.getInt("ShortWait"));
753 public static void shortWait(int milliseconds) {
754 try {
755 Thread.sleep(milliseconds);
756 } catch (InterruptedException e) {
757 System.out.println("While waiting :" + e);
762 * Validate the AppExecutionCommand. Returned is an error message, starting
763 * with "Error:", or a warning, if the command might work.
764 * @param appExecCommand The application execution command that is checked.
765 * @param os The operating system where the check runs.
766 * @return The error message, or OK, if no error was detected.
768 public static String validateAppExecutionCommand(String appExecCommand, String os) {
769 String errorMessage = "OK";
770 appExecCommand = replaceAll13(appExecCommand, "\"", "");
771 appExecCommand = replaceAll13(appExecCommand, "'", "");
772 StringTokenizer commandTokens = new StringTokenizer(appExecCommand, " \t");
773 String officeExecutable = "";
774 String officeExecCommand = "soffice";
775 // is there a 'soffice' in the command? 2do: eliminate case sensitivity on windows
776 int index = -1;
777 while (commandTokens.hasMoreTokens() && index == -1) {
778 officeExecutable += commandTokens.nextToken() + " ";
779 index = officeExecutable.indexOf(officeExecCommand);
781 if (index == -1) {
782 errorMessage = "Error: Your 'AppExecutionCommand' parameter does not " +
783 "contain '" + officeExecCommand + "'.";
784 } else {
785 // does the directory exist?
786 officeExecutable = officeExecutable.trim();
787 String officePath = officeExecutable.substring(0, index);
788 File f = new File(officePath);
789 if (!f.exists() || !f.isDirectory()) {
790 errorMessage = "Error: Your 'AppExecutionCommand' parameter does not " +
791 "point to a valid system directory: " + officePath;
792 } else {
793 // is it an office installation?
794 f = new File(officeExecutable);
795 // one try for windows platform can't be wrong...
796 if (!f.exists() || !f.isFile()) {
797 f = new File(officeExecutable + ".exe");
799 if (!f.exists() || !f.isFile()) {
800 errorMessage = "Error: Your 'AppExecutionCommand' parameter does not " +
801 "point to a valid office installation.";
802 } else {
803 // do we have the accept parameter?
804 boolean gotNoAccept = true;
805 while (commandTokens.hasMoreElements()) {
806 String officeParam = commandTokens.nextToken();
807 if (officeParam.indexOf("--accept=") != -1) {
808 gotNoAccept = false;
809 errorMessage = validateConnectString(officeParam, true);
812 if (gotNoAccept) {
813 errorMessage = "Error: Your 'AppExecutionCommand' parameter does not " +
814 "contain a '--accept' parameter for connecting the office.";
819 return errorMessage;
823 * Validate the connection string. Returned is an error message, starting
824 * with "Error:", or a warning, if the command might work.
825 * @param connectString The connection string that is checked.
826 * @param checkAppExecutionCommand If the AppExecutionCommand is checked, the error messages willbe different.
827 * @return The error message, or OK, if no error was detected.
829 public static String validateConnectString(String connectString, boolean checkAppExecutionCommand) {
830 String acceptPrefix = "";
831 if (checkAppExecutionCommand) {
832 acceptPrefix = "--accept=";
835 String errorMessage = "OK";
836 // a warning, if an unknown connection method is used
837 if (connectString.indexOf("socket") != -1) {
838 if (connectString.indexOf(acceptPrefix + "socket,host=") == -1 ||
839 connectString.indexOf("port=") == -1) {
840 if (checkAppExecutionCommand) {
841 errorMessage = "Error: The '--accept' parameter contains a syntax error: It should be like: '--accept=socket,host=localhost,port=8100;urp;";
842 } else {
843 errorMessage = "Error: The 'ConnectionString' parameter contains a syntax error: It should be like: 'socket,host=localhost,port=8100'";
846 } else if (connectString.indexOf("pipe") != -1) {
847 if (connectString.indexOf(acceptPrefix + "pipe,name=") == -1) {
848 if (checkAppExecutionCommand) {
849 errorMessage = "Error: The '--accept' parameter contains a syntax error: It should be like: '--accept=pipe,name=myuniquename;urp;'";
850 } else {
851 errorMessage = "Error: The 'ConnectionString' parameter contains a syntax error: It should be like: 'pipe,name=myuniquename'";
854 } else {
855 if (checkAppExecutionCommand) {
856 errorMessage = "Warning: The '--accept' parameter contains an unknown connection method.";
857 } else {
858 errorMessage = "Warning: The 'ConnectionString' parameter contains an unknown connection method.";
861 return errorMessage;
865 * String.replaceAll() ist available since Java 1.4 but the runner must be buldabale with Java 1.3
866 * @param originalString
867 * @param searchString
868 * @param replaceString
869 * @return modified string
871 public static String replaceAll13(String originalString, String searchString, String replaceString) {
873 StringBuffer changeStringBuffer = new StringBuffer(originalString);
874 int searchLength = searchString.length();
875 int replaceLength = replaceString.length();
876 int index = originalString.indexOf(searchString);
877 while (index != -1) {
878 changeStringBuffer = changeStringBuffer.replace(index, index + searchLength, replaceString);
879 originalString = changeStringBuffer.toString();
880 index = originalString.indexOf(searchString, index + replaceLength);
882 return originalString;
886 * expand macrofied strings like <CODE>${$ORIGIN/bootstrap.ini:UserInstallation}</CODE> or
887 * <CODE>$_OS</CODE>
888 * @param xMSF the MultiServiceFactory
889 * @param expand the string to expand
890 * @throws java.lang.Exception was thrown on any exception
891 * @return return the expanded string
892 * @see com.sun.star.util.XMacroExpander
894 public static String expandMacro(XMultiServiceFactory xMSF, String expand) throws java.lang.Exception {
895 try {
896 XPropertySet xPS = UnoRuntime.queryInterface(XPropertySet.class, xMSF);
897 XComponentContext xContext = UnoRuntime.queryInterface(XComponentContext.class,
898 xPS.getPropertyValue("DefaultContext"));
899 XMacroExpander xME = UnoRuntime.queryInterface(XMacroExpander.class,
900 xContext.getValueByName("/singletons/com.sun.star.util.theMacroExpander"));
901 return xME.expandMacros(expand);
902 } catch (Exception e) {
903 throw new Exception("could not expand macro: " + e.toString(), e);
909 * returns the platform of the office.<br>
910 * Since the runner and the office could run on different platform this function delivers the
911 * platform the office is running.
912 * @param xMSF the XMultiServiceFactory
913 * @return unxsols, unxsoli, unxlngi, wntmsci
915 public static String getOfficeOS(XMultiServiceFactory xMSF) {
916 String platform = "unknown";
918 try {
919 String theOS = expandMacro(xMSF, "$_OS");
921 if (theOS.equals("Windows")) {
922 platform = "wntmsci";
923 } else if (theOS.equals("Linux")) {
924 platform = "unxlngi";
925 } else {
926 if (theOS.equals("Solaris")) {
927 String theArch = expandMacro(xMSF, "$_ARCH");
928 if (theArch.equals("SPARC")) {
929 platform = "unxsols";
930 } else if (theArch.equals("x86")) {
931 platform = "unxsoli";
935 } catch (Exception ex) {
937 return platform;
941 * dispatches given <CODE>URL</CODE> to the document <CODE>XComponent</CODE>
942 * @param xMSF the <CODE>XMultiServiceFactory</CODE>
943 * @param xDoc the document where to dispatch
944 * @param URL the <CODE>URL</CODE> to dispatch
945 * @throws java.lang.Exception throws <CODE>java.lang.Exception</CODE> on any error
947 public static void dispatchURL(XMultiServiceFactory xMSF, XComponent xDoc, String URL) throws java.lang.Exception {
948 XModel aModel = UnoRuntime.queryInterface(XModel.class, xDoc);
950 XController xCont = aModel.getCurrentController();
952 dispatchURL(xMSF, xCont, URL);
957 * dispatches given <CODE>URL</CODE> to the <CODE>XController</CODE>
958 * @param xMSF the <CODE>XMultiServiceFactory</CODE>
959 * @param xCont the <CODE>XController</CODE> to query for a XDispatchProvider
960 * @param URL the <CODE>URL</CODE> to dispatch
961 * @throws java.lang.Exception throws <CODE>java.lang.Exception</CODE> on any error
963 public static void dispatchURL(XMultiServiceFactory xMSF, XController xCont, String URL) throws java.lang.Exception {
964 try {
966 XDispatchProvider xDispProv = UnoRuntime.queryInterface(XDispatchProvider.class, xCont);
968 XURLTransformer xParser = UnoRuntime.queryInterface(
969 XURLTransformer.class,
970 xMSF.createInstance("com.sun.star.util.URLTransformer"));
972 // Because it's an in/out parameter we must use an array of URL objects.
973 URL[] aParseURL = new URL[1];
974 aParseURL[0] = new URL();
975 aParseURL[0].Complete = URL;
976 xParser.parseStrict(aParseURL);
978 URL aURL = aParseURL[0];
980 XDispatch xDispatcher = xDispProv.queryDispatch(aURL, "", 0);
981 xDispatcher.dispatch(aURL, null);
983 utils.shortWait(3000);
985 } catch (Exception e) {
986 throw new Exception("ERROR: could not dispatch URL '" + URL + "': " + e.toString());
990 /** returns a String which contains the current date and time<br>
991 * format: [DD.MM.YYYY - HH:MM:SS::mm]
993 ** @return a String which contains the current date and time
995 public static String getDateTime() {
997 Calendar cal = new GregorianCalendar();
998 DecimalFormat dfmt = new DecimalFormat("00");
999 String dateTime = dfmt.format(cal.get(Calendar.DAY_OF_MONTH)) + "." +
1000 dfmt.format(cal.get(Calendar.MONTH) + 1) + "." +
1001 dfmt.format(cal.get(Calendar.YEAR)) + " - " +
1002 dfmt.format(cal.get(Calendar.HOUR_OF_DAY)) + ":" +
1003 dfmt.format(cal.get(Calendar.MINUTE)) + ":" +
1004 dfmt.format(cal.get(Calendar.SECOND)) + "," +
1005 dfmt.format(cal.get(Calendar.MILLISECOND));
1006 return "[" + dateTime + "]";