OO-Snippets: Connect to Listening OpenOffice

Commons

Keywordsbootstrap, connect
LanguageJava
ApplicationOffice
AuthorsTobias Krais (www.design-to-use.de) (initial)
Supported Versions2.0.x  1.1.x  
Supported OSAll  
QuestionHow to connect to a already listening OpenOffice?

You can start a OpenOffice in listening mode with e.g. this command:

ooffice -accept="socket,host=localhost,port=9000;urp;StarOffice.ServiceManager"

This commandline starts OpenOffice listening on port 9000

Answer

This method connect to a listening OpenOffice.

Code-Snippet-Listing (snippet-source)

import com.sun.star.beans.XPropertySet;
import com.sun.star.bridge.UnoUrlResolver;
import com.sun.star.bridge.XUnoUrlResolver;
import com.sun.star.comp.helper.Bootstrap;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;

/**
 * This method connects to a running OpenOffice. This OpenOffice is
 * listening on a specific port. It connects to this port.
 * 
 * @param ooport
 * @return
 */
public void connectListeningOpenOffice(String ooport)
{
	try{
		// Create an OO Component Context
		XComponentContext xCC = 
				Bootstrap.createInitialComponentContext(null);

		// create a connector, so that it can contact the office
		XUnoUrlResolver urlResolver = UnoUrlResolver.create(xCC);

		Object initialObject = urlResolver.resolve(
				"uno:socket,host=localhost,port=" + ooport
				+ ";urp;StarOffice.ServiceManager");

		XMultiComponentFactory xMCF = (XMultiComponentFactory)
				UnoRuntime.queryInterface(XMultiComponentFactory.class,
							initialObject);

		// retrieve the component context as property (it is not yet
		// exported from the office). Query for the XPropertySet interface.
		XPropertySet xProperySet = (XPropertySet) UnoRuntime.queryInterface(
				XPropertySet.class, xMCF);

		// Get the default context from the office server.
		Object oDefaultContext = xProperySet.getPropertyValue("DefaultContext");

		// Query for the interface XComponentContext.
		xCC = (XComponentContext)
		UnoRuntime.queryInterface(XComponentContext.class, oDefaultContext);

		// now create the desktop service
		// NOTE: use the office component context here!
		Object desktop = xMCF.createInstanceWithContext(
				"com.sun.star.frame.Desktop", xCC);
	}
	catch(Exception e){
	}
}

Changelog

DateUserModification
2006-12-11tobiaskraisLinking imports
2006-03-20tobiaskraisInitial version

and