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

From Apache OpenOffice Wiki
Jump to: navigation, search
(Getting Started)
Line 6: Line 6:
 
Since {{PRODUCTNAME}} {{OOo2.x}} 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 <code>FirstUnoContact</code> class.
 
Since {{PRODUCTNAME}} {{OOo2.x}} 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 <code>FirstUnoContact</code> class.
  
To create and run the class in the NetBeans 3.5.1 IDE, use the following steps:
+
To create and run the example in the NetBeans IDE, use the following steps:
 +
 
 +
# 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 and change maybe the package and/or the location. Press '''Finish''' to create the project.
 +
# Navigate over the project node '''FirstUnoContact''' -> '''Source Packages''' -> ... to the generated FirstUnoContect.java skeleton.
 +
# Complete the generated source code as shown below <!--[SOURCE:FirstSteps/FirstUnoContact.java].-->
 +
# Build the project by pressing '''F11''' and run it by pressing '''F6'''
  
# 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'''.
 
# 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.
 
# Enter the source code shown below <!--[SOURCE:FirstSteps/FirstUnoContact.java].-->
 
# 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'''.
 
# 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 <code>build_FirstUnoContact</code> is added to your project. Click '''Finish''' to create the script.
 
# Enter the script code shown below. <!--[SOURCE:FirstSteps/build_FirstUnoContact.xml] Adjust the property values OFFICE_HOME and OO_SDK_HOME to your own local environment.
 
# Select and right click the <code>build_FirstUnoContact</code> script, select '''Execute''' to build the example project. Right click the <code>build_FirstUnoContact</code> script again, select '''Run Target''' to display more availble targets, select the run target to execute the example.
 
 
The FirstUnoContact example: <!--[SOURCE:FirstSteps/FirstUnoContact.java]-->
 
The FirstUnoContact example: <!--[SOURCE:FirstSteps/FirstUnoContact.java]-->
  
 
   public class FirstUnoContact {
 
   public class FirstUnoContact {
 
+
      ...
 
       public static void main(String[] args) {
 
       public static void main(String[] args) {
 
           try {
 
           try {
Line 42: Line 40:
 
   }
 
   }
  
The example ant build script: <!--[SOURCE:FirstSteps/build_FirstUnoContact.xml]-->
+
Whereas in NetBeans the '''OpenOffice.org Client Application''' wizard prepares a working project environment for you, it should be easy possible to integrate the necessary steps in other IDEs as well or run an ant script directly.
 +
 
 +
An example ant build script couild be as the following: <!--[SOURCE:FirstSteps/build_FirstUnoContact.xml]-->
  
 
   <?xml version="1.0" encoding="UTF-8"?>
 
   <?xml version="1.0" encoding="UTF-8"?>
 
   <project basedir="." default="all" name="FirstUnoContact">
 
   <project basedir="." default="all" name="FirstUnoContact">
 
    
 
    
       <property name="OFFICE_HOME" value="d:/StarOffice8_m48"/>
+
       <property name="OFFICE_HOME" value="c:/OpenOffice.org"/>
       <property name="OO_SDK_HOME" value="d:/SDK/StarOffice8.EA_SDK"/>
+
       <property name="OO_SDK_HOME" value="c:/OpenOffice.org_SDK"/>
 
        
 
        
 
       <target name="init">
 
       <target name="init">

Revision as of 08:41, 10 August 2007

Template:FirstSteps

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 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 and change maybe the package and/or the location. Press Finish to create the project.
  2. Navigate over the project node FirstUnoContact -> Source Packages -> ... to the generated FirstUnoContect.java skeleton.
  3. Complete the generated source code as shown below
  4. Build the project by pressing F11 and run it by pressing F6

The FirstUnoContact example:

 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);
         }
     }
 }

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

An example ant build script couild be as the following:

 <?xml version="1.0" encoding="UTF-8"?>
 <project basedir="." default="all" name="FirstUnoContact">
 
     <property name="OFFICE_HOME" value="c:/OpenOffice.org"/>
     <property name="OO_SDK_HOME" value="c:/OpenOffice.org_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 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
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