1 // base classes 2 import com.sun.star.uno.UnoRuntime; 3 4 // factory for creating components 5 import com.sun.star.beans.PropertyValue; 6 import com.sun.star.bridge.XUnoUrlResolver; 7 import com.sun.star.frame.XComponentLoader; 8 import com.sun.star.frame.XDesktop; 9 import com.sun.star.frame.XModel; 10 import com.sun.star.lang.XMultiServiceFactory; 11 import com.sun.star.uno.XInterface; 12 13 // Exceptions 14 import com.sun.star.uno.RuntimeException; 15 16 17 /** @descr This class establishes a connection to a StarOffice application. 18 */ 19 public class OfficeConnection 20 { 21 public OfficeConnection (int nPortNumber) 22 { 23 mnDefaultPort = nPortNumber; 24 connect (); 25 } 26 27 /** @descr Return the service manager that represents the connected 28 StarOffice application 29 */ 30 public XMultiServiceFactory getServiceManager () 31 { 32 if ( ! mbInitialized) 33 connect (); 34 return maServiceManager; 35 } 36 37 /** @descr Return a flag that indicates if the constructor has been able to 38 establish a valid connection. 39 */ 40 public boolean connectionIsValid () 41 { 42 return getServiceManager() != null; 43 } 44 45 /** @descr Connect to a already running StarOffice application. 46 */ 47 private void connect () 48 { 49 connect (msDefaultHost, mnDefaultPort); 50 } 51 52 private void connect (String hostname) 53 { 54 connect (hostname, mnDefaultPort); 55 } 56 57 /** @descr Connect to a already running StarOffice application that has 58 been started with a command line argument like 59 "-accept=socket,host=localhost,port=5678;urp;" 60 */ 61 private void connect (String hostname, int portnumber) 62 { 63 mbInitialized = true; 64 // Set up connection string. 65 String sConnectString = "uno:socket,host=" + hostname + ",port=" + portnumber 66 + ";urp;StarOffice.ServiceManager"; 67 68 69 // connect to a running office and get the ServiceManager 70 try 71 { 72 // Create a URL Resolver. 73 XMultiServiceFactory aLocalServiceManager = 74 com.sun.star.comp.helper.Bootstrap.createSimpleServiceManager(); 75 XUnoUrlResolver aURLResolver = (XUnoUrlResolver) UnoRuntime.queryInterface ( 76 XUnoUrlResolver.class, 77 aLocalServiceManager.createInstance ("com.sun.star.bridge.UnoUrlResolver") 78 ); 79 80 maServiceManager = (XMultiServiceFactory) UnoRuntime.queryInterface ( 81 XMultiServiceFactory.class, 82 aURLResolver.resolve (sConnectString) 83 ); 84 } 85 86 catch (Exception e) 87 { 88 MessageArea.println ("Could not connect with " + sConnectString + " : " + e); 89 MessageArea.println ("Please start OpenOffice/StarOffice with " 90 + "\"-accept=socket,host=localhost,port=5678;urp;\""); 91 } 92 } 93 94 private int mnDefaultPort = 5678; 95 private final String msDefaultHost = "localhost"; 96 private XMultiServiceFactory maServiceManager = null; 97 98 /** A value of true just indicates that it has been tried to establish a connection, 99 not that that has been successfull. 100 */ 101 private boolean mbInitialized = false; 102 } 103