Difference between revisions of "Documentation/DevGuide/FirstSteps/First Contact"

From Apache OpenOffice Wiki
Jump to: navigation, search
([IDL WORKAROUND] replaced IDL tags with hard links (checkpoint save))
([IDLWORKAROUND] replaced idlm and idls tags with hard links)
 
Line 165: Line 165:
 
For example, the following services are available:
 
For example, the following services are available:
  
''[http://www.openoffice.org/api/docs/common/ref/com/sun/star/frame/Desktop.html com.sun.star.frame.Desktop]''
+
''<idl>com.sun.star.frame.Desktop</idl>''
 
: maintains loaded documents: is used to load documents, to get the current document, and access all loaded documents
 
: maintains loaded documents: is used to load documents, to get the current document, and access all loaded documents
  
''[http://www.openoffice.org/api/docs/common/ref/com/sun/star/configuration/ConfigurationProvider.html com.sun.star.configuration.ConfigurationProvider]''
+
''<idl>com.sun.star.configuration.ConfigurationProvider</idl>''
 
: yields access to the {{PRODUCTNAME}} configuration, for instance the settings in the '''Tools''' > '''Options''' dialog
 
: yields access to the {{PRODUCTNAME}} configuration, for instance the settings in the '''Tools''' > '''Options''' dialog
  
''[http://www.openoffice.org/api/docs/common/ref/com/sun/star/sdb/DatabaseContext.html com.sun.star.sdb.DatabaseContext]''
+
''<idl>com.sun.star.sdb.DatabaseContext</idl>''
 
: holds databases registered with {{PRODUCTNAME}}
 
: holds databases registered with {{PRODUCTNAME}}
  
''[http://www.openoffice.org/api/docs/common/ref/com/sun/star/system/SystemShellExecute.html com.sun.star.system.SystemShellExecute]''
+
''<idl>com.sun.star.system.SystemShellExecute</idl>''
 
: executes system commands or documents registered for an application on the current platform
 
: executes system commands or documents registered for an application on the current platform
  
''[http://www.openoffice.org/api/docs/common/ref/com/sun/star/text/GlobalSettings.html com.sun.star.text.GlobalSettings]''
+
''<idl>com.sun.star.text.GlobalSettings</idl>''
 
: manages global view and print settings for text documents
 
: manages global view and print settings for text documents
  
Line 186: Line 186:
 
The <tt>FirstUnoContact</tt> class above is considered a client of the {{PRODUCTNAME}} process, {{PRODUCTNAME}} is the server in this respect. The server has its own component context and its own service manager, which can be accessed from client programs to use the office functionality. The client program initializes UNO and gets the component context from the {{PRODUCTNAME}} process. Internally, this initialization process creates a local service manager, establishes a pipe connection to a running {{PRODUCTNAME}} process (if necessary a new process is started) and returns the remote component context. In the first step this is the only thing you have to know. The [http://api.openoffice.org/docs/java/ref/com/sun/star/comp/helper/Bootstrap.html <tt>com.sun.star.comp.helper.Bootstrap.bootstrap()</tt>] method initializes UNO and returns the remote component context of a running {{PRODUCTNAME}} process. You can find more details about bootstrapping UNO, the opportunities of different connection types and how to establish a connection to a UNO server process in the [[Documentation/DevGuide/ProUNO/UNO Concepts|UNO Concepts]].  
 
The <tt>FirstUnoContact</tt> class above is considered a client of the {{PRODUCTNAME}} process, {{PRODUCTNAME}} is the server in this respect. The server has its own component context and its own service manager, which can be accessed from client programs to use the office functionality. The client program initializes UNO and gets the component context from the {{PRODUCTNAME}} process. Internally, this initialization process creates a local service manager, establishes a pipe connection to a running {{PRODUCTNAME}} process (if necessary a new process is started) and returns the remote component context. In the first step this is the only thing you have to know. The [http://api.openoffice.org/docs/java/ref/com/sun/star/comp/helper/Bootstrap.html <tt>com.sun.star.comp.helper.Bootstrap.bootstrap()</tt>] method initializes UNO and returns the remote component context of a running {{PRODUCTNAME}} process. You can find more details about bootstrapping UNO, the opportunities of different connection types and how to establish a connection to a UNO server process in the [[Documentation/DevGuide/ProUNO/UNO Concepts|UNO Concepts]].  
  
After this first initialization step, you can use the method [http://www.openoffice.org/api/docs/common/ref/com/sun/star/uno/XComponentContext.html#getServiceManager getServiceManager]() from the component context to get the remote service manager from the {{PRODUCTNAME}} process, which offers you access to the complete office functionality available through the API.
+
After this first initialization step, you can use the method [http://api.openoffice.org/docs/common/ref/com/sun/star/uno/XComponentContext.html#getServiceManager getServiceManager]() from the component context to get the remote service manager from the {{PRODUCTNAME}} process, which offers you access to the complete office functionality available through the API.
  
 
====Failed Connections====
 
====Failed Connections====
Line 196: Line 196:
 
* Clients that are supposed to run over a long period of time should not assume that a reference to an initial object will be valid over the whole runtime of the client. The client should resume even if the connection goes down for some reason and comes back later on. When the connection fails, a robust, long running client should stop the current work, inform the user that the connection is not available and release the references to the remote process. When the user tries to repeat the last action, the client should try to rebuild the connection. Do not force the user to restart your program just because the connection was temporarily unavailable.  
 
* Clients that are supposed to run over a long period of time should not assume that a reference to an initial object will be valid over the whole runtime of the client. The client should resume even if the connection goes down for some reason and comes back later on. When the connection fails, a robust, long running client should stop the current work, inform the user that the connection is not available and release the references to the remote process. When the user tries to repeat the last action, the client should try to rebuild the connection. Do not force the user to restart your program just because the connection was temporarily unavailable.  
  
When the bridge has become unavailable and access is tried, it throws a [http://www.openoffice.org/api/docs/common/ref/com/sun/star/lang/DisposedException.html DisposedException]. Whenever you access remote references in your program, catch this Exception in such a way that you set your remote references to null and inform the user accordingly. If your client is designed to run for a longer period of time, be prepared to get new remote references when you find that they are currently null.  
+
When the bridge has become unavailable and access is tried, it throws a [http://api.openoffice.org/docs/common/ref/com/sun/star/lang/DisposedException.html DisposedException]. Whenever you access remote references in your program, catch this Exception in such a way that you set your remote references to null and inform the user accordingly. If your client is designed to run for a longer period of time, be prepared to get new remote references when you find that they are currently null.  
  
 
A more sophisticated way to handle lost connections is to register a listener at the underlying bridge object. The chapter [[Documentation/DevGuide/ProUNO/UNO Interprocess Connections|UNO Interprocess Connections]] shows how to write a connection-aware client.
 
A more sophisticated way to handle lost connections is to register a listener at the underlying bridge object. The chapter [[Documentation/DevGuide/ProUNO/UNO Interprocess Connections|UNO Interprocess Connections]] shows how to write a connection-aware client.

Latest revision as of 14:54, 17 May 2020



Getting Started

Since OpenOffice.org 2.0 it is very simple to get a working environment that offers a transparent use of UNO functionality and of office functionality. The following demonstrates how to write and build a small program that initializes UNO, which means that it internally connects to an office or starts a new office process if necessary and tells you if it was able to get the office component context that provides the office service manager object.

Start a Java IDE or source editor, and enter the source code for the FirstUnoContact class. In order to automate the build process one may use an Ant build script as shown below.

Using the NetBeans IDE

To create and run the example in the NetBeans IDE, use the following steps:

  1. From the File menu, select New Project. Select OpenOffice.org category and select the OpenOffice.org Client Application. On the next wizard panel insert FirstUnoContact as project name and maybe change the package and/or the location path. Press Finish to create the project.
  2. If you have a 64-bit machine, right-click the project name in the project explorer on the left and choose Properties. Click the Libraries Category on the left and use the drop-down box on the right to choose your registered 32-bit Java Platform (JDK), then click the OK button.
  3. Navigate over the project node FirstUnoContact > Source Packages > ... to the generated FirstUnoContact.java skeleton.
  4. Complete the generated source code as shown below
  5. Build the project by pressing F11 and run it by pressing F6

Whereas in NetBeans the OpenOffice.org Client Application wizard prepares a working project environment for you, it should be easily possible to integrate the necessary steps in other IDEs as well or run an Ant script directly.

Using the Eclipse IDE

To create and run the example in the Eclipse IDE, use the following steps:

  1. From the File menu, select New > Java Project. On the first wizard panel insert FirstUnoContact as project name. Press Next. On the next wizard panel check that the default output folder is set to FirstUnoContact/bin. Select the Libraries tab, where you may add the necessary libraries and a variable as described in section Prepare the Eclipse IDE. Press Finish to create the project.
  2. Right click on the project node FirstUnoContact, select New > Class to generate the FirstUnoContact.java skeleton.
  3. Complete the generated source code as shown below. Note: when you have copied the file, it will create a default package.
  4. Right click on the project node FirstUnoContact, select New > File to create the build.xml file.
  5. Enter the code for the Ant build script as shown below.
  6. From the Run menu, select External Tools > Open External Tools Dialog. On the dialog select FirstUnoContact build.xml. On the JRE tab, select the option Run in the same JRE as the workspace. Press Apply and Close. This option is necessary for the Ant property eclipse.running to be set when the Ant build script is run.
  7. Build and run the project by using the build script.

An Ant build script

An example Ant build script could be as follows:

<?xml version="1.0" encoding="UTF-8"?>
<project basedir="." default="all" name="FirstUnoContact">
 
	<!-- The following build script works with a standard installation of OpenOffice 3.0.1
	     and OpenOffice SDK 3.0.1 as described in section >Linux RPM-based Installation< 
	     of the document found at http://download.openoffice.org/common/instructions.html. -->
 
	<!-- This script is tested with the Eclipse IDE and stand-alone, without any IDE support. -->
 
	<!-- Paths based on the standard installation of OOo 3.0.1 and OOo SDK 3.0.1 on unix -->
	<property name="OFFICE_ROOT" value="/opt/openoffice.org" />
	<property name="OFFICE_HOME" value="${OFFICE_ROOT}/basis3.0" />
	<property name="OO_SDK_HOME" value="${OFFICE_HOME}/sdk" />
	<property name="OO_URE_HOME" value="${OFFICE_ROOT}/ure" />
 
	<target name="init">
		<property name="OUT_DIR" value="${basedir}/build/example1/" />
		<!-- For eclipse we need to set the output folder to this path -->
		<property name="BIN_DIR" value="${basedir}/bin/" />
	</target>
 
	<path id="office.class.path">
		<filelist dir="${OFFICE_HOME}/program/classes" files="unoil.jar" />
		<filelist dir="${OO_URE_HOME}/share/java" files="jurt.jar,ridl.jar,juh.jar" />
	</path>
 
	<fileset id="bootstrap.glue.code" dir="${OO_SDK_HOME}/classes">
		<patternset>
			<include name="com/sun/star/lib/loader/*.class" />
		</patternset>
	</fileset>
 
	<!-- Since the Eclipse IDE has an incremental compiler build in we do not need
	     to run the >compile< target in this case -->
	<target name="compile" depends="init" unless="eclipse.running">
		<mkdir dir="${BIN_DIR}" />
		<javac debug="true" deprecation="true" destdir="${BIN_DIR}" srcdir=".">
			<classpath refid="office.class.path" />
		</javac>
	</target>
 
	<target name="jar" depends="init,compile">
		<mkdir dir="${OUT_DIR}" />
		<jar basedir="${BIN_DIR}" compress="true" jarfile="${OUT_DIR}/FirstUnoContact.jar">
			<exclude name="**/*.java" />
			<exclude name="*.jar" />
			<fileset refid="bootstrap.glue.code" />
			<manifest>
				<attribute name="Main-Class" value="com.sun.star.lib.loader.Loader" />
				<section name="com/sun/star/lib/loader/Loader.class">
					<attribute name="Application-Class" value="de.ooo.devguide.example1.FirstUnoContact" />
				</section>
			</manifest>
		</jar>
	</target>
 
	<target name="all" description="Build everything." depends="init,compile,jar">
		<echo message="Application built. FirstUnoContact!" />
	</target>
 
	<target name="run" description="Try running it." depends="all">
		<java jar="${OUT_DIR}/FirstUnoContact.jar" failonerror="true" fork="true">
		</java>
	</target>
 
	<target name="cleanbin" description="Clean all binaries." unless="eclipse.running">
		<delete>
			<fileset dir="${BIN_DIR}">
				<include name="**/*.class" />
			</fileset>
		</delete>
	</target>
 
	<target name="cleanall" description="Clean all build products." depends="init,cleanbin">
		<delete file="${OUT_DIR}/FirstUnoContact.jar" />
	</target>
 
</project>

This build script has been tested stand-alone and with the Eclipse IDE. For use with other IDEs it may have to be adapted. The comments and all targets that have an unless attribute with the value eclipse.running should give an idea about what might be necessary.

The script works with a standard installation on unix, which is rooted at /opt. For other installations the property OFFICE_ROOT has to be set accordingly.

The FirstUnoContact class

The FirstUnoContact example that connects to the office with java:

package de.ooo.devguide.example1;
 
public class FirstUnoContact {
 
    public static void main(String[] args) {
	try {
	    // get the remote office component context
	    com.sun.star.uno.XComponentContext xContext = com.sun.star.comp.helper.Bootstrap.bootstrap();
 
	    System.out.println("Connected to a running office ...");
 
	    com.sun.star.lang.XMultiComponentFactory xMCF = xContext.getServiceManager();
 
            String available = (xMCF != null ? "available" : "not available");
	    System.out.println("remote ServiceManager is " + available);
	} catch (java.lang.Exception e) {
	    e.printStackTrace();
	} finally {
	    System.exit(0);
	}
    }
}

For an example that connects to the office with C++, see chapter C++ Language Binding. Accessing the office with OpenOffice.org Basic is described in First Steps with OpenOffice.org Basic. The next section describes what happens during the connection between a Java program and OpenOffice.org.

Service Managers

UNO introduces the concept of service managers, which can be considered as “factories” that create services. For now, it is sufficient to see services as UNO objects that can be used to perform specific tasks. Later on we will give a more precise definition for the term service. For example, the following services are available:

com.sun.star.frame.Desktop

maintains loaded documents: is used to load documents, to get the current document, and access all loaded documents

com.sun.star.configuration.ConfigurationProvider

yields access to the OpenOffice.org configuration, for instance the settings in the Tools > Options dialog

com.sun.star.sdb.DatabaseContext

holds databases registered with OpenOffice.org

com.sun.star.system.SystemShellExecute

executes system commands or documents registered for an application on the current platform

com.sun.star.text.GlobalSettings

manages global view and print settings for text documents
Service manager

A service always has a component context, which consists of the service manager that created the service and other data to be used by the service.

The FirstUnoContact class above is considered a client of the OpenOffice.org process, OpenOffice.org is the server in this respect. The server has its own component context and its own service manager, which can be accessed from client programs to use the office functionality. The client program initializes UNO and gets the component context from the OpenOffice.org process. Internally, this initialization process creates a local service manager, establishes a pipe connection to a running OpenOffice.org process (if necessary a new process is started) and returns the remote component context. In the first step this is the only thing you have to know. The com.sun.star.comp.helper.Bootstrap.bootstrap() method initializes UNO and returns the remote component context of a running OpenOffice.org process. You can find more details about bootstrapping UNO, the opportunities of different connection types and how to establish a connection to a UNO server process in the UNO Concepts.

After this first initialization step, you can use the method getServiceManager() from the component context to get the remote service manager from the OpenOffice.org process, which offers you access to the complete office functionality available through the API.

Failed Connections

A remote connection can fail under certain conditions:

  • Client programs should be able to detect errors. For instance, sometimes the bridge might become unavailable. Simple clients that connect to the office, perform a certain task and exit afterwards should stop their work and inform the user if an error occurred.
  • Clients that are supposed to run over a long period of time should not assume that a reference to an initial object will be valid over the whole runtime of the client. The client should resume even if the connection goes down for some reason and comes back later on. When the connection fails, a robust, long running client should stop the current work, inform the user that the connection is not available and release the references to the remote process. When the user tries to repeat the last action, the client should try to rebuild the connection. Do not force the user to restart your program just because the connection was temporarily unavailable.

When the bridge has become unavailable and access is tried, it throws a DisposedException. Whenever you access remote references in your program, catch this Exception in such a way that you set your remote references to null and inform the user accordingly. If your client is designed to run for a longer period of time, be prepared to get new remote references when you find that they are currently null.

A more sophisticated way to handle lost connections is to register a listener at the underlying bridge object. The chapter UNO Interprocess Connections shows how to write a connection-aware client.

Content on this page is licensed under the Public Documentation License (PDL).
Personal tools
In other languages