Documentation/DevGuide/FirstSteps/First Contact

From Apache OpenOffice Wiki
< Documentation‎ | DevGuide
Revision as of 10:33, 12 June 2007 by Cc208500 (Talk)

Jump to: navigation, search

Template:DevGuide

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 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 the Java IDE or source editor, and enter the following source code for the FirstUnoContact class.

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

  1. Add a main class to the project. In the NetBeans Explorer window, click the Project <project_name> tab, right click the Project item, select Add New... to display the New Wizard, open the Java Classes folder, highlight the template Main, and click Next.
  2. In the Name field, enter 'FirstUnoContact' as classname for the Main class and select the folder that contains your project files. The FirstUnoContact is added to the default package of your project. Click Finish to create the class.
  3. Enter the source code shown below
  4. Add a blank ant script to the project. In the NetBeans Explorer window, click the Project <project_name> tab, right click the Project item, select Add New... to display the New Wizard, open the Ant Build Scripts folder, highlight the template Blank Ant Project, and click Next.
  5. In the Name field, enter 'build_FirstUnoContact' as script name for the ant build script and select the folder that contains your project files. The build_FirstUnoContact is added to your project. Click Finish to create the script.
  6. Enter the script code shown below.
 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);
         }
     }
 }

The example ant build script:

 <?xml version="1.0" encoding="UTF-8"?>
 <project basedir="." default="all" name="FirstUnoContact">
 
     <property name="OFFICE_HOME" value="d:/StarOffice8_m48"/>
     <property name="OO_SDK_HOME" value="d:/SDK/StarOffice8.EA_SDK"/>
     
     <target name="init">
         <property name="OUTDIR" value="${OO_SDK_HOME}/WINExample.out/class/FirstUnoContact"/>
     </target>
 
     <path id="office.class.path"> 
         <filelist dir="${OFFICE_HOME}/program/classes"
             files="jurt.jar,unoil.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"/>
             <include name="win/unowinreg.dll"/>
         </patternset>
     </fileset>    
            
     <target name="compile" depends="init">
         <mkdir dir="${OUTDIR}"/>
         <javac debug="true" deprecation="true" destdir="${OUTDIR}" srcdir=".">
             <classpath refid="office.class.path"/>
         </javac>
     </target>
 
     <target name="jar" depends="init,compile">
         <jar basedir="${OUTDIR}" compress="true" 
             jarfile="${OUTDIR}/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"/>
                 
             </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="init,all">
         <java jar="${OUTDIR}/FirstUnoContact.jar" failonerror="true" fork="true">
         </java>
     </target>
 
     <target  name="clean" description="Clean all build products." depends="init">
         <delete>
             <fileset dir="${OUTDIR}">
                 <include name="**/*.class"/>
             </fileset>
         </delete>
         <delete file="${OUTDIR}/FirstUnoContact.jar"/>
     </target>
 
 </project>

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 OpenOffice.org Basic and Dialogs. 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
Illustration 2.1: Service manager

A service always exists in 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 com.sun.star.lang.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 be to register a listener at the underlying bridge object. The chapter UNO Interprocess Connections shows how to write a connection-aware client.

Personal tools