[ Previous document | Content Table | Next document ]

3  Professional UNO

 

 

This chapter provides in-depth information about UNO and the use of UNO in various programming languages. There are four sections: 

3.1  Introduction

The goal of UNO (Universal Network Objects) is to provide an environment for network objects across programming language and platform boundaries. UNO objects run and communicate everywhere. UNO reaches this goal by providing the following fundamental framework: 

3.2  API Concepts

The OpenOffice.org API is a language independent approach to specify the functionality of OpenOffice.org. Its main goals are to provide an API to access the functionality of OpenOffice.org, to enable users to extend the functionality by their own solutions and new features, and to make the internal implementation of OpenOffice.org exchangeable. 

A long term target on the OpenOffice.org roadmap is to split the existing OpenOffice.org into small components which are combined to provide the complete OpenOffice.org functionality. Such components are manageable, they interact with each other to provide high level features and they are exchangeable with other implementations providing the same functionality, even if these new implementations are implemented in a different programming language. When this target will be reached, the API, the components and the fundamental concepts will provide a construction kit, which makes OpenOffice.org adaptable to a wide range of specialized solutions and not only an office suite with a predefined and static functionality. 

This section provides you with a thorough understanding of the concepts behind the OpenOffice.org API. In the API reference there are UNOIDL data types which are unknown outside of the API. The reference provides abstract specifications which sometimes can make you wonder how they map to implementations you can actually use. 

The data types of the API reference are explained in 3.2.1 Professional UNO - API Concepts - Data Types. The relationship between API specifications and OpenOffice.org implementations is treated in 3.2.2 Professional UNO - API Concepts - Understanding the API Reference.

3.2.1  Data Types

The data types in the API reference are UNO types which have to be mapped to the types of any programming language that can be used with the OpenOffice.org API. In the chapter 2 First Steps the most important UNO types were introduced. However, there is much more to be said about simple types, interfaces, properties and services in UNO. There are special flags, conditions and relationships between these entities which you will want to know if you are working with UNO on a professional level.

This section explains the types of the API reference from the perspective of a developer who wants to use the OpenOffice.org API. If you are interested in writing your own components, and you must define new interfaces and types, please refer to the chapter 4 Writing UNO Components, which describes how to write your own UNOIDL specifications and how to create UNO components.

Simple Types

UNO provides a set of predefined, simple types which are listed in the following table: 

UNO Type 

Description 

void

Empty type, used only as method return type and in any.

boolean

Can be true or false.

byte

Signed 8-bit integer type (ranging from -128 to 127, inclusive). 

short

Signed 16-bit integer type (ranging from −32768 to 32767, inclusive). 

unsigned short

Unsigned 16-bit integer type (deprecated). 

long

Signed 32-bit integer type (ranging from −2147483648 to 2147483647, inclusive). 

unsigned long

Unsigned 32-bit integer type (deprecated). 

hyper

Signed 64-bit integer type (ranging from −9223372036854775808 to 9223372036854775807, inclusive). 

unsigned hyper

Unsigned 64-bit integer type (deprecated). 

float

IEC 60559 single precision floating point type. 

double

IEC 60559 double precision floating point type. 

char

Represents individual Unicode characters (more precisely: individual UTF-16 code units). 

string

Represents Unicode strings (more precisely: strings of Unicode scalar values). 

type

Meta type that describes all UNO types. 

any

Special type that can represent values of all other types. 

The chapters about language bindings 3.4.1 Professional UNO - UNO Language Bindings - Java Language Binding, 3.4.2 Professional UNO - UNO Language Bindings - C++ Language Binding, 3.4.3 Professional UNO - UNO Language Bindings - OpenOffice.org Basic and 3.4.4 Professional UNO - UNO Language Bindings - Automation Bridge describe how these types are mapped to the types of your target language.

The Any Type

The special type any can represent values of all other UNO types. In the target languages, the any type requires special treatment. There is an AnyConverter in Java and special operators in C++. For details, see the section 3.4 Professional UNO - UNO Language Bindings about language bindings.

Interfaces

Communication between UNO objects is based on object interfaces. Interfaces can be seen from the outside or the inside of an object. 

From the outside of an object, an interface provides a functionality or special aspect of the object. Interfaces provide access to objects by publishing a set of operations that cover a certain aspect of an object without telling anything about its internals.

The concept of interfaces is quite natural and frequently used in everyday life. Interfaces allow the creation of things that fit in with each other without knowing internal details about them. A power plug that fits into a standard socket or a one-size-fits-all working glove are simple examples. They all work by standardizing the minimal conditions that must be met to make things work together. 

A more advanced example would be the “remote control aspect” of a simple TV system. One possible feature of a TV system is a remote control. The remote control functions can be described by an XPower and an XChannel interface. The illustration below shows a RemoteControl object with these interfaces:

UML diagram showing the RemoteControl serviceIllustration 3.1: RemoteControl service

The XPower interface has the functions turnOn() and turnOff() to control the power and the XChannel interface has the functions select(), next(),  previous() to control the current channel. The user of these interfaces does not care if he uses an original remote control that came with a TV set or a universal remote control as long as it carries out these functions. The user is only dissatisfied if some of the functions promised by the interface do not work with a remote control.

From the inside of an object, or from the perspective of someone who implements a UNO object, interfaces are abstract specifications. The abstract specification of all the interfaces in the OpenOffice.org API has the advantage that user and implementer can enter into a contract, agreeing to adhere to the interface specification. A program that strictly uses the OpenOffice.org API according to the specification will always work, while an implementer can do whatever he wants with his objects, as long as he serves the contract.

UNO uses the interface type to describe such aspects of UNO objects. By convention, all interface names start with the letter X to distinguish them from other types. All interface types must inherit the com.sun.star.uno.XInterface root interface, either directly or in the inheritance hierarchy. XInterface is explained in 3.3.3 Professional UNO - UNO Concepts - Using UNO Interfaces. The interface types define methods (sometimes also called operations) to provide access to the specified UNO objects.

Interfaces allow access to the data inside an object through dedicated methods (member functions) which encapsulate the data of the object. The methods always have a parameter list and a return value, and they may define exceptions for smart error handling. 

The exception concept in the OpenOffice.org API is comparable with the exception concepts known from Java or C++. All operations can raise com.sun.star.uno.RuntimeExceptions without explicit specification, but all other exceptions must be specified. UNO exceptions are explained in the section 3.3.7 Professional UNO - UNO Concepts - Exception Handling below.

Consider the following two examples for interface definitions in UNOIDL notation. UNOIDL interfaces resemble Java interfaces, and methods look similar to Java method signatures. However, note the flags in square brackets in the following example:

// base interface for all UNO interfaces 

 

interface XInterface 

        any queryInterface( [in] type aType );

        [oneway] void acquire();

        [oneway] void release();

 

};  

 

// fragment of the Interface com.sun.star.io.XInputStream 

 

interface XInputStream: com::sun::star::uno::XInterface 

{  

    long readBytes( [out] sequence<byte> aData,

                    [in] long nBytesToRead )

                raises( com::sun::star::io::NotConnectedException,

                        com::sun::star::io::BufferSizeExceededException,

                        com::sun::star::io::IOException);

    ...

};  

 

The [oneway] flag indicates that an operation can be executed asynchronously if the underlying method invocation system does support this feature. For example, a UNO Remote Protocol (URP) bridge is a system that supports oneway calls.

Pay attention to the following important text section

Although there are no general problems with the specification and the implementation of the UNO oneway feature, there are several API remote usage scenarios where oneway calls cause deadlocks in OpenOffice.org. Therefore, do not introduce new oneway methods with new OpenOffice.org UNO APIs.

There are also parameter flags. Each parameter definition begins with one of the direction flags in, out, or inout to specify the use of the parameter:

These parameter flags do not appear in the API reference. The fact that a parameter is an [out] or [inout] parameter is explained in the method details.

Interfaces consisting of methods form the basis for service specifications. 

Services

We have seen that a single-inheritance interface describes only one aspect of an object. However, it is quite common that objects have more than one aspect. UNO uses multiple-inheritance interfaces and services to specify complete objects which can have many aspects.

In a first step, all the various aspects of an object (which are typically represented by single-inheritance interfaces) are grouped together in one multiple-inheritance interface type. If such an object is obtainable by calling specific factory methods, this step is all that is needed. The factory methods are specified to return values of the given, multiple-inheritance  interface type. If, however, such an object is available as a general service at the global component context, a service description must be provided in a second step. This service description will be of the new style, mapping the service name (under which the service is available at the component context) to the given, multiple-inheritance interface type.

For backward compatibility, there are also old-style services, which comprise a set of single-inheritance interfaces and properties that are needed to support a certain functionality. Such a service can include other old-style services as well. The main drawback of an old-style service is that it is unclear whether it describes objects that can be obtained through specific factory methods (and for which there would therefore be no new-style service description), or whether it describes a general service that is available at the global component context, and for which there would thus be a new-style service description. 

From the perspective of a user of a UNO object, the object offers one or sometimes even several independent, multiple-inheritance interfaces or old-style services described in the API reference. The services are utilized through method calls grouped in interfaces, and through properties, which are handled through special interfaces as well. Because the access to the functionality is provided by interfaces only, the implementation is irrelevant to a user who wants to use an object.

From the perspective of an implementer of a UNO object, multiple-inheritance interfaces and old-style services are used to define a functionality independently of a programming language and without giving instructions about the internal implementation of the object. Implementing an object means that it must support all specified interfaces and properties. It is possible that a UNO object implements more than one independent, multiple-inheritance interface or old-style service. Sometimes it is useful to implement two or more independent, multiple-inheritance interfaces or services because they have related functionality, or because they support different views to the object.

Illustration 3.2 shows the relationship between interfaces and services. The language independent specification of an old-style service with several interfaces is used to implement a UNO object that fulfills the specification. Such a UNO object is sometimes called a “component,” although that term is more correctly used to describe deployment entities within a UNO environment. The illustration uses an old-style service description that directly supports multiple interfaces; for a new-style service description, the only difference would be that it would only support one multiple-inheritance interface, which in turn would inherit the other interfaces.

Service specification against service implementationIllustration 3.2: Interfaces, services and implementation

The functionality of a TV system with a TV set and a remote control can be described in terms of service specifications. The interfaces XPower and XChannel described above would be part of a service specification RemoteControl. The new service TVSet consists of the three interfaces XPower, XChannel and XStandby to control the power, the channel selection, the additional power function standby() and a timer() function.

UML diagram showing a TVSet serviceIllustration 3.3: TV System Specification
Referencing Interfaces

References to interfaces in a service definition mean that an implementation of this service must offer the specified interfaces. However, optional interfaces are possible. If a multiple-inheritance interface inherits an optional interface, or an old-style service contains an optional interface, any given UNO object may or may not support this interface. If you utilize an optional interface of a UNO object, always check if the result of queryInterface() is equal to null and react accordingly—otherwise your code will not be compatible with implementations without the optional interface and you might end up with null pointer exceptions. The following UNOIDL snippet shows a fragment of the specification for the old-style com.sun.star.text.TextDocument service in the OpenOffice.org API. Note the flag optional in square brackets, which makes the interfaces XFootnotesSupplier and XEndnotesSupplier non-mandatory.

// com.sun.star.text.TextDocument 

service TextDocument 

    ...

 

    interface com::sun::star::text::XTextDocument;

    interface com::sun::star::util::XSearchable;

    interface com::sun::star::util::XRefreshable;

    [optional] interface com::sun::star::text::XFootnotesSupplier;

    [optional] interface com::sun::star::text::XEndnotesSupplier;

 

    ...

}; 

Service Constructors

New-style services can have constructors, similar to interface methods: 

service SomeService: XSomeInterface {
   create1();

    create2([in] long arg1, [in] string arg2);

    create3([in] any... rest);
};

In the above example, there are three explicit constructors, named create1, create2, and create3. The first has no parameters, the second has two normal parameters, and the third has a special rest parameter, which accepts an arbitrary number of any values. Constructor parameters may only be [in], and a rest parameter must be the only parameter of a constructor, and must be of type any; also, unlike an interface method, a service constructor does not specify a return type.

The various language bindings map the UNO constructors into language-specific constructs, which can be used in client code to obtain instances of those services, given a component context. The general convention (followed,for example, by the Java and C++ language bindings) is to map each constructor to a static method (resp. function) with the same name, that takes as a first parameter an XComponentContext, followed by all the parameters specified in the constructor, and returns an (appropriately typed) service instance. If an instance cannot be obtained, a com.sun.star.uno.DeploymentException is thrown. The above SomeService would map to the following Java 1.5 class, for example:

public class SomeService {
   public static XSomeInterface create1(

        com.sun.star.uno.XComponentContext context) { ... }

    public static XSomeInterface create2(

        com.sun.star.uno.XComponentContext context, int arg1, String arg2) { ... }

    public static XSomeInterface create3(

        com.sun.star.uno.XComponentContext context, Object... rest) { ... }
}

Service constructors can also have exception specifications (“raises (Exception1, ...)”), which are treated in the same way as exception specifications of interface methods. (If a constructor has no exception specification, it may only throw runtime exceptions, com.sun.star.uno.DeploymentException in particular.)

If a new-style service is written using the short form, 

service SomeService: XSomeInterface; 

then it has an implicit constructor. The exact behavior of the implicit constructor is language-binding–specific, but it is typically named create, takes no arguments besides the XComponentContext, and may only throw runtime exceptions.

Including Properties

When the structure of the OpenOffice.org API was founded, the designers discovered that the objects in an office environment would have huge numbers of qualities that did not appear to be part of the structure of the objects, rather they seemed to be superficial changes to the underlying objects. It was also clear that not all qualities would be present in each object of a certain kind. Therefore, instead of defining a complicated pedigree of optional and non-optional interfaces for each and every quality, the concept of properties was introduced. Properties are data in an object that are provided by name over a generic interface for property access, that contains getPropertyValue() and setPropertyValue() access methods. The concept of properties has other advantages, and there is more to know about properties. Please refer to 3.3.4 Professional UNO - UNO Concepts - Properties for further information about properties.

Old-style services can list supported properties directly in the UNOIDL specification. A property defines a member variable with a specific type that is accessible at the implementing component by a specific name. It is possible to add further restrictions to a property through additional flags. The following old-style service references one interface and three optional properties. All known API types can be valid property types:

// com.sun.star.text.TextContent 

service TextContent 

    interface com::sun::star::text::XTextContent;

    [optional, property] com::sun::star::text::TextContentAnchorType AnchorType;

    [optional, readonly, property] sequence<com::sun::star::text::TextContentAnchorType> AnchorTypes;

    [optional, property] com::sun::star::text::WrapTextMode TextWrap;

}; 

Possible property flags are: 

Referencing other Services

Old-style services can include other old-style services. Such references may be optional. That a service is included by another service has nothing to do with implementation inheritance, only the specifications are combined. It is up to the implementer if he inherits or delegates the necessary functionality, or if he implements it from scratch.  

The old-style service com.sun.star.text.Paragraph in the following UNOIDL example includes one mandatory service com.sun.star.text.TextContent and five optional services. Every Paragraph must be a TextContent. It can be a TextTable and it is used to support formatting properties for paragraphs and characters:

// com.sun.star.text.Paragraph 

service Paragraph 

    service com::sun::star::text::TextContent;

    [optional] service com::sun::star::text::TextTable;

    [optional] service com::sun::star::style::ParagraphProperties;

    [optional] service com::sun::star::style::CharacterProperties;

    [optional] service com::sun::star::style::CharacterPropertiesAsian;

    [optional] service com::sun::star::style::CharacterPropertiesComplex;

 

    ...

}; 

If all the old-style services in the example above were multiple-inheritance interface types instead, the structure would be similar: the multiple-inheritance interface type Paragraph would inherit the mandatory interface TextContent and the optional interfaces TextTable, ParagraphProperties, etc.

Service Implementations in Components

A component is a shared library or Java archive containing implementations of one or more services in one of the target programming languages supported by UNO. Such a component must meet basic requirements, mostly different for the different target language, and it must support the specification of the implemented services. That means all specified interfaces and properties must be implemented. Components must be registered in the UNO runtime system. After the registration all implemented services can be used by ordering an instance of the service at the appropriate service factory and accessing the functionality over interfaces.

Based on our example specifications for a TVSet and a RemoteControl service, a component RemoteTVImpl could simulate a remote TV system:

UML diagram showing  a RmoteTV componentIllustration 3.4: RemoteTVImpl Component

Such a RemoteTV component could be a jar file or a shared library. It would contain two service implementations, TVSet and RemoteControl. Once the RemoteTV component  is registered with the global service manager, users can call the factory method of the service manager and ask for a TVSet or a RemoteControl service. Then they could use their functionality over the interfaces XPower, XChannel and XStandby. When a new  implementation of these services with better performance or new features is available later on, the old component can be replaced without breaking existing code, provided that the new features are introduced by adding interfaces.

Structs

A struct type defines several elements in a record. The elements of a struct are UNO types with a unique name within the struct. Structs have the disadvantage not to encapsulate data, but the absence of get() and set() methods can help to avoid the overhead of method calls over a UNO bridge. UNO supports single inheritance for struct types. A derived struct recursively inherits all elements of the parent and its parents.

// com.sun.star.lang.EventObject 

/** specifies the base for all event objects and identifies the 

        source of the event.

 */

struct EventObject 

        /** refers to the object that fired the event.

        */

        com::sun::star::uno::XInterface Source;

 

};  

 

// com.sun.star.beans.PropertyChangeEvent 

struct PropertyChangeEvent : com::sun::star::lang::EventObject { 

    string PropertyName;

    boolean Further;

    long PropertyHandle;

    any OldValue;

    any NewValue;

}; 

A new feature of OpenOffice.org 2.0 is the polymorphic struct type. A polymorphic struct type template is similar to a plain struct type, but it has one or more type parameters, and its members can have these parameters as types. A polymorphic struct type template is not itself a UNO type—it has to be instantiated with actual type arguments to be used as a type.

// A polymorphic struct type template with two type parameters:
struct Poly<T,U> {

    T member1;

    T member2;

    U member3;

    long member4;

}; 

 

// Using an instantiation of Poly as a UNO type:
interface XIfc { Poly<boolean, any> fn(); };

In the example, Poly<boolean, any> will be an instantiated polymorphic struct type with the same form as the plain struct type

struct PolyBooleanAny {
   boolean member1;

    boolean member2;

    any member3;

    long member4;
};

Polymorphic struct types were added primarily to support rich interface type attributes that are as expressive as maybeambiguous, maybedefault, or maybevoid properties (see com.sun.star.beans.Ambiguous, com.sun.star.beans.Defaulted, com.sun.star.beans.Optional), but they are probably useful in other contexts, too.

Predefined Values

The API offers many predefined values, that are used as method parameters, or returned by methods. In UNO IDL there are two different data types for predefined values: constants and enumerations. 

const

A const defines a named value of a valid UNO IDL type. The value depends on the specified type and can be a literal (integer number, floating point number or a character), an identifier of another const type or an arithmetic term using the operators: +, -, *, /, ~, &, |, %, ^, <<, >>.

Since a wide selection of types and values is possible in a const, const is occasionally used to build bit vectors which encode combined values. 

const short ID = 23; 

const boolean ERROR = true; 

const double PI = 3.1415; 

Usually const definitions are part of a constants group. 

constants

The constants type defines a named group of const values. A const in a constants group is denoted by the group name and the const name. In the UNO IDL example below, ImageAlign.RIGHT refers to the value 2:

constants ImageAlign { 

    const short LEFT = 0;

    const short TOP = 1;

    const short RIGHT = 2;

    const short BOTTOM = 3;

}; 

enum

An enum type is equivalent to an enumeration type in C++. It contains an ordered list of one or more identifiers representing long values of the enum type. By default, the values are numbered sequentially, beginning with 0 and adding 1 for each new value. If an enum value has been assigned a value, all following enum values without a predefined value get a value starting from this assigned value.

// com.sun.star.uno.TypeClass 

enum TypeClass { 

    VOID,

    CHAR,

    BOOLEAN,

    BYTE,

    SHORT,

    ...

}; 

 

enum Error { 

    SYSTEM = 10, // value 10

    RUNTIME,     // value 11

    FATAL,       // value 12

    USER = 30,   // value 30

    SOFT         // value 31

}; 

If enums are used during debugging, you should be able to derive the numeric value of an enum by counting its position in the API reference. However, never use literal numeric values instead of enums in your programs. 

Pay attention to the following important text section

Once an enum type has been specified and published, you can trust that it is not extended later on, for that would break existing code. However, new const vaues may be added to a constant group. 

Sequences

A sequence type is a set of elements of the same type, that has a variable number of elements. In UNO IDL, the used element always references an existing and known type or another sequence type. A sequence can occur as a normal type in all other type definitions.

sequence< com::sun::star::uno::XInterface > 

sequence< string > getNamesOfIndex( sequence< long > indexes ); 

Modules

Modules are namespaces, similar to namespaces in C++ or packages in Java. They group services, interfaces, structs, exceptions, enums, typedefs, constant groups and submodules with related functional content or behavior. They are utilized to specify coherent blocks in the API, this allows for a well-structured API. For example, the module com.sun.star.text contains interfaces and other types for text handling. Some other typical modules are com.sun.star.uno, com.sun.star.drawing, com.sun.star.sheet and com.sun.star.table. Identifiers inside a module do not clash with identifiers in other modules, therefore it is possible for the same name to occur more than once. The global index of the API reference shows that this does happen.

Although it may seem that the modules correspond with the various parts of OpenOffice.org, there is no direct relationship between the API modules and the OpenOffice.org applications Writer, Calc and Draw. Interfaces from the module com.sun.star.text are used in Calc and Draw. Modules like com.sun.star.style or com.sun.star.document provide generic services and interfaces that are not specific to any one part of OpenOffice.org.

The modules you see in the API reference were defined by nesting UNO IDL types in module instructions. For example, the module com.sun.star.uno contains the interface XInterface:

module com { 

    module sun {

        module star {

            module uno {

                interface XInterface {

                    ...

                };

            };

        };

    };

}; 

Exceptions

An exception type indicates an error to the caller of a function. The type of an exception gives a basic description of the kind of error that occurred. In addition, the UNO IDL exception types contain elements which allow for an exact specification and a detailed description of the error. The exception type supports inheritance, this is freqzuently used to define a hierarchy of errors. Exceptions are only used to raise errors, not  as method parameters or return types.

UNO IDL requires that all exceptions must inherit from com.sun.star.uno.Exception. This is a precondition for the UNO runtime.

// com.sun.star.uno.Exception is the base exception for all exceptions 

exception Exception { 

    string Message;

    Xinterface Context;

}; 

 

// com.sun.star.uno.RuntimeException is the base exception for serious problems 

// occuring at runtime, usually programming errors or problems in the runtime environment 

exception RuntimeException : com::sun::star::uno::Exception { 

}; 

 

// com.sun.star.uno.SecurityException is a more specific RuntimeException  

exception SecurityException : com::sun::star::uno::RuntimeException { 

}; 

Exceptions may only be thrown by operations which were specified to do so. In contrast, com.sun.star.uno.RuntimeExceptions can always occur.

Pay attention to the following important text section

The methods acquire() and release of the UNO base interface com.sun.star.uno.XInterface are an exception to the above rule. They are the only operations that may not even throw runtime exceptions. But in Java and C++ programs, you do not use these methods directly, they are handled by the respective language binding.

Singletons

Singletons are used to specify named objects where exactly one instance can exist in the life of a UNO component context. A singleton references one interface type and specifies that the only existing instance of this singleton can be reached over the component context using the name of the singleton. If no instance of the singleton exists, the component context will instantiate a new one. An example of such a new-style singleton is

module com { module sun { module star { module deployment {
singleton thePackageManagerFactory: XPackageManagerFactory;
}; }; }; };

The various language bindings offer language-specific ways to obtain the instance of a new-style singleton, given a component context. For example, in Java and C++ there is a static method (resp. function) named get, that takes as its only argument an XComponentContext and returns the (appropriately typed) singleton instance. If the instance cannot be obtained, a com.sun.star.uno.DeploymentException is thrown.

There are also old-style singletons, which reference (old-style) services instead of interfaces. However, for old-style services, the language bindings offer no get functionality.

3.2.2  Understanding the API Reference

Specification, Implementation and Instances

The API specifications you find in the API reference are abstract. The service descriptions of the API reference are not about classes that previously exist somewhere. The specifications are first, then the UNO implementation is created according to the specification. That holds true even for legacy implementations that had to be adapted to UNO. 

Moreover, since a component developer is free to implement services and interfaces as required, there is not necessarily a one-to-one relationship between a certain service specification and a real object. The real object can be capable of more things than specified in a service definition. For example, if you order a service at the factory or receive an object from a getter or getPropertyValue() method, the specified features will be present, but there may be additional features. For instance, the text document model has a few interfaces which are not included in the specification for the com.sun.star.text.TextDocument.

Because of the optional interfaces and properties, it is impossible to comprehend fully from the API reference what a given instance of an object in OpenOffice.org is capable of. The optional interfaces and properties are correct for an abstract specification, but it means that when you leave the scope of mandatory interfaces and properties, the reference only defines how things are allowed to work, not how they actually work.  

Another important point is the fact that there are several entry points where object implementations are actually available. You cannot instantiate every old-style service that can be found in the API reference by means of the global service manager. The reasons are: 

In the first and the last case above, using multiple-inheritance interface types instead of old-style services would have been the right design choice, but the mentioned services predate the availability of multiple-inheritance interface types in UNO. 

Consequently, it is sometimes confusing to look up a needed functionality in the API reference, for you need a basic understanding how a functionality works, which services are involved, where they are available etc., before you can really utilize the reference. This manual aims at giving you this understanding about the OpenOffice.org document models, the database integration and the application itself. 

Object Composition

Interfaces support single and multiple inheritance, and they are all based on com.sun.star.uno.XInterface. In the API reference, this is mirrored in the Base Hierarchy section of any interface specification. If you look up an interface, always check the base hierarchy section to understand the full range of supported methods. For instance, if you look up com.sun.star.text.XText, you see two methods, insertTextContent() and removeTextContent(), but  there are nine more methods provided by the inherited interfaces. The same applies to exceptions and sometimes also to structs, which support single inheritance as well.

The service specifications in the API reference can contain a section  Included Services , which is similar to the above in that a single included old-style service might encompass a whole world of services. However, the fact that a service is included has nothing to do with class inheritance. In which manner a service implementation technically includes other services, by inheriting from base implementations, by aggregation, some other kind of delegation or simply by re-implementing everything is by no means defined (which it is not, either, for UNO interface inheritance). And it is uninteresting for an API user – he can absolutely rely on the availability of the described functionality, but he must never rely on inner details of the implementation, which classes provide the functionality, where they inherit from and what they delegate to other classes.

3.3  UNO Concepts

Now that you have an advanced understanding of OpenOffice.org API concepts and you understand the specification of UNO objects, we are ready to explore UNO, i.e. to see how UNO objects connect and communicate with each other. 

3.3.1  UNO Interprocess Connections

UNO objects in different environments connect via the interprocess bridge. You can execute calls on UNO object instances, that are located in a different process. This is done by converting the method name and the arguments into a byte stream representation, and sending this package to the remote process, for example, through a socket connection. Most of the examples in this manual use the interprocess bridge to communicate with the OpenOffice.org.      

This section deals with the creation of UNO interprocess connections using the UNO API. 

Starting OpenOffice.org in Listening Mode

Most examples in this developers guide connect to a running OpenOffice.org and perform API calls, which are then executed in OpenOffice.org. By default, the office does not listen on a resource for security reasons. This makes it necessary to make OpenOffice.org listen on an interprocess connection resource, for example, a socket. Currently this can be done in two ways: 

Choose the procedure that suits your requirements and launch OpenOffice.org in listening mode now. Check if it is listening by calling netstat -a or -na on the command-line. An output similar to the following shows that the office is listening:

TCP    <Hostname>:8100   <Fully qualified hostname>: 0 Listening

If you use the -n option, netstat displays addresses and port numbers in numerical form. This is sometimes useful on UNIX systems where it is possible to assign logical names to ports.

If the office is not listening, it probably was not started with the proper connection URL parameter. Check the Setup.xcu file or your command-line for typing errors and try again.

Note graphics marks a special text section

Note: In versions before OpenOffice.org 1.1.0, there are several differences.  

The configuration setting that makes the office listen everytime is located elsewhere. Open the file <OfficePath>/share/config/registry/instance/org/openoffice/Setup.xml in an editor, and look for the element:

<ooSetupConnectionURL cfg:type="string"/>  

Extend it with the following code: 

<ooSetupConnectionURL cfg:type="string">
socket,port=2083;urp;
</ooSetupConnectionURL>

The commandline option -accept is ignored when there is a running instance of the office, including the quick starter and the online help. If you use it, make sure that no soffice process runs on your system.

The various parts of the connection URL will be discussed in the next section. 

Importing a UNO Object

The most common use case of interprocess connections is to import a reference to a UNO object from an exporting server. For instance, most of the Java examples described in this manual retrieve a reference to the OpenOffice.org ComponentContext. The correct way to do this is using the com.sun.star.bridge.UnoUrlResolver service. Its main interface com.sun.star.bridge.XUnoUrlResolver is defined in the following way:

interface XUnoUrlResolver: com::sun::star::uno::XInterface 

{
   /** resolves an object on the UNO URL */
   com::sun::star::uno::XInterface resolve( [in] string sUnoUrl )
       raises (com::sun::star::connection::NoConnectException,
               com::sun::star::connection::ConnectionSetupException,
               com::sun::star::lang::IllegalArgumentException);
};

The string passed to the resolve() method is called a UNO URL. It must have the following format:

Graphic showing an UNO Url scheme

An example URL could be uno:socket,host=localhost,port=2002;urp;StarOffice.ServiceManager. The parts of this URL are:

  1. The URL schema uno:. This identifies the URL as UNO URL and distinguishes it from others, such as http: or ftp: URLs.

  2. A string which characterizes the type of connection to be used to access the other process. Optionally, directly after this string, a comma separated list of name-value pairs can follow, where name and value are separated by a '='. The currently supported connection types are described in 3.3.1 Professional UNO - UNO Concepts - UNO Interprocess Connections - Opening a Connection. The connection type specifies the transport mechanism used to transfer a byte stream, for example, TCP/IP sockets or named pipes.

  3. A string which characterizes the type of protocol used to communicate over the established byte stream connection. The string can be followed by a comma separated list of name-value pairs, which can be used to customize the protocol to specific needs. The suggested protocol is urp (UNO Remote Protocol). Some useful parameters are explained below. Refer to the document named UNO-URL at udk.openoffice.org. for the complete specification.

  4. A process must explicitly export a certain object by a distinct name. It is not possible to access an arbitrary UNO object (which would be possible with IOR in CORBA, for instance).

The following example demonstrates how to import an object using the UnoUrlResolver: (ProfUNO/InterprocessConn/UrlResolver.java):

    XComponentContext xLocalContext =

        com.sun.star.comp.helper.Bootstrap.createInitialComponentContext(null);

       

    // initial serviceManager

    XMultiComponentFactory xLocalServiceManager = xLocalContext.getServiceManager();

               

    // create a URL resolver

    Object urlResolver = xLocalServiceManager.createInstanceWithContext(

        "com.sun.star.bridge.UnoUrlResolver", xLocalContext);

 

    // query for the XUnoUrlResolver interface

    XUnoUrlResolver xUrlResolver =

        (XUnoUrlResolver) UnoRuntime.queryInterface(XUnoUrlResolver.class, urlResolver);

 

    // Import the object

    Object rInitialObject = xUrlResolver.resolve(

        “uno:socket,host=localhost,port=2002;urp;StarOffice.ServiceManager”);

           

    // XComponentContext

    if (null != rInitialObject) {

        System.out.println("initial object successfully retrieved");

    } else {

        System.out.println("given initial-object name unknown at server side");

    }

The usage of the UnoUrlResolver has certain disadvantages. You cannot:

These issues are addressed by the underlying API, which is explained below. in 3.3.1 Professional UNO - UNO Concepts - UNO Interprocess Connections - Opening a Connection.

Characteristics of the Interprocess Bridge

The whole bridge is threadsafe and allows multiple threads to execute remote calls. The dispatcher thread inside the bridge cannot block because it never executes calls. It instead passes the requests to worker threads.

 

Pay attention to the following important text section

Although there are no general problems with the specification and the implementation of the UNO oneway feature, there are several API remote usage scenarios where oneway calls cause deadlocks in OpenOffice.org. Therefore do not introduce new oneway methods with new OpenOffice.org UNO APIs.

For synchronous requests, thread identity is guaranteed. When process A calls process B, and process B calls process A, the same thread waiting in process A will take over the new request. This avoids deadlocks when the same mutex is locked again. For asynchronous requests, this is not possible because there is no thread waiting in process A. Such requests are executed in a new thread. The series of calls between two processes is guaranteed. If two asynchronous requests from process A are sent to process B, the second request waits until the first request is finished.

Although the remote bridge supports asynchronous calls, this feature is disabled by default. Every call is executed synchronously. The oneway flag of UNO interface methods is ignored. However, the bridge can be started in a mode that enables the oneway feature and thus executes calls flagged with the [oneway] modifier as  asynchronous calls. To do this, the protocol part of the connection string on both sides of the remote bridge must be extended by ',Negotiate=0,ForceSynchronous=0' . For example:

soffice “-accept=socket,host=0,port=2002;urp,Negotiate=0,ForceSynchronous=0;”

for starting the office and  

"uno:socket,host=localhost,port=2002;urp,Negotiate=0,ForceSynchronous=0;StarOffice.ServiceManager"

as UNO URL for connecting to it.  

Pay attention to the following important text section

The asynchronous mode can cause deadlocks in OpenOffice.org. It is recommended not to activate it if one side of the remote bridge is OpenOffice.org. 

Opening a Connection

The method to import a UNO object using the UnoUrlResolver has drawbacks as described in the previous chapter. The layer below the UnoUrlResolver offers full flexibility in interprocess connection handling.

UNO interprocess bridges are established on the com.sun.star.connection.XConnection interface, which encapsulates a reliable bidirectional byte stream connection (such as a TCP/IP connection).

interface XConnection: com::sun::star::uno::XInterface 

{  

    long read( [out] sequence < byte > aReadBytes , [in] long nBytesToRead )

                raises( com::sun::star::io::IOException );

    void write( [in] sequence < byte > aData )

                raises( com::sun::star::io::IOException );

    void flush( ) raises( com::sun::star::io::IOException );

    void close( ) raises( com::sun::star::io::IOException );

    string getDescription();

}; 

There are different mechanisms to establish an interprocess connection. Most of these mechanisms follow a similar pattern. One process listens on a resource and waits for one or more processes to connect to this resource. 

This pattern has been abstracted by the services com.sun.star.connection.Acceptor that exports the com.sun.star.connection.XAcceptor interface and com.sun.star.connection.Connector that exports the com.sun.star.connection.XConnector interface.

interface XAcceptor: com::sun::star::uno::XInterface 

{  

    XConnection accept( [in] string sConnectionDescription )

                raises( AlreadyAcceptingException,

                ConnectionSetupException,

                com::sun::star::lang::IllegalArgumentException);

 

    void stopAccepting();

};  

 

interface XConnector: com::sun::star::uno::XInterface 

{  

    XConnection connect( [in] string sConnectionDescription )

                raises( NoConnectException,ConnectionSetupException );

};  

The acceptor service is used in the listening process while the connector service is used in the actively connecting service. The methods accept() and connect() get the connection string as a parameter. This is the connection part of the UNO URL (between uno: and ;urp).

The connection string consists of a connection type followed by a comma separated list of name-value pairs. The following table shows the connection types that are supported by default. 

Connection type 

 

socket 

Reliable TCP/IP socket connection 

Parameter 

Description 

host 

Hostname or IP number of the resource to listen on/connect. May be localhost. In an acceptor string, this may be 0 ('host=0'), which means, that it accepts on all available network interfaces.

port 

TCP/IP port number to listen on/connect to. 

tcpNoDelay 

Corresponds to the socket option tcpNoDelay. For a UNO connection, this parameter should be set to 1 (this is NOT the default it must be added explicitly). If the default is used (0), it may come to 200 ms delays at certain call combinations.

pipe 

A named pipe (uses shared memory). This type of interprocess connection is marginally faster than socket connections and works only if both processes are located on the same machine. It does not work on Java by default, because Java does not support named pipes directly 

Parameter 

Description 

name 

Name of the named pipe. Can only accept one process on name on one machine at a time. 

Tip graphics marks a hint section in the text

You can add more kinds of interprocess connections by implementing connector and acceptor services, and choosing the service name by the scheme com.sun.star.connection.Connector.<connection-type>, where <connection-type> is the name of the new connection type.

If you implemented the service com.sun.star.connection.Connector.mytype, use the UnoUrlResolver with the URL 'uno:mytype,param1=foo;urp;StarOffice.ServiceManager' to establish the interprocess connection to the office.

Creating the Bridge

UML diagram showing the initiaton of a brdigeIllustration 3.5: The interaction of services that are needed to initiate a UNO interprocess bridge. The interfaces have been simplified.

The XConnection instance can now be used to establish a UNO interprocess bridge on top of the connection, regardless if the connection was established with a Connector or Acceptor service (or another method). To do this, you must instantiate the service com.sun.star.bridge.BridgeFactory. It supports the com.sun.star.bridge.XBridgeFactory interface.

interface XBridgeFactory: com::sun::star::uno::XInterface 

{  

    XBridge createBridge(

            [in] string sName,

            [in] string sProtocol ,

            [in] com::sun::star::connection::XConnection aConnection ,

            [in] XInstanceProvider anInstanceProvider )

        raises ( BridgeExistsException , com::sun::star::lang::IllegalArgumentException );

    XBridge getBridge( [in] string  sName );

    sequence < XBridge > getExistingBridges( );

};  

The BridgeFactory service administrates all UNO interprocess connections. The createBridge() method creates a new bridge:

interface XInstanceProvider: com::sun::star::uno::XInterface 

{  

    com::sun::star::uno::XInterface getInstance( [in] string sInstanceName )

                raises ( com::sun::star::container::NoSuchElementException );

};  

The BridgeFactory returns a com.sun.star.bridge.XBridge interface.

interface XBridge: com::sun::star::uno::XInterface 

{  

    XInterface getInstance( [in] string sInstanceName );

    string getName();

    string getDescription();

};  

The XBridge.getInstance() method retrieves an initial object from the remote counterpart. The local XBridge.getInstance() call arrives in the remote process as an XInstanceProvider.getInstance() call. The object returned can be controlled by the string sInstanceName. It completely depends on the implementation of XInstanceProvider, which object it returns.

The XBridge interface can be queried for a com.sun.star.lang.XComponent interface, that adds a com.sun.star.lang.XEventListener to the bridge. This listener will be terminated when the underlying connection closes (see above). You can also call dispose() on the XComponent interface explicitly, which closes the underlying connection and initiates the bridge shutdown procedure.

Closing a Connection

The closure of an interprocess connection can occur for the following reasons: 

Except for the first reason, all other connection closures initiate an interprocess bridge shutdown procedure. All pending synchronous requests abort with a com.sun.star.lang.DisposedException, which is derived from the com.sun.star.uno.RuntimeException. Every call that is initiated on a disposed proxy throws a DisposedException. After all threads have left the bridge (there may be a synchronous call from the former remote counterpart in the process), the bridge explicitly releases all stubs to the original objects in the local process, which were previously held by the former remote counterpart. The bridge then notifies all registered listeners about the disposed state using com.sun.star.lang.XEventListener. The example code for a connection-aware client below shows how to use this mechanism. The bridge itself is destroyed, after the last proxy has been released.

Unfortunately, the various listed error conditions are not distinguishable. 

Example: A Connection Aware Client

The following example shows an advanced client which can be informed about the status of the remote bridge. A complete example for a simple client is given in the chapter 2 First Steps.

The following Java example opens a small awt window containing the buttons new writer and new calc that opens a new document and a status label. It connects to a running office when a button is clicked for the first time. Therefore it uses the connector/bridge factory combination, and registers itself as an event listener at the interprocess bridge.

When the office is terminated, the disposing event is terminated, and the Java program sets the text in the status label to 'disconnected' and clears the office desktop reference. The next time a button is pressed, the program knows that it has to re-establish the connection. 

The method getComponentLoader() retrieves the XComponentLoader reference on demand:

(ProfUNO/InterprocessConn/ConnectionAwareClient.java

    XComponentLoader _officeComponentLoader = null;

 

    // local component context

    XComponentContext _ctx;    

 

    protected com.sun.star.frame.XComponentLoader getComponentLoader()

            throws com.sun.star.uno.Exception {

        XComponentLoader officeComponentLoader = _officeComponentLoader;

 

        if (officeComponentLoader == null) {

            // instantiate connector service

            Object x = _ctx.getServiceManager().createInstanceWithContext(

                "com.sun.star.connection.Connector", _ctx);

           

            XConnector xConnector = (XConnector) UnoRuntime.queryInterface(XConnector.class, x);

 

            // helper function to parse the UNO URL into a string array

            String a[] = parseUnoUrl(_url);

            if (null == a) {

                throw new com.sun.star.uno.Exception("Couldn't parse UNO URL "+ _url);

            }

 

            // connect using the connection string part of the UNO URL only.

            XConnection connection = xConnector.connect(a[0]);

       

            x = _ctx.getServiceManager().createInstanceWithContext(

                "com.sun.star.bridge.BridgeFactory", _ctx);

 

            XBridgeFactory xBridgeFactory = (XBridgeFactory) UnoRuntime.queryInterface(

                XBridgeFactory.class , x);

 

            // create a nameless bridge with no instance provider

            // using the middle part of the UNO URL

            XBridge bridge = xBridgeFactory.createBridge("" , a[1] , connection , null);

 

            // query for the XComponent interface and add this as event listener

            XComponent xComponent = (XComponent) UnoRuntime.queryInterface(

                XComponent.class, bridge);

            xComponent.addEventListener(this);

 

            // get the remote instance

            x = bridge.getInstance(a[2]);

 

            // Did the remote server export this object ?

            if (null == x) {

                throw new com.sun.star.uno.Exception(

                    "Server didn't provide an instance for" + a[2], null);

            }

     

            // Query the initial object for its main factory interface

            XMultiComponentFactory xOfficeMultiComponentFactory = (XMultiComponentFactory)

                UnoRuntime.queryInterface(XMultiComponentFactory.class, x);

 

            // retrieve the component context (it's not yet exported from the office)

            // Query for the XPropertySet interface.

            XPropertySet xProperySet = (XPropertySet)

                UnoRuntime.queryInterface(XPropertySet.class, xOfficeMultiComponentFactory);

           

            // Get the default context from the office server.

            Object oDefaultContext =

                xProperySet.getPropertyValue("DefaultContext");

           

            // Query for the interface XComponentContext.

            XComponentContext xOfficeComponentContext =

                (XComponentContext) UnoRuntime.queryInterface(

                    XComponentContext.class, oDefaultContext);

 

           

            // now create the desktop service

            // NOTE: use the office component context here !

            Object oDesktop = xOfficeMultiComponentFactory.createInstanceWithContext(

                "com.sun.star.frame.Desktop", xOfficeComponentContext);

 

            officeComponentLoader = (XComponentLoader)

                UnoRuntime.queryInterface( XComponentLoader.class, oDesktop);

 

            if (officeComponentLoader == null) {

                throw new com.sun.star.uno.Exception(

                    "Couldn't instantiate com.sun.star.frame.Desktop" , null);

            }

            _officeComponentLoader = officeComponentLoader;

        }

        return officeComponentLoader;

    }

This is the button event handler: 

    public void actionPerformed(ActionEvent event) {

        try {

            String sUrl;

            if (event.getSource() == _btnWriter) {

                sUrl = "private:factory/swriter";

            } else {

                sUrl = "private:factory/scalc";

            }

            getComponentLoader().loadComponentFromURL(

                sUrl, "_blank", 0,new com.sun.star.beans.PropertyValue[0]);

            _txtLabel.setText("connected");

        } catch (com.sun.star.connection.NoConnectException exc) {

            _txtLabel.setText(exc.getMessage());

        } catch (com.sun.star.uno.Exception exc) {

            _txtLabel.setText(exc.getMessage());

            exc.printStackTrace();

            throw new java.lang.RuntimeException(exc.getMessage());

        }

    }

And the disposing handler clears the _officeComponentLoader reference:

    public void disposing(com.sun.star.lang.EventObject event) {

        // remote bridge has gone down, because the office crashed or was terminated.

        _officeComponentLoader = null;

        _txtLabel.setText("disconnected");

    }

3.3.2  Service Manager and Component Context

This chapter discusses the root object for connections to OpenOffice.org (and to any UNO application) – the service manager. The root object serves as the entry point for every UNO application and is passed to every UNO component during instantiation.

Two different concepts to get the root object currently exist. StarOffice6.0 and OpenOffice.org1.0 use the previous concept. Newer versions or product patches use the newer concept and provide the previous concept for compatibility issues only. First we will look at the previous concept, the service manager as it is used in the main parts of the underlying OpenOffice.org implementation of this guide. Second, we will introduce the component context—which is the newer concept and explain the migration path.

Service Manager

The com.sun.star.lang.ServiceManager is the main factory in every UNO application. It instantiates services by their service name, to enumerate all implementations of a certain service, and to add or remove factories for a certain service at runtime. The service manager is passed to every UNO component during instantiation.

XMultiServiceFactory Interface

The main interface of the service manager is the com.sun.star.lang.XMultiServiceFactory interface. It offers three methods: createInstance(), createInstanceWithArguments() and getAvailableServiceNames().

interface XMultiServiceFactory: com::sun::star::uno::XInterface 

{  

    com::sun::star::uno::XInterface createInstance( [in] string aServiceSpecifier )

        raises( com::sun::star::uno::Exception );

 

    com::sun::star::uno::XInterface createInstanceWithArguments(

            [in] string ServiceSpecifier,

            [in] sequence<any> Arguments )

        raises( com::sun::star::uno::Exception );

 

    sequence<string> getAvailableServiceNames();

};  

When using the service name, the caller does not have any influence on which concrete implementation is instantiated. If multiple implementations for a service exist, the service manager is free to decide which one to employ. This in general does not make a difference to the caller because every implementation does fulfill the service contract. Performance or other details may make a difference. So it is also possible to pass the implementation name instead of the service name, but it is not advised to do so as the implementation name may change.

In case the service manager does not provide an implementation for a request, a null reference is returned, so it is mandatory to check. Every UNO exception may be thrown during instantiation. Some may be described in the specification of the service that is to be instantiated, for instance, because of a misconfiguration of the concrete implementation. Another reason may be the lack of a certain bridge, for instance the Java-C++ bridge, in case a Java component shall be instantiated from C++ code. 

XContentEnumerationAccess Interface

The com.sun.star.container.XContentEnumerationAccess interface allows the creation of an enumeration of all implementations of a concrete servicename.

interface XContentEnumerationAccess: com::sun::star::uno::XInterface 

{  

    com::sun::star::container::XEnumeration createContentEnumeration( [in] string aServiceName );

 

    sequence<string> getAvailableServiceNames();

 

};  

The createContentEnumeration() method returns a com.sun.star.container.XEnumeration interface. Note that it may return an empty reference in case the enumeration is empty.

interface XEnumeration: com::sun::star::uno::XInterface 

{  

    boolean hasMoreElements();

 

    any nextElement()

        raises( com::sun::star::container::NoSuchElementException,

                com::sun::star::lang::WrappedTargetException );

 

};  

In the above case, the returned any of the method Xenumeration.nextElement() contains a com.sun.star.lang.XSingleServiceFactory interface for each implementation of this specific service. You can, for instance, iterate over all implementations of a certain service and check each one for additional implemented services. The XSingleServiceFactory interface provides such a method. With this method, you can instantiate a feature rich implementation of a service.

XSet Interface

The com.sun.star.container.XSet interface allows the insertion or removal of com.sun.star.lang.XSingleServiceFactory or com.sun.star.lang.XSingleComponentFactory implementations to the service manager at runtime without making the changes permanent. When the office application terminates, all the changes are lost. The object must also support the com.sun.star.lang.XServiceInfo interface that provides information about the implementation name and supported services of the component implementation.

This feature may be of particular interest during the development phase. For instance, you can connect to a running office, insert a new factory into the service manager and directly instantiate the new service without having it registered before. 

The chapter 4.9.6 Writing UNO Components - Deployment Options for Components - Special Service Manager Configurations shows an example that demonstrates how a factory is inserted into the service manager.

Component Context

The service manager was described above as the main factory that is passed to every new instantiated component. Often a component needs more functionality or information that must be exchangeable after deployment of an application. In this context, the service manager approach is limited. 

Therefore, the concept of the component context was created. In future, it will be the central object in every UNO application. It is basically a read-only container offering named values. One of the named values is the service manager. The component context is passed to a component during its instantiation. This can be understood as an environment where components live (the relationship is similar to shell environment variables and an executable program).

UML diagram showing an CompoenntContextIllustration 3.6: ComponentContext and the ServiceManager
ComponentContext API

The component context only supports the com.sun.star.uno.XComponentContext interface.

// module com::sun::star::uno 

interface XComponentContext : XInterface 

    any getValueByName( [in] string Name );

    com::sun::star::lang::XMultiComponentFactory getServiceManager();

}; 

The getValueByName() method returns a named value. The getServiceManager() is a convenient way to retrieve the value named /singleton/com.sun.star.lang.theServiceManager. It returns the ServiceManager singleton, because most components need to access the service manager. The component context offers at least three kinds of named values:

Singletons (/singletons/...) 

The singleton concept was introduced in 3.2.1 Professional UNO - API Concepts - Data Types. In OpenOffice.org 1.0.2 there is only the ServiceManager singleton. From OpenOffice.org 1.1.0, a singleton  /singletons/com.sun.star.util.theMacroExpander has been added, which can be used to expand macros in configuration files. Other possible singletons can be found in the IDL reference.

Implementation properties (not yet defined) 

These properties customize a certain implementation and are specified in the module description of each component. A module description is an xml-based description of a module (DLL or jar file) which contains the formal description of one or more components. 

Service properties (not yet defined) 

These properties can customize a certain service independent from the implementation and are specified in the IDL specification of a service.
Note that service context properties are different from service properties. Service context properties are not subject to change and are the same for every instance of the service that shares the same component context. Service properties are different for each instance and can be changed at runtime through the XPropertySet interface.

Note, that in the scheme above, the ComponentContext has a reference to the service manager, but not conversely.

Besides the interfaces discussed above, the ServiceManager supports the com.sun.star.lang.XMultiComponentFactory interface.

interface XMultiComponentFactory : com::sun::star::uno::XInterface 

{  

        com::sun::star::uno::XInterface createInstanceWithContext(

                        [in] string aServiceSpecifier,

                        [in] com::sun::star::uno::XComponentContext Context )

                        raises (com::sun::star::uno::Exception);

   

        com::sun::star::uno::XInterface createInstanceWithArgumentsAndContext(

                        [in] string ServiceSpecifier,

                        [in] sequence<any> Arguments,

                        [in] com::sun::star::uno::XComponentContext Context )

                        raises (com::sun::star::uno::Exception);

   

        sequence< string > getAvailableServiceNames();

};  

It replaces the XMultiServiceFactory interface. It has an additional XComponentContext parameter for the two object creation methods. This parameter enables the caller to define the component context that the new instance of the component receives. Most components use their initial component context to instantiate new components. This allows for context propagation.

Context propagationIllustration 3.7: Context propagation.

The illustration above shows the context propagation. A user might want a special component to get a customized context. Therefore, the user creates a new context by simply wrapping an existing one. The user overrides the desired values and delegates the properties that he is not interested into the original C1 context.The user defines which context Instance A and B receive. Instance A and B  propagate their context to every new object that they create. Thus, the user has established two instance trees, the first tree completely uses the context Ctx C1, while the second tree uses Ctx C2.

Availability

The final API for the component context is available in StarOffice 6.0 and OpenOffice 1.0. Use this API instead of the API explained in the service manager section. Currently the component context does not have a persistent storage, so named values can not be added to the context of a deployed OpenOffice.org. Presently, there is no additional benefit from the new API until there is a future release. 

Compatibility Issues and Migration Path
Relation between service manager and component contextIllustration 3.8Compromise between service-manger-only und component context concept

As discussed previously, both concepts are currently used within the office. The ServiceManager supports the interfaces com.sun.star.lang.XMultiServiceFactory and com.sun.star.lang.XMultiComponentFactory. Calls to the XMultiServiceFactory interface are delegated to the XMultiComponentFactory interface. The service manager uses its own XComponentContext reference to fill the missing parameter. The component context of the ServiceManager can be retrieved through the XPropertySet interface as 'DefaultContext'.

// Query for the XPropertySet interface. 

// Note xOfficeServiceManager is the object retrieved by the  

// UNO URL resolver  

XPropertySet xPropertySet = (XPropertySet) 

        UnoRuntime.queryInterface(XPropertySet.class, xOfficeServiceManager);

               

// Get the default context from the office server. 

Object oDefaultContext = xpropertysetMultiComponentFactory.getPropertyValue("DefaultContext"); 

               

// Query for the interface XComponentContext. 

xComponentContext = (XComponentContext) UnoRuntime.queryInterface( 

        XComponentContext.class, objectDefaultContext);

This solution allows the use of the same service manager instance, regardless if it uses the old or  new style API. In future, the whole OpenOffice.org code will only use the new API. However, the old API will still remain to ensure compatibility.

Note graphics marks a special text section

The described compromise has a drawback. The service manager now knows the component context, that was not necessary in the original design. Thus, every component that uses the old API (plain createInstance()) breaks the context propagation (see Illustration 3.7). Therefore, it is recommended to use the new API in every new piece of code that is written.

3.3.3  Using UNO Interfaces

Every UNO object must inherit from the interface com.sun.star.uno.XInterface. Before using an object, know how to use it and how long it will function. By prescribing XInterface to be the base interface for each and every UNO interface, UNO lays the groundwork for object communication. For historic reasons, the UNOIDL description of XInterface lists the functionality that is associated with XInterface in the C++ (or binary UNO) language binding; other language bindings offer similar functionality by different mechanisms:

// module com::sun::star::uno 

interface XInterface 

    any queryInterface( [in] type aType );

    [oneway] void acquire();

    [oneway] void release();

};  

The methods acquire() and release() handle the lifetime of the UNO object by reference counting. Detailed information about Reference counting is discussed in chapter 3.3.8 Professional UNO - UNO Concepts - Lifetime of UNO Objects. All current language bindings take care of acquire() and release() internally whenever there is a reference to a UNO object.

The queryInterface() method obtains other interfaces exported by the object. The caller asks the implementation of the object if it supports the interface specified by the type argument. The type parameter must denote a UNO interface type. The call may return with an interface reference of the requested type or with a void any. In C++ or Java simply test if the result is not equal null.

Unknowingly, we encountered XInterface when the service manager was asked to create a service instance:

    XComponentContext xLocalContext =

        com.sun.star.comp.helper.Bootstrap.createInitialComponentContext(null);

       

    // initial serviceManager

    XMultiComponentFactory xLocalServiceManager = xLocalContext.getServiceManager();

               

    // create a urlresolver

    Object urlResolver  = xLocalServiceManager.createInstanceWithContext(

        "com.sun.star.bridge.UnoUrlResolver", xLocalContext);

The IDL specification of XMultiComponentFactory shows:

// module com::sun::star::lang 

interface XMultiComponentFactory : com::sun::star::uno::XInterface 

{  

    com::sun::star::uno::XInterface createInstanceWithContext(

            [in] string aServiceSpecifier,

            [in] com::sun::star::uno::XComponentContext Context )

        raises (com::sun::star::uno::Exception);

    ...

The above code shows that createInstanceWithContext() provides an instance of the given service, but it only returns a com.sun.star.uno.XInterface. This is mapped to java.lang.Object by the Java UNO binding afterwards.

In order to access a service, you need to know which interfaces the service exports. This information is available in the IDL reference. For instance, for the com.sun.star.bridge.UnoUrlResolver service, you learn:

// module com::sun::star::bridge 

service UnoUrlResolver: XUnoUrlResolver; 

This means the service you ordered at the service manager must support com.sun.star.bridge.XUnoUrlResolver. Next query the returned object for this interface:

// query urlResolver for its com.sun.star.bridge.XUnoUrlResolver interface 

XUnoUrlResolver xUrlResolver = (XUnoUrlResolver)  

    UnoRuntime.queryInterface(UnoUrlResolver.class, urlResolver);

 

// test if the interface was available 

if (null == xUrlResolver) { 

    throw new java.lang.Exception(

        “Error: UrlResolver service does not export XUnoUrlResolver interface”);

// use the interface 

Object remoteObject = xUrlResolver.resolve(

    “uno:socket,host=0,port=2002;urp;StarOffice.ServiceManager”);       

 

Note graphics marks a special text section

For a new-style service like com.sun.star.bridge.UnoUrlResolver, there is a superior way to obtain an instance of it, see 3.4.1 Professional UNO - UNO Language Bindings - Java Language Binding - Type Mappings - Mapping of Services and 3.4.2 Professional UNO - UNO Language Bindings - C++ Language Binding - Type Mappings - Mapping of Services.

The object decides whether or not it returns the interface. You have encountered a bug if the object does not return an interface that is specified to be mandatory in a service. When the interface reference is retrieved, invoke a call on the reference according to the interface specification. You can follow this strategy with every service you instantiate at a service manager, leading to success.  

With this method, you may not only get UNO objects through the service manager, but also by normal interface calls: 

// Module com::sun::star::text 

interface XTextRange: com::sun::star::uno::XInterface 

{  

    XText getText();

    XTextRange getStart();

    ....

}; 

The returned interface types are specified in the operations, so that calls can be invoked directly on the returned interface. Often, an object implementing multiple interfaces are returned, instead of an object implementing one certain interface. 

You can then query the returned object for the other interfaces specified in the given old-style service, here com.sun.star.drawing.Text.

UNO has a number of generic interfaces. For example, the interface com.sun.star.frame.XComponentLoader:

// module com::sun::star::frame 

interface XComponentLoader: com::sun::star::uno::XInterface 

    com::sun::star::lang::XComponent loadComponentFromURL( [in] string aURL,

            [in] string aTargetFrameName,

            [in] long nSearchFlags,

            [in] sequence<com::sun::star::beans::PropertyValue> aArgs )

        raises( com::sun::star::io::IOException,

                com::sun::star::lang::IllegalArgumentException );

}; 

It becomes difficult to find which interfaces are supported beside XComponent, because the kind of returned document (text, calc, draw, etc.) depends on the incoming URL.

These dependencies are described in the appropriate chapters of this manual. 

Tools such as the InstanceInspector component is a quick method to find out which interfaces a certain object supports. The InstanceInspector component comes with the OpenOffice.org SDK that allows the inspection of a certain object at runtime. Do not rely on implementation details of certain objects. If an object supports more interfaces than specified in the service description, query the interface and perform calls. The code may only work for this distinct office version and not work with an update of the office!

Note graphics marks a special text section

Unfortunately, there may still be bugs in the service specifications. Please provide feedback about missing interfaces to openoffice.org to ensure that the specification is fixed and that you can rely on the support of this interface.

There are certain specifications a queryInterface() implementation must not violate:

These specifications must not be violated because a UNO runtime environment may choose to cache queryInterface() calls. The rules are basically identical to the rules of QueryInterface in MS COM.

3.3.4  Properties

Properties are name-value pairs belonging to a service and determine the characteristics of an object in a service instance. Usually, properties are used for non-structural attributes, such as font, size or color of objects, whereas get and set methods are used for structural attributes like a parent or sub-object.

In almost all cases, com.sun.star.beans.XPropertySet is used to access properties by name. Other interfaces, for example, are com.sun.star.beans.XPropertyAccess which is used to set and retrieve all properties at once or com.sun.star.beans.XMultiPropertySet which is used to access several specified properties at once. This is useful on remote connections. Additionally, there are interfaces to access properties by numeric ID, such as com.sun.star.beans.XFastPropertySet.

The following example demonstrates how to query and change the properties of a given text document cursor using its XPropertySet interface:

    // get an XPropertySet, here the one of a text cursor

    XPropertySet xCursorProps = (XPropertySet)

            UnoRuntime.queryInterface(XPropertySet.class, mxDocCursor);

 

    // get the character weight property

    Object aCharWeight = xCursorProps.getPropertyValue("CharWeight");

    float fCharWeight = AnyConverter.toFloat(aCharWeight);

    System.out.println("before: CharWeight=" + fCharWeight);

 

    // set the character weight property to BOLD

    xCursorProps.setPropertyValue("CharWeight", new Float(com.sun.star.awt.FontWeight.BOLD));

 

    // get the character weight property again

    aCharWeight = xCursorProps.getPropertyValue("CharWeight");

    fCharWeight = AnyConverter.toFloat(aCharWeight);

    System.out.println("after: CharWeight=" + fCharWeight);

A possible output of this code could be: 

before: CharWeight=100.0 

after: CharWeight=150.0 

Pay attention to the following important text section

The sequence of property names must be sorted. 

The following example deals with multiple properties at once: 

// get an XMultiPropertySet, here the one of the first paragraph 

XEnumerationAccess xEnumAcc = (XEnumerationAccess) UnoRuntime.queryInterface( 

    XEnumerationAccess.class, mxDocText);

XEnumeration xEnum = xEnumAcc.createEnumeration(); 

Object aPara = xEnum.nextElement(); 

XMultiPropertySet xParaProps = (XMultiPropertySet) UnoRuntime.queryInterface( 

    XMultiPropertySet.class, aPara);

 

// get three property values with a single UNO call 

String[] aNames = new String[3]; 

aNames[0] = "CharColor"; 

aNames[1] = "CharFontName"; 

aNames[2] = "CharWeight"; 

Object[] aValues = xParaProps.getPropertyValues(aNames); 

 

// print the three values 

System.out.println("CharColor=" + AnyConverter.toLong(aValues[0])); 

System.out.println("CharFontName=" + AnyConverter.toString(aValues[1])); 

System.out.println("CharWeight=" + AnyConverter.toFloat(aValues[2])); 

Properties can be assigned flags to determine a specific behavior of the property, such as read-only, bound, constrained or void. Possible flags are specified in com.sun.star.beans.PropertyAttribute. Read-only properties cannot be set. Bound properties broadcast changes of their value to registered listeners and constrained properties veto changes to these listeners.

Properties might have a status specifying where the value comes from. See com.sun.star.beans.XPropertyState. The value determines if the value comes from the object, a style sheet or if it cannot be determined at all. For example, in a multi-selection with multiple values within this selection.

The following example shows how to find out status information about property values: 

    // get an XPropertySet, here the one of a text cursor

    XPropertySet xCursorProps = (XPropertySet) UnoRuntime.queryInterface(

        XPropertySet.class, mxDocCursor);

 

    // insert “first” in NORMAL character weight

    mxDocText.insertString(mxDocCursor, "first ", true);

    xCursorProps.setPropertyValue("CharWeight", new Float(com.sun.star.awt.FontWeight.NORMAL));

 

    // append “second” in BODL characer weight

    mxDocCursor.collapseToEnd();

    mxDocText.insertString(mxDocCursor, "second", true);

    xCursorProps.setPropertyValue("CharWeight", new Float(com.sun.star.awt.FontWeight.BOLD));

 

    // try to get the character weight property of BOTH words

    mxDocCursor.gotoStart(true);

    try {

        Object aCharWeight = xCursorProps.getPropertyValue("CharWeight");

        float fCharWeight = AnyConverter.toFloat(aCharWeight );

        System.out.println("CharWeight=" + fCharWeight);

    } catch (NullPointerException e) {

        System.out.println("CharWeight property is NULL");

    }

 

    // query the XPropertState interface of the cursor properties

    XPropertyState xCursorPropsState = (XPropertyState) UnoRuntime.queryInterface(

        XPropertyState.class, xCursorProps);

 

    // get the status of the character weight property

    PropertyState eCharWeightState = xCursorPropsState.getPropertyState("CharWeight");

    System.out.print("CharWeight property state has ");

    if (eCharWeightState == PropertyState.AMBIGUOUS_VALUE)

        System.out.println("an ambiguous value");

    else

        System.out.println("a clear value");

The property state of character weight is queried for a string like this: 

        first second

And the output is: 

CharWeight property is NULL 

CharWeight property state has an ambiguous value 

The description of properties available for a certain object is given by com.sun.star.beans.XPropertySetInfo. Multiple objects can share the same property information for their description. This makes it easier for introspective caches that are used in scripting languages where the properties are accessed directly, without directly calling the methods of the interfaces mentioned above.

This example shows how to find out which properties an object provides using com.sun.star.beans.XPropertySetInfo:

try { 

    // get an XPropertySet, here the one of a text cursor

    XPropertySet xCursorProps = (XPropertySet)UnoRuntime.queryInterface(

        XPropertySet.class, mxDocCursor);

 

    // get the property info interface of this XPropertySet

    XPropertySetInfo xCursorPropsInfo = xCursorProps.getPropertySetInfo();

 

    // get all properties (NOT the values) from XPropertySetInfo

    Property[] aProps = xCursorPropsInfo.getProperties();

    int i;

    for (i = 0; i < aProps.length; ++i) {

        // number of property within this info object

        System.out.print("Property #"  + i);

 

        // name of property

        System.out.print(": Name<" + aProps[i].Name);

 

        // handle of property (only for XFastPropertySet)

        System.out.print("> Handle<" + aProps[i].Handle);

 

        // type of property

        System.out.print("> " + aProps[i].Type.toString());

 

        // attributes (flags)

        System.out.print(" Attributes<");

        short nAttribs = aProps[i].Attributes;

        if ((nAttribs & PropertyAttribute.MAYBEVOID) != 0)

            System.out.print("MAYBEVOID|");

        if ((nAttribs & PropertyAttribute.BOUND) != 0)

        System.out.print("BOUND|");

        if ((nAttribs & PropertyAttribute.CONSTRAINED) != 0)

            System.out.print("CONSTRAINED|");

        if ((nAttribs & PropertyAttribute.READONLY) != 0)

            System.out.print("READONLY|");

        if ((nAttribs & PropertyAttribute.TRANSIENT) != 0)

            System.out.print("TRANSIENT|");

        if ((nAttribs & PropertyAttribute.MAYBEAMBIGUOUS ) != 0)

            System.out.print("MAYBEAMBIGUOUS|");

        if ((nAttribs & PropertyAttribute.MAYBEDEFAULT) != 0)

            System.out.print("MAYBEDEFAULT|");

        if ((nAttribs & PropertyAttribute.REMOVEABLE) != 0)

            System.out.print("REMOVEABLE|");

        System.out.println("0>");

    }

} catch (Exception e) { 

    // If anything goes wrong, give the user a stack trace

    e.printStackTrace(System.out);

The following is an example output for the code above. The output shows the names of the text cursor properties, and their handle, type and property attributes. The handle is not unique, since the specific object does not implement com.sun.star.beans.XFastPropertySet, so proper handles are not needed here. 

Using default connect string: socket,host=localhost,port=8100 

Opening an empty Writer document 

Property #0: Name<BorderDistance> Handle<93> Type<long> Attributes<MAYBEVOID|0> 

Property #1: Name<BottomBorder> Handle<93> Type<com.sun.star.table.BorderLine> Attributes<MAYBEVOID|0> 

Property #2: Name<BottomBorderDistance> Handle<93> Type<long> Attributes<MAYBEVOID|0> 

Property #3: Name<BreakType> Handle<81> Type<com.sun.star.style.BreakType> Attributes<MAYBEVOID|0> 

 

... 

 

Property #133: Name<TopBorderDistance> Handle<93> Type<long> Attributes<MAYBEVOID|0> 

Property #134: Name<UnvisitedCharStyleName> Handle<38> =Type<string> Attributes<MAYBEVOID|0> 

Property #135: Name<VisitedCharStyleName> Handle<38> Type<string> Attributes<MAYBEVOID|0> 

In some cases properties are used to specify the options in a sequence of com.sun.star.beans.PropertyValue. See com.sun.star.view.PrintOptions or com.sun.star.document.MediaDescriptor for examples properties in sequences. These are not accessed by the methods mentioned above, but by accessing the sequence specified in the language binding.

This example illustrates how to deal with sequences of property values: 

// create a sequence of PropertyValue 

PropertyValue[] aArgs = new PropertyValue[2]; 

 

// set name/value pairs (other fields are irrelevant here) 

aArgs[0] = new PropertyValue(); 

aArgs[0].Name = "FilterName"; 

aArgs[0].Value = "HTML (StarWriter)"; 

aArgs[1] = new PropertyValue(); 

aArgs[1].Name = "Overwrite"; 

aArgs[1].Value = Boolean.TRUE; 

 

// use this sequence of PropertyValue as an argument 

// where a service with properties but witouth any interfaces is specified 

com.sun.star.frame.XStorable xStorable = (com.sun.star.frame.XStorable) UnoRuntime.queryInterface( 

    com.sun.star.frame.XStorable.class, mxDoc);

xStorable.storeAsURL("file:///tmp/devmanual-test.html", aArgs); 

Usually the properties supported by an object, as well as their type and flags are fixed over the lifetime of the object. There may be exceptions. If the properties can be added and removed externally, the interface com.sun.star.beans.XPropertyContainer has to be used. In this case, the fixed com.sun.star.beans.XPropertySetInfo changes its supplied information over the lifetime of the object. Listeners for such changes can register at com.sun.star.beans.XPropertyChangeListener.

Tip graphics marks a hint section in the text

If you use a component from other processes or remotely, try to adhere to the rule to use com.sun.star.beans.XPropertyAccess and com.sun.star.beans.XMultiPropertySet instead of having a separate call for each single property.

The following diagram shows the relationship between the property-related interfaces. 

UML diagram showing the relationship of property-related interfacesIllustration 3.9: Properties

Starting with OpenOffice.org 2.0, interface attributes are comparable in expressiveness to the properties described above: 

Interface attributes offer the following advantages compared to properties: 

The main disadvantage is that the set of interface attributes supported by an object is static, so that scenarios that exploit the dynamic nature of XpropertySet, and so on, do not map well to interface attributes. In cases where it might be useful to have all the interface attributes supported by an object also accessible via XPropertySet etc., the Java and C++ language bindings offer experimental, not yet published support to do just that.See www.openoffice.org to find out more.

3.3.5  Collections and Containers

Collections and containers are concepts for objects that contain multiple sub-objects where the number of sub-objects is usually not predetermined. While the term collection is used when the sub-objects are implicitly determined by the collection itself, the term container is used when it is possible to add new sub-objects and remove existing sub-objects explicitly. Thus, containers add methods like insert() and remove() to the collection interfaces.

UML diagram showing the interfaces of  the com.sun.star.conatiner moduleIllustration 3.10: Interfaces in com.sun.star.container

In general, the OpenOffice.org API collection and container interfaces contain any type that can be represented by the UNO type any. However, many container instances can be bound to a specific type or subtypes of this type. This is a runtime and specification agreement, and cannot be checked at runtime.

The base interface for collections is com.sun.star.container.XElementAccess that determines the types of the sub-object, if they are determined by the collection, and the number of contained sub-objects. Based on XElementAccess, there are three main types of collection interfaces:

com.sun.star.container.XIndexAccess is extended by com.sun.star.container.XIndexReplace to replace existing sub-objects by index, and com.sun.star.container.XIndexContainer to insert and remove sub-objects. You can find the same similarity for com.sun.star.container.XNameAccess and other specific collection types.

All containers support com.sun.star.container.XContainer that has interfaces to register com.sun.star.container.XContainerListener interfaces. This way it is possible for an application to learn about insertion and removal of sub-objects in and from the container.

Note graphics marks a special text section

The com.sun.star.container.XIndexAccess is appealing to programmers because in most cases, it is easy to implement. But this interface should only be implemented if the collection really is indexed.

Refer to the module com.sun.star.container in the API reference for details about collection and container interfaces.

The following examples demonstrate the usage of the three main collection interfaces. First, we iterate through an indexed collection. The index always starts with 0 and is continuous: 

// get an XIndexAccess interface from the collection 

XIndexAccess xIndexAccess = (XIndexAccess) UnoRuntime.queryInterface( 

    XIndexAccess.class, mxCollection);

 

// iterate through the collection by index 

int i; 

for (i = 0; i < xIndexAccess.getCount(); ++i) { 

    Object aSheet = xIndexAccess.getByIndex(i);

    Named xSheetNamed = (XNamed) oRuntime.queryInterface(XNamed.class, aSheet);

    System.out.println("sheet #" + i + " is named '" + xSheetNamed.getName() + "'");

Our next example iterates through a collection with named objects. The element names are unique within the collection and case sensitive. 

// get an XNameAccess interface from the collection 

XNameAccess xNameAccess = (XNameAccess) UnoRuntime.queryInterface(XNameAccess.class, mxCollection); 

 

// get the list of names 

String[] aNames = xNameAccess.getElementNames(); 

 

// iterate through the collection by name 

int i; 

for (i = 0; i < aNames.length; ++i) { 

    // get the i-th object as a UNO Any

    Object aSheet = xNameAccess.getByName( aNames[i] );

 

    // get the name of the sheet from its XNamed interface

    XNamed xSheetNamed = (XNamed) UnoRuntime.queryInterface(XNamed.class, aSheet);

    System.out.println("sheet '" + aNames[i] + "' is #" + i);

The next example shows how we iterate through a collection using an enumerator. The order of the enumeration is undefined. It is only defined that all elements are enumerated. The behavior is undefined, if the collection is modified after creation of the enumerator. 

// get an XEnumerationAccess interface from the collection 

XEnumerationAccess xEnumerationAccess = (XEnumerationAccess) UnoRuntime.queryInterface( 

    XEnumerationAccess.class, mxCollection );

 

// create an enumerator 

XEnumeration xEnum = xEnumerationAccess.createEnumeration(); 

 

// iterate through the collection by name 

while (xEnum.hasMoreElements()) { 

    // get the next element as a UNO Any

    Object aSheet = xEnum.nextElement();

 

    // get the name of the sheet from its XNamed interface

    XNamed xSheetNamed = (XNamed) UnoRuntime.queryInterface(XNamed.class, aSheet);

    System.out.println("sheet '" + xSheetNamed.getName() + "'");

For an example showing the use of containers, see 8.4.1 Text Documents - Overall Document Features - Styles where a new style is added into the style family ParagraphStyles.

3.3.6  Event Model

Events are a well known concept in graphical user interface (GUI) models, although they can be used in many contexts. The purpose of events is to notify an application about changes in the components used by the application. In a GUI environment, for example, an event might be the click on a button. Your application might be registered to this button and thus be able to execute certain code when this button is clicked.

The OpenOffice.org event model is similar to the JavaBeans event model. Events in OpenOffice.org are, for example, the creation or activation of a document, as well as the change of the current selection within a view. Applications interested in these events can register handlers (listener interfaces) that are called when the event occurs. Usually these listeners are registered at the object container where the event occurs or to the object itself. These listener interfaces are named X...Listener.

UML diagram showing the relation between listener interfaces and eventsIllustration 3.11

Event listeners are subclasses of com.sun.star.lang.XEventListener that receives one event by itself, the deletion of the object to which the listener is registered. On this event, the listener has to unregister from the object, otherwise it would keep it alive with its interface reference counter.

Pay attention to the following important text section

Important! Implement the method disposing() to unregister at the object you are listening to and release all other references to this object.

Many event listeners can handle several events. If the events are generic, usually a single callback method is used. Otherwise, multiple callback methods are used. These methods are called with at least one argument: com.sun.star.lang.EventObject. This argument specifies the source of the event, therefore, making it possible to register a single event listener to multiple objects and still know where an event is coming from. Advanced listeners might get an extended version of this event descriptor struct.

3.3.7  Exception Handling

UNO uses exceptions as a mechanism to propagate errors from the called method to the caller. This error mechanism is preferred instead of error codes (as in MS COM) to allow a better separation of the error handling code from the code logic. Furthermore, Java, C++ and other high-level programming languages provide an exception handling mechanism, so that this can be mapped easily into these languages.

In IDL, an exception is a structured container for data, comparable to IDL structs. Exceptions cannot be passed as a return value or method argument, because the IDL compiler does not allow this. They can be specified in raise clauses and transported in an any. There are two kinds of exceptions, user-defined exceptions and runtime exceptions.

User-Defined Exceptions

The designer of an interface should declare exceptions for every possible error condition that might occur. Different exceptions can be declared for different conditions to distinguish between different error conditions. 

The implementation may throw the specified exceptions and exceptions derived from the specified exceptions. The implementation must not throw unspecified exceptions, that is, the implementation must not throw an exception if no exception is specified. This applies to all exceptions except for RuntimeExceptions, described later. 

When a user-defined exception is thrown, the object should be left in the state it was in before the call. If this cannot be guaranteed, then the exception specification must describe the state of the object. Note that this is not recommended. 

Every UNO IDL exception must be derived from com.sun.star.uno.Exception, whether directly or indirectly. Its UNO IDL specification looks like this:

module com {  module sun {  module star {  module uno {  

exception Exception 

    string Message;

    com::sun::star::uno::XInterface Context;

};  

}; }; }; }; 

The exception has two members: 

The following .IDL file snippet shows a method with a proper exception specification and proper documentation. 

module com {  module sun {  module star {  module beans {  

 

interface XPropertySet: com::sun::star::uno::XInterface 

    ...

    /** @returns

        the value of the property with the specified name.

                                         

        @param PropertyName      

            This parameter specifies the name of the property.

                         

        @throws UnknownPropertyException        

            if the property does not exist.

                                 

        @throws com::sun::star::uno::lang::WrappedTargetException  

            if the implementation has an internal reason for the

            exception. In this case the original exception

            is wrapped into that WrappedTargetException.

    */

    any getPropertyValue( [in] string PropertyName )

        raises( com::sun::star::beans::UnknownPropertyException,

                com::sun::star::lang::WrappedTargetException );

    ...

};  

 

}; }; }; }; 

Runtime Exceptions

Throwing a runtime exception signals an exceptional state. Runtime exceptions and exceptions derived from runtime exceptions cannot be specified in the raise clause of interface methods in IDL. 

These are a few reasons for throwing a runtime exception are: 

Every UNO call may throw a com.sun.star.uno.RuntimeException, except acquire and release. This is independent of how many calls have been completed successfully. Every caller should ensure that its own object is kept in a consistent state even if a call to another object replied with a runtime exception. The caller should also ensure that no resource leaks occur in these cases. For example, allocated memory, file descriptors, etc.

If a runtime exception occurs, the caller does not know if the call has been completed successfully or not. The com.sun.star.uno.RuntimeException is derived from com.sun.star.uno.Exception. Note, that in the Java UNO binding, the com.sun.star.uno.Exception is derived from java.lang.Exception, while the com.sun.star.uno.RuntimeException is directly derived from java.lang.RuntimeException.

A common misuse of the runtime exception is to reuse it for an exception that was forgotten during interface specification. This should be avoided under all circumstances. Consider, defining a new interface. 

An exception should not be misused as a new kind of programming flow mechanism. It should always be possible that during a session of a program, no exception is thrown. If this is not the case, the interface design should be reviewed.  

Good Exception Handling

This section provides tips on exception handling strategies. Under certain circumstances, the code snippets we call bad below might make sense, but often they do not. 

Often, especially in C++ code where you generally do not have a stack trace, the message within the exception is the only method that informs the caller about the reason and origin of the exception. The message is important, especially when the exception comes from a generic interface where all kinds of UNO exceptions can be thrown. 

When writing exceptions, put descriptive text into them. To transfer the text to another exception, make sure to copy the text. 

Many people write helper functions to simplify recurring coding tasks. However, often code will be written like the following: 

// Bad example for exception handling  

public static void insertIntoCell( XPropertySet xPropertySet ) { 

    [...]

    try {

        xPropertySet.setPropertyValue("CharColor",new Integer(0));

    } catch (Exception e) {

    }

This code is ineffective, because the error is hidden. The caller will never know that an error has occurred. This is fine as long as test programs are written or to try out certain aspects of the API (although even test programs should be written correctly). Exceptions must be addressed because the compiler can not perform correctly. In real applications, handle the exception. 

The appropriate solution depends on the appropriate handling of exceptions. The following is the minimum each programmer should do: 

// During early development phase, this should be at least used instead 

public static void insertIntoCell(XPropertySet xPropertySet) { 

    [...]

    try {

        xPropertySet.setPropertyValue("CharColor",new Integer(0));

    } catch (Exception e) {

        e.dumpStackTrace();

    }

The code above dumps the exception and its stack trace, so that a message about the occurrence of the exception is received on stderr. This is acceptable during development phase, but it is insufficient for deployed code. Your customer does not watch the stderr window.

The level where the error can be handled must be determined. Sometimes, it would be better not to catch the exception locally, but further up the exception chain. The user can then be informed of the error through dialog boxes. Note that you can even specify exceptions on the main() function:

// this is how the final solution could look like 

public static void insertIntoCell(XPropertySet xPropertySet) throws UnknownPropertyException, 

        PropertyVetoException, IllegalArgumentException, WrappedTargetException {

    [...]

    xPropertySet.setPropertyValue("CharColor",new Integer(0));

As a general rule, if you cannot recover from an exception in a helper function, let the caller determine the outcome. Note that you can even throw exceptions at the main() method.

3.3.8  Lifetime of UNO Objects

The UNO component model has a strong impact on the lifetime of UNO objects, in contrast to CORBA, where object lifetime is completely unspecified. UNO uses the same mechanism as Microsoft COM by handling the lifetime of objects by reference counting.

Each UNO runtime environment defines its own specification on lifetime management. While in C++ UNO, each object maintains its own reference count. Java UNO uses the normal Java garbage collector mechanism. The UNO core of each runtime environment needs to ensure that it upholds the semantics of reference counting towards other UNO environments. 

The last paragraph of this chapter explains the differences between the lifetime of Java and C++ objects in detail. 

acquire() and release()

Every UNO interface is derived from com.sun.star.uno.XInterface:

// module com::sun::star::uno 

interface XInterface 

    any queryInterface( [in] type aType );

    [oneway] void acquire();

    [oneway] void release();

};  

 

UNO objects must maintain an internal reference counter. Calling acquire() on a UNO interface increases the reference count by one. Calling release() on UNO interfaces decreases the reference count by one. If the reference count drops to zero, the UNO object may be destroyed. Destruction of an object is sometimes called death of an object or that the object dies. The reference count of an object must always be non-negative.

Once acquire() is called on the UNO object, there is a reference or a hard reference to the object, as opposed to a weak reference. Calling release() on the object is often called releasing or clearing the reference.

The UNO object does not export the state of the reference count, that is, acquire() and release() do not have return values. Generally, the UNO object should not make any assumptions on the concrete value of the reference count, except for the transition from one to zero.

The invocation of a method is allowed first when acquire () has been called before. For every call to acquire() , there must be a corresponding release call, otherwise the object leaks.

Note graphics marks a special text section

The UNO Java binding encapsulates acquire() and release() in the UnoRuntime.queryInterface() call. The same applies to the Reference<> template in C++. As long as the interface references are obtained through these mechanisms, acquire() and release() do not have to be called in your programs.

The XComponent Interface

A central problem of reference counting systems is cyclic references. Assume Object A keeps a reference on object B and B keeps a direct or indirect reference on object A. Even if all the external references to A and B are released, the objects are not destroyed, which results in a resource leak.  

Cyclic referenceIllustration 3.12: Cyclic Reference
Note graphics marks a special text section

In general, a Java developer does not have to be concerned about this kind of issue, as the garbage collector algorithm detects ring references. However, in the UNO world one never knows, whether object A and object B really live in the same Java virtual machine. If they do, the ring reference is really garbage collected. If they do not, the object leaks, because the Java VM is not able to inspect the object outside of the VM for its references. 

In UNO, the developer must explicitly decide when to the break cyclic references. To support this concept, the interface com.sun.star.lang.XComponent exists. When an XComponent is disposed of, it can inform other objects that have expressed interest to be notified.

// within the module com::sun::star::lang 

// when dispose() is called, previously added XEventListeners are notified 

interface XComponent: com::sun::star::uno::XInterface 

{  

     void dispose();

     void addEventListener( [in] XEventListener xListener );

     void removeEventListener( [in] XEventListener aListener );

}; 

 

// An XEventListener is notified by calling its disposing() method 

interface XEventListener: com::sun::star::uno::XInterface 

{  

   void disposing( [in] com::sun::star::lang::EventObject Source );

};  

Other objects can add themselves as com.sun.star.lang.XEventListener to an XComponent. When the dispose() method is called, the object notifies all XEventListeners through the disposing() method and releases all interface references, thus breaking the cyclic reference.

Dispose CallIllustration 3.13: Object C calls dispose() on XComponent of Object B

A disposed object is unable to comply with its specification, so it is necessary to ensure that an object is not disposed of before calling it. UNO uses an owner/user concept for this purpose. Only the owner of an object is allowed to call dispose and there can only be one owner per object. The owner is always free to dispose of the object. The user of an object knows that the object may be disposed of at anytime. The user adds an event listener to discover when an object is being disposed. When the user is notified, the user releases the interface reference to the object. In this case, the user should not call removeEventListener(), because the disposed object releases the reference to the user.

Pay attention to the following important text section

One major problem of the owner/user concept is that there always must be someone who calls dispose(). This must be considered at the design time of the services and interfaces, and be specified explicitly.

This solves the problem described above. However, there are a few conditions which still have to be met. 

Break of a cyclic referenceIllustration 3.14: B releases all interface references, which leads to destruction of Object A, which then releases its reference to B, thus the cyclic reference is broken.

If an object is called while it is disposed of, it should behave passively. For instance, if removeListener() is called, the call should be ignored. If methods are called while the object is no longer able to comply with its interface specification, it should throw a com.sun.star.lang.DisposedException, derived from com.sun.star.uno.RuntimeException. This is one of the rare situations in which an implementation should throw a RuntimeException. The situation described above can always occur in a multithreaded environment, even if the caller has added an event listener to avoid calling objects which were disposed of by the owner.

The owner/user concept may not always be appropriate, especially when there is more than one possible owner. In these cases, there should be no owner but only users. In a multithreaded scenario, dispose() might be called several times. The implementation of an object should be able to cope with such a situation.

The XComponent implementation should always notify the disposing() listeners that the object is being destroyed, not only when dispose() is called, but when the object is deleted. When the object is deleted, the reference count of the object drops to zero. This may happen when the listeners do not hold a reference on the broadcaster object.

The XComponent does not have to be implemented when there is only one owner and no further users.

Children of the XEventListener Interface

The com.sun.star.lang.XEventListener interface is the base for all listener interfaces . This means that not only XEventListeners, but every listener must implement disposing(), and every broadcaster object that allows any kind of listener to register, must call disposing() on the listeners as soon as it dies. However, not every broadcaster is forced to implement the XComponent interface with the dispose() method, because it may define its own condition when it is disposed.

In a chain of broadcaster objects where every element is a listener of its predecessor and only the root object is an XComponent that is being disposed, all the other chain links must handle the disposing() call coming from their predecessor and call disposing() on their registered listeners.

Weak Objects and References

A strategy to avoid cyclic references is to use weak references. Having a weak reference to an object means that you can reestablish a hard reference to the object again if the object still exists, and there is another hard reference to it.

In the cyclic reference shown in illustration 3.12: Cyclic Reference, object B could be specified to hold a hard reference on object A, but object A only keeps a weak reference to B. If object A needs to invoke a method on B, it temporarily tries to make the reference hard. If this succeeds, it invokes the method and releases the hard reference afterwards.

To be able to create a weak reference on an object, the object needs to support it explicitly by exporting the com.sun.star.uno.XWeak interface. The illustration 3.13: Object C calls dispose() on XComponent of Object B depicts the UNO mechanism for weak references.

When an object is assigned to a weak reference, the weak reference calls queryAdapter() at the original object and adds itself (with the com.sun.star.uno.XReference interface) as reference to the adapter.

UML diagram showing the weak reference mechanismIllustration 3.15: The UNO weak reference mechanism

When a hard reference is established from the weak reference, it calls the queryAdapted() method at the com.sun.star.uno.XAdapter interface of the adapter object. When the original object is still alive, it gets a reference for it, otherwise a null reference is returned.

The adapter notifies the destruction of the original object to all weak references which breaks the cyclic reference between the adapter and weak reference. 

4 Writing UNO Components describes the helper classes in C++ and Java that implement a Xweak interface and a weak reference.

Differences Between the Lifetime of C++ and Java Objects

Note graphics marks a special text section

Read 3.4.2 Professional UNO - UNO Language Bindings - C++ Language Binding and 3.4.1 Professional UNO - UNO Language Bindings - Java Language Binding for information on language bindings, and 4.6 Writing UNO Components - C++ Component and 4.5.6 Writing UNO Components - Simple Component in Java - Storing the Service Manager for Further Use about component implementation before beginning this section.

The implementation of the reference count specification is different in Java UNO and C++ UNO. In C++ UNO, every object maintains its own reference counter. When you implement a C++ UNO object, instantiate it, acquire it and afterwards release it, the destructor of the object is called immediately. The following example uses the standard helper class ::cppu::OWeakObject and prints a message when the destructor is called. (ProfUNO/Lifetime/object_lifetime.cxx)

class MyOWeakObject : public ::cppu::OWeakObject 

public: 

    MyOWeakObject() { fprintf( stdout, "constructed\n" ); }

    ~MyOWeakObject() { fprintf( stdout, "destroyed\n" ); }

}; 

The following method creates a new MyOWeakObject, acquires it and releases it for demonstration purposes. The call to release() immediately leads to the destruction of MyOWeakObject. If the Reference<> template is used, you do not need to care about acquire() and release().

void simple_object_creation_and_destruction() 

    // create the UNO object

    com::sun::star::uno::XInterface * p = new MyOWeakObject();

 

    // acquire it

    p->acquire();

 

    // releast it

    fprintf( stdout, "before release\n" );

    p->release();

    fprintf( stdout, "after release\n" );

This piece of code produces the following output: 

constructed 

before release 

destroyed 

after release 

Java UNO objects behave differently, because they are finalized by the garbage collector at a time of its choosing. com.sun.star.uno.XInterface has no methods in the Java UNO language binding, therefore no methods need to be implemented, although MyUnoObject implements XInterface: (ProfUNO/Lifetime/MyUnoObject.java)

class MyUnoObject implements com.sun.star.uno.XInterface { 

 

    public MyUnoObject() {

    }

 

    void finalize() {

        System.out.println("finalizer called");

    }

 

    static void main(String args[]) throws java.lang.InterruptedException {

        com.sun.star.uno.XInterface a = new MyUnoObject();

        a = null;

 

        // ask the garbage collector politely

        System.gc();

        System.runFinalization();

 

        System.out.println("leaving");

 

        // It is java VM dependent, whether or not the finalizer was called

    }

The output of this code depends on the Java VM implementation. The output “finalizer called” is not a usual result. Be aware of the side effects when UNO brings Java and C++ together. 

When a UNO C++ object is mapped to Java, a Java proxy object is created that keeps a hard UNO reference to the C++ object. The UNO core takes care of this. The Java proxy only clears the reference when it enters the finalize() method, thus the destruction of the C++ object is delayed until the Java VM collects some garbage.

When a UNO Java object is mapped to C++, a C++ proxy object is created that keeps a hard UNO reference to the Java object. Internally, the Java UNO bridge keeps a Java reference to the original Java object. When the C++ proxy is no longer used, it is destroyed immediately. The Java UNO bridge is notified and immediately frees the Java reference to the original Java object. When the Java object is finalized is dependent on the garbage collector. 

When a Java program is connected to a running OpenOffice.org, the UNO objects in the office process are not destroyed until the garbage collector finalizes the Java proxies or until the interprocess connection is closed (see 3.3.1 Professional UNO - UNO Concepts - UNO Interprocess Connections).

3.3.9  Object Identity

UNO guarantees if two object references are identical, that a check is performed and it always leads to a correct result, whether it be true or false. This is different from CORBA, where a return of false does not necessarily mean that the objects are different.

Every UNO runtime environment defines how this check should be performed. In Java UNO, there is a static areSame() function at the com.sun.star.uno.UnoRuntime class. In C++, the check is performed with the Reference<>::operator == () function that queries both references for XInterface and compares the resulting XInterface pointers.

This has a direct effect in the API design. For instance, look at com.sun.star.lang.XComponent:

interface XComponent: com::sun::star::uno::XInterface 

{  

    void dispose();

    void addEventListener( [in] XEventListener xListener );

    void removeEventListener( [in] XEventListener aListener );

};  

The method removeEventListener() that takes a listener reference, is logical if the implementation can check for object identity, otherwise it could not identify the listener that has to be removed. CORBA interfaces are not designed in this manner. They need an object ID, because object identity is not guaranteed.

3.4  UNO Language Bindings

This chapter documents the mapping of UNO to various programming languages or component models. This language binding is sometimes called a UNO Runtime Environment (URE). Each URE needs to fulfill the specifications given in the earlier chapters. The use of UNO services and interfaces are also explained in this chapter. Refer to 4 Writing UNO Components for information about the implementation of UNO objects.

Each section provides detail information for the following topics: 

Java, C++, OpenOffice.org Basic, and all languages supporting MS OLE automation or the Common Language Infrastructure (CLI) on the win32 platform are currently supported. In the future, the number of supported language bindings may be extended. 

3.4.1  Java Language Binding

The Java language binding gives developers the choice of using Java or UNO components for client programs. A Java program can access components written in other languages and built with a different compiler, as well as remote objects, because of the seamless interaction of UNO bridges. 

Java delivers a rich set of classes that can be used within client programs or component implementations. However, when it comes to interaction with other UNO objects, use UNO interfaces, because only those are known to the bridge and can be mapped into other environments. 

To control the office from a client program, the client needs a Java 1.3 (or later) installation, a free socket port, and the following jar files juh.jar, jurt.jar, ridl.jar, and unoil.jar. A Java installation on the server-side is not necessary. A step-by-step description is given in the chapter 2 First Steps

When using Java components, the office is installed with Java support. Also make sure that Java is enabled: there is a switch that can be set to achieve this in the Tools - Options - OpenOffice.org - Security dialog. All necessary jar files should have been installed during the OpenOffice.org setup. A detailed explanation can be found in the chapter 4.5.6 Writing UNO Components - Simple Component in Java - Storing the Service Manager for Further Use.

The Java UNO Runtime is documented in the Java UNO Reference which can be found in the OpenOffice.org Software development Kit (SDK) or on api.openoffice.org.

Getting a Service Manager

Office objects that provide the desired functionality are required when writing a client application that accesses the office. The root of all these objects is the service manager component, therefore clients need to instantiate it. Service manager runs in the office process, therefore office must be running first when you use Java components that are instantiated by the office. In a client-server scenario, the office has to be launched directly. The interprocess communication uses a remote protocol that can be provided as a command-line argument to the office:

soffice -accept=socket,host=localhost,port=8100;urp

The client obtains a reference to the global service manager of the office (the server) using a local com.sun.star.bridge.UnoUrlResolver. The global service manager of the office is used to get objects from the other side of the bridge. In this case, an instance of the com.sun.star.frame.Desktop is acquired:

import com.sun.star.uno.XComponentContext; 

import com.sun.star.comp.helper.Bootstrap; 

import com.sun.star.lang.XMultiComponentFactory; 

import com.sun.star.bridge.UnoUrlResolver; 

import com.sun.star.bridge.XUnoUrlResolver; 

import com.sun.star.beans.XPropertySet 

import com.sun.star.uno.UnoRuntime; 

 

XComponentContext xcomponentcontext = Bootstrap.createInitialComponentContext(null); 

 

// create a connector, so that it can contact the office 

XUnoUrlResolver urlResolver = UnoUrlResolver.create(xcomponentcontext); 

 

Object initialObject = urlResolver.resolve(

    "uno:socket,host=localhost,port=8100;urp;StarOffice.ServiceManager");

       

XMultiComponentFactory xOfficeFactory = (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, xOfficeFactory);

 

// Get the default context from the office server. 

Object oDefaultContext = xProperySet.getPropertyValue("DefaultContext"); 

 

// Query for the interface XComponentContext. 

XComponentContext xOfficeComponentContext = (XComponentContext) UnoRuntime.queryInterface( 

    XComponentContext.class, oDefaultContext);

 

// now create the desktop service 

// NOTE: use the office component context here! 

Object oDesktop = xOfficeFactory.createInstanceWithContext( 

    “com.sun.star.frame.Desktop", xOfficeComponentContext);

As the example shows, a local component context is created through the com.sun.star.comp.helper.Bootstrap class (a Java UNO runtime class). Its implementation provides a service manager that is limited in the number of services it can create. The names of these services are:

com.sun.star.lang.ServiceManager
com.sun.star.lang.MultiServiceFactory
com.sun.star.loader.Java
com.sun.star.loader.Java2
com.sun.star.bridge.UnoUrlResolver
com.sun.star.bridge.BridgeFactory
com.sun.star.connection.Connector
com.sun.star.connection.Acceptor

They are sufficient to establish a remote connection and obtain the fully featured service manager provided by the office. 

Tip graphics marks a hint section in the text

The service manager of the local component context could create other components, but this is only possible if the service manager is provided with the respective factories during runtime. An example that shows how this works can be found in the implementation of the Bootstrap class in the project javaunohelper.
There is also a service manager that uses a registry database to locate services. It is implemented by the class com.sun.star.comp.helper.RegistryServiceFactory in the project javaunohelper. However, the implementation uses a native registry service manager instead of providing a pure Java implementation.

Transparent Use of Office UNO Components

If some client code wants to use office UNO components, then a typical use case is that the client code first looks for an existing office installation. If an installation is found, the client checks if the office process is already running. If no office process is running, an office process is started. After that, the client code connects to the running office using remote UNO mechanisms in order to get the remote component context of that office. After this, the client code can use the remote component context to access arbitrary office UNO components. From the perspective of the client code, there is no difference between local and remote components. 

The bootstrap method

Therefore, the remote office component context is provided in a more transparent way by the com.sun.star.comp.helper.Bootstrap.bootstrap() method, which bootstraps the component context from a UNO installation. A simple client application may then look like: (ProfUNO/SimpleBootstrap_java/SimpleBootstrap_java.java)

// get the remote office component context 

XComponentContext xContext = 

    com.sun.star.comp.helper.Bootstrap.bootstrap();

 

// get the remote office service manager 

XMultiComponentFactory xServiceManager = 

    xContext.getServiceManager();

 

// get an instance of the remote office desktop UNO service 

Object desktop = xServiceManager.createInstanceWithContext( 

    "com.sun.star.frame.Desktop", xContext );

The com.sun.star.comp.helper.Bootstrap.bootstrap() method first bootstraps a local component context and then tries to establish a named pipe connection to a running office. If no office is running, an office process is started. If the connection succeeds, the remote component context is returned.

Pay attention to the following important text section

Note, that the com.sun.star.comp.helper.Bootstrap.bootstrap() method is only available since OpenOffice.org 1.1.2.

SDK tooling

For convenience, the OpenOffice.org Software Development Kit (SDK) provides some tooling for writing Java client applications. 

One of the requirements for a Java client application is that Java finds the com.sun.star.comp.helper.Bootstrap class and all the UNO types (for example, UNO interfaces) and other Java UNO language binding classes (for example,  com.sun.star.uno.AnyConverter) used by the client code. A natural approach would be to add the UNO jar files to the Java CLASSPATH, but this requires the knowledge of the location of a UNO installation. Other approaches would be to use the Java extension mechanism or to deploy the jar files containing the UNO types in the client jar file. Both of those approaches have several drawbacks, the most important one is the problem of type conflicts, for example, if a deployed component adds new UNO types. The SDK tooling therefore provides a more dynamic approach, namely a customized class loader. The customized class loader has an extended search path, which also includes the path to a UNO installation. The UNO installation is auto-detected on the system by using a search algorithm.

Customized Class Loader

The concept is based on the requirement that every class that uses UNO types, or other classes that come with a office installation, gets loaded by a customized class loader. This customized class loader recognizes the location of a UNO installation and loads every class from a jar or class file that belongs to the office installation. That means that the customized class loader must be instantiated and initialized before the first class that uses UNO is loaded. 

The SDK tooling allows to build a client jar file, which can be invoked by the following: 

java -jar SimpleBootstrap_java.jar

The client jar file contains the following files: 

META-INF/MANIFEST.MF
com/sun/star/lib/loader/InstallationFinder$StreamGobbler.class
com/sun/star/lib/loader/InstallationFinder.class
com/sun/star/lib/loader/Loader$CustomURLClassLoader.class
com/sun/star/lib/loader/Loader.class
com/sun/star/lib/loader/WinRegKey.class
com/sun/star/lib/loader/WinRegKeyException.class
win/unowinreg.dll
SimpleBootstrap_java.class

A client application created by using the SDK tooling will automatically load the class com.sun.star.lib.loader.Loader, which sets up the customized class loader for loading the application class. In order to achieve this, the SDK tooling creates a manifest file that contains the following Main-Class entry

Main-Class: com.sun.star.lib.loader.Loader

The customized loader needs a special entry in the manifest file that specifies the name of the class that contains the client application code: 

Name: com/sun/star/lib/loader/Loader.class
Application-Class: SimpleBootstrap_java

The implementation of com.sun.star.lib.loader.Loader.main reads this entry and calls the main method of the application class after the customized class loader has been created and set up properly. The SDK tooling will take over the task of writing the correct manifest entry for the application class.

Finding a UNO Installation

The location of a UNO installation can be specified by the Java system property com.sun.star.lib.loader.unopath. The system property can be passed to the client application by using the -D flag, e.g

java -Dcom.sun.star.lib.loader.unopath=/opt/OpenOffice.org/program -jar SimpleBootstrap_java.jar

In addition, it is possible to specify a UNO installation by setting the environment variable UNO_PATH to the program directory of a UNO installation, for example,

setenv UNO_PATH /opt/OpenOffice.org/program

Pay attention to the following important text section

This does not working with Java 1.3.1 and Java 1.4, because environment variables are not supported in those Java versions. 

If no UNO installation is specified by the user, the default UNO installation on the system is searched. The search algorithm is platform dependent. 

On the Windows platform, the UNO installation is found by reading the default value of the key 'Software\OpenOffice.org\UNO\InstallPath' from the root key HKEY_CURRENT_USER in the Windows Registry. If this key is missing, the key is read from the root key HKEY_LOCAL_MACHINE. One of those keys is always written during the installation of an office. In a single user installation the key is written to HKEY_CURRENT_USER, in a multi-user installation of an administrator to HKEY_LOCAL_MACHINE. Note that the default installation is the last installed office, but with the restriction, that HKEY_CURRENT_USER has a higher priority than HKEY_LOCAL_MACHINE. The reading from the Windows Registry requires that the native library unowinreg.dll is part of the application jar file or can be found in the java.library.path. The SDK tooling automatically will put the native library into the jar file containing the client application.

On the Unix/Linux platforms, the UNO installation is found from the PATH environment variable. Note that for Java 1.3.1 and Java 1.4, the installation is found by using the which command, because environment variables are not supported with those Java versions. Both methods require that the soffice executable or a symbolic link is in one of the directories listed in the PATH environment variable. For older versions than OpenOffice.org 2.0 the above described methods may fail. In this case the UNO installation is taken from the .sversionrc file in the user's home directory. The default installation is the last entry in the .sversionrc file which points to a UNO installation. Note that there won't be a .sversionrc file with OpenOffice.org 2.0 anymore.

Handling Interfaces

The service manager is created in the server process and the Java UNO remote bridge ensures that its XInterface is transported back to the client. A Java proxy object is constructed that can be used by the client code. This object is called the initial object, because it is the first object created by the bridge. When another object is obtained through this object, then the bridge creates a new proxy. For instance, if a function is called that returns an interface. That is, the original object is actually running in the server process (the office) and calls to the proxy are forwarded by the bridge. Not only interfaces are converted, but function arguments, return values and exceptions.

The Java bridge maps objects on a per-interface basis, that is, in the first step only the interface is converted that is returned by a function described in the API reference. For example, if you have  the service manager and use it to create another component, you initially get a com.sun.star.uno.XInterface:

XInterface xint= (XInterface) serviceManager.createInstance(“com.sun.star.bridge.oleautomation.Factory”); 

You know from the service description that Factory implements a com.sun.star.lang.XMultiServiceFactory interface. However, you cannot cast the object or call the interface function on the object, since the object is only a proxy for just one interface, XInterface. Therefore, you have to use a mechanism that is provided with the Java bridge that generates proxy objects on demand. For example:

XMultiServiceFactory xfac = (XMultiServiceFactory) UnoRuntime.queryInterface( 

    XMultiServiceFactory.class, xint);

If xint is a proxy, then queryInterface() hands out another proxy for XMultiServiceFactory provided that the original object implements it. Interface proxies can be used as arguments in function calls on other proxy objects. For example:

// client side 

// obj is a proxy interface and returns another interface through its func() method 

XSomething ret = obj.func(); 

 

// anotherObject is a proxy interface, too. Its method func(XSomething arg) 

// takes the interface ret obtained from obj 

anotherObject.func(ret); 

In the server process, the obj object would receive the original ret object as a function argument.

It is also possible to have Java components on the client side. As well, they can be used as function arguments, then the bridge would set up proxies for them in the server process. 

Not all language concepts of UNO have a corresponding language element in Java. For example, there are no structs and all-purpose out parameters. Refer to 3.4.1 Professional UNO - UNO Language Bindings - Java Language Binding - Type Mappings for how those concepts are mapped.

Interface handling normally involves the ability of com.sun.star.uno.XInterface to acquire and release objects by reference counting. In Java, the programmer does not bother with acquire() and release(), since the Java UNO runtime automatically acquires objects on the server side when com.sun.star.uno.UnoRuntime.queryInterface() is used. Conversely, when the Java garbage collector deletes your references, the Java UNO runtime releases the corresponding office objects. If a UNO object is written in Java, no reference counting is used to control its lifetime. The garbage collector takes that responsibility.

Sometimes it is necessary to find out if two interfaces belong to the same object. In Java, you would compare the references with the equality operator '=='. This works as long as the interfaces refer to a local Java object. Often the interfaces are proxies and the real objects reside in a remote process. There can be several proxies that belong to the same object, because objects are bridged on a per-interface basis. Those proxies are Java objects and comparing their references would not establish them as parts of the same object. To determine if interfaces are part of the same UNO object, use the method areSame() at the com.sun.star.uno.UnoRuntime class:

static public boolean areSame(Object object1, Object object2)

Type Mappings

Mapping of Simple Types

The following table shows the mapping of simple UNO types to the corresponding Java types. 

UNO 

Java 

void 

void 

boolean 

boolean 

byte 

byte 

short 

short 

unsigned short 

short 

long 

int 

unsigned long 

int 

hyper 

long 

unsigned hyper 

long 

float 

float 

double 

double 

char 

char 

string 

java.lang.String 

type 

com.sun.star.uno.Type 

any 

java.lang.Object/com.sun.star.uno.Any 

The mapping between the values of the corresponding UNO and Java types is obvious, except for a few cases that are explained in the following sections: 

Mapping of Unsigned Integer Types

An unsigned UNO integer type encompasses the range from 0 to 2N − 1, inclusive, while the corresponding signed Java integer type encompasses the range from −2N − 1 to 2N − 1 − 1, inclusive (where N is 16, 32, or 64 for unsigned short, unsigned long, or unsigned hyper, respectively). The mapping is done modulo N, that is: 0 is mapped to 0; 2N − 1 − 1 is mapped to  2N − 1 − 1;  2N − 1 is mapped to −2N − 1; and 2N − 1 is mapped to −1.

Users should be careful when using any of the deprecated UNO unsigned integer types. A user is responsible for correctly interpreting values of signed Java integer types as unsigned integer values in such cases. 

Mapping of String

The mapping between the UNO string type and java.lang.String is straightforward, except for three details:

Mapping of Type

The Java class com.sun.star.uno.Type is used to represent the UNO type type; only non-null references to com.sun.star.uno.Type are valid. (It is a historic mistake that com.sun.star.Type is not final. You should never derive from it in your code.)

In many places in the Java UNO runtime, there are convenience functions that take values of type java.lang.Class where conceptually a value of com.sun.star.uno.Type would be expected. For example, there are two overloaded versions of the method com.sun.star.uno.Uno­Runtime.query­Interface, one with a parameter of type com.sun.star.uno.Type and one with a parameter of type java.lang.Class. See the documentation of com.sun.star.uno.Type for the details of how values of java.lang.Class are interpreted in such a context.

Mapping of Any

There is a dedicated com.sun.star.uno.Any type, but it is not always used. An any in the API reference is represented by a java.lang.Object in Java UNO. An Object reference can be used to refer to all possible Java objects. This does not work with primitive types, but if you need to use them as an any, there are Java wrapper classes available that allow primitive types to be used as objects. Also, a Java Object always brings along its type information by means of an instance of java.lang.Class. Therefore a variable declared as:

Object ref; 

can be used with all objects and its type information is available by calling: 

ref.getClass(); 

Those qualities of Object are sufficient to replace the Any in most cases. Even Java interfaces generated from IDL interfaces do not contain Anys, instead Object references are used in place of Anys. Cases where an explicit Any is needed to not loose information contain unsigned integer types, all interface types except the basic XInterface, and the void type.

Pay attention to the following important text section

However, implementations of those interfaces must be able to deal with real Anys that can also be passed by means of Object references.

To facilitate the handling of the Any type, use the com.sun.star.uno.AnyConverter class. It is documented in the Java UNO reference. The following list sums up its methods:

static boolean isArray(java.lang.Object object)

static boolean isBoolean(java.lang.Object object)

static boolean isByte(java.lang.Object object)

static boolean isChar(java.lang.Object object)

static boolean isDouble(java.lang.Object object)

static boolean isFloat(java.lang.Object object)

static boolean isInt(java.lang.Object object)

static boolean isLong(java.lang.Object object)

static boolean isObject(java.lang.Object object)

static boolean isShort(java.lang.Object object)

static boolean isString(java.lang.Object object)

static boolean isType(java.lang.Object object)

static boolean isVoid(java.lang.Object object)

static java.lang.Object toArray(java.lang.Object object)

static boolean toBoolean(java.lang.Object object)

static byte toByte(java.lang.Object object)

static char toChar(java.lang.Object object)

static double toDouble(java.lang.Object object)

static float toFloat(java.lang.Object object)

static int toInt(java.lang.Object object)

static long toLong(java.lang.Object object)

static java.lang.Object toObject(Type type, java.lang.Object object)

static short toShort(java.lang.Object object)

static java.lang.String toString(java.lang.Object object)

static Type toType(java.lang.Object object)

The Java com.sun.star.uno.Any is needed in situations when the type needs to be specified explicitly. Assume there is a C++ component with an interface function which is declared in UNOIDL as:

//UNOIDL 

void foo(any arg); 

The corresponding C++ implementation could be: 

void foo(const Any& arg) 

    const Type& t = any.getValueType();

    if (t == cppu::UnoType< XReference >::get())

    {

        Reference<XReference> myref = *reinterpret_cast<const Reference<XReference>*>(arg.getValue());

        ...

    }

In the example, the any is checked if it contains the expected interface. If it does, it is assigned  accordingly. If the any contained a different interface, a query would be performed for the expected interface. If the function is called from Java, then an interface has to be supplied that is an object. That object could implement several interfaces and the bridge would use the basic XInterface. If this is not the interface that is expected, then the C++ implementation has to call queryInterface to obtain the desired interface. In a remote scenario, those queryInterface() calls could lead to a noticeable performance loss. If you use a Java Any as a parameter for foo(), the intended interface is sent across the bridge.

It is a historic mistake that com.sun.star.uno.Any is not final. You should never derive from it in your code.

Mapping of Sequence Types

A UNO sequence type with a given component type is mapped to the Java array type with corresponding component type. 

Only non-null references to those Java array types are valid. As usual, non-null references to other Java array types that are assignment compatible to a given array type can also be used, but doing so can cause java.lang.ArrayStoreExceptions. In Java, the maximal length of an array is limited; therefore, it is an error if a UNO sequence that is too long is used in the context of the Java language binding.

Mapping of Enum Types

An UNO enum type is mapped to a public, final Java class with the same name, derived from the class com.sun.star.uno.Enum. Only non-null references to the generated final classes are valid.

The base class com.sun.star.uno.Enum declares a protected member to store the actual value, a protected constructor to initialize the value and a public getValue() method to get the actual value. The generated final class has a protected constructor and a public method getDefault() that returns an instance with the value of the first enum member as a default. For each member of a UNO enum type, the corresponding Java class declares a public static member of the given Java type that is initialized with the value of the UNO enum member. The Java class for the enum type has an additional public method fromInt() that returns the instance with the specified value. The following IDL definition for com.sun.star.uno.TypeClass:

module com { module sun { module star { module uno { 

 

enum TypeClass { 

    INTERFACE,

    SERVICE,

    IMPLEMENTATION,

    STRUCT,

    TYPEDEF,

    ...

}; 

 

}; }; }; }; 

is mapped to: 

package com.sun.star.uno; 

 

public final class TypeClass extends com.sun.star.uno.Enum { 

    private TypeClass(int value) {

        super(value);

    }

 

    public static TypeClass getDefault() {

        return INTERFACE;

    }

 

    public static final TypeClass INTERFACE = new TypeClass(0);

    public static final TypeClass SERVICE = new TypeClass(1);

    public static final TypeClass IMPLEMENTATION = new TypeClass(2);

    public static final TypeClass STRUCT = new TypeClass(3);

    public static final TypeClass TYPEDEF = new TypeClass(4);

    ...

 

    public static TypeClass fromInt(int value) {

        switch (value) {

        case 0:

            return INTERFACE;

        case 1:

            return SERVICE;

        case 2:

            return IMPLEMENTATION;

        case 3:

            return STRUCT;

        case 4:

            return TYPEDEF;

        ...

        }

    }
}

Mapping of Struct Types

A plain UNO struct type is mapped to a public Java class with the same name. Only non-null references to such a class are valid. Each member of the UNO struct type is mapped to a public field with the same name and corresponding type. The class provides a default constructor which initializes all members with default values, and a constructor which takes explicit values for all struct members. If a plain struct type inherits from another struct type, the generated class extends the class of the inherited struct type. 

module com { module sun { module star { module chart { 

 

struct ChartDataChangeEvent: com::sun::star::lang::EventObject { 

    ChartDataChangeType Type;

    short StartColumn;

    short EndColumn;

    short StartRow;

    short EndRow;

}; 

 

}; }; }; }; 

is mapped to: 

package com.sun.star.chart; 

 

public class ChartDataChangeEvent extends com.sun.star.lang.EventObject { 

    public ChartDataChangeType Type;

    public short StartColumn;

    public short EndColumn;

    public short StartRow;

    public short EndRow;

 

    public ChartDataChangeEvent() {

        Type = ChartDataChangeType.getDefault();

    }

 

    public ChartDataChangeEvent(

        Object Source, ChartDataChangeType Type,

        short StartColumn, short EndColumn, short StartRow, short EndRow)

    {

        super(Source);

        this.Type = Type;

        this.StartColumn = StartColumn;

        this.EndColumn = EndColumn;

        this.StartRow = StartRow;

        this.EndRow = EndRow;

    }
}

Similar to a plain struct type, a polymorphic UNO struct type template is also mapped to a Java class. The only difference is how struct members with parametric types are handled, and this handling in turn differs between Java 1.5 and older versions. 

Take, for example, the polymorphic struct type template: 

module com { module sun { module star { module beans { 

 

struct Optional<T> { 

    boolean IsPresent;

    T Value;

}; 

 

}; }; }; }; 

In Java 1.5, a polymorphic struct type template with a list of type parameters is mapped to a generic Java class with a corresponding list of unbounded type parameters. For com.sun.star.beans.Optional, that means that the corresponding Java 1.5 class looks something like the following example:

package com.sun.star.beans; 

 

public class Optional<T> { 

    public boolean IsPresent;

    public T Value;

 

    public Optional() {}

 

    public Optional(boolean IsPresent, T Value) {

        this.IsPresent = IsPresent;

        this.Value = Value;

    }
}

Instances of such polymorphic struct type templates map to Java 1.5 in a natural way. For example, UNO Optional<string> maps to Java Optional<String>. However, UNO type arguments that would normally map to primitive Java types map to corresponding Java wrapper types instead:

For example, UNO Optional<long> maps to Java Optional<Integer>. Also note that UNO type arguments of both any and com.sun.star.uno.XInterface map to java.lang.Object, and thus, for example, both Optional<any> and Optional<XInterface> map to Java Optional<Object>.

Still, there are a few problems and pitfalls when dealing with parametric members of default-constructed polymorphic struct type instances: 

In Java versions prior to 1.5, which do not support generics, a polymorphic struct type template is mapped to a plain Java class in such a way that any parametric members are mapped to class fields of type java.lang.Object. This is generally less favorable than using generics, as it reduces type-safety, but it has the advantage that it is compatible with Java 1.5 (actually, a single Java class file is generated for a given UNO struct type template, and that class file works with both Java 1.5 and older versions). In a pre-1.5 Java, the Optional example will look something like the following:

package com.sun.star.beans; 

 

public class Optional { 

    public boolean IsPresent;

    public Object Value;

 

    public Optional() {}

 

    public Optional(boolean IsPresent, Object Value) {

        this.IsPresent = IsPresent;

        this.Value = Value;

    }
}

How java.lang.Object is used to represent values of arbitrary UNO types is detailed as follows:

This is similar to how java.lang.Object is used to represent values of the UNO any type. The difference is that there is nothing like com.sun.star.uno.Any here, which is used to disambiguate those cases where different UNO types map to the same subclass of java.lang.Object. Instead, here it must always be deducible from context exactly which UNO type a given Java reference represents.

The problems and pitfalls mentioned for Java 1.5, regarding parametric members of default-constructed polymorphic struct type instances, apply for older Java versions as well. 

Mapping of Exception Types

A UNO exception type is mapped to a public Java class with the same name. Only non-null references to such a class are valid.

There are two UNO exceptions that are the base for all other exceptions. These are the com.sun.star.uno.Exception and com.sun.star.uno.RuntimeException that are inherited by all other exceptions. The corresponding exceptions in Java inherit from Java exceptions:

module com { module sun { module star { module uno { 

 

exception Exception { 

    string Message;

    XInterface Context;

}; 

 

exception RuntimeException { 

    string Message;

    XInterface Context;

}; 

 

}; }; }; }; 

The com.sun.star.uno.Exception in Java:

package com.sun.star.uno; 

 

public class Exception extends java.lang.Exception { 

    public Object Context;

 

    public Exception() {}

 

    public Exception(String Message) {

        super(Message);

    }

 

    public Exception(String Message, Object Context) {

        super(Message);

        this.Context = Context;

    }
}

The com.sun.star.uno.RuntimeException in Java:

package com.sun.star.uno; 

 

public class RuntimeException extends java.lang.RuntimeException { 

    public Object Context;

 

    public RuntimeException() {}

 

    public RuntimeException(String Message) {

        super(Message);

    }

 

    public RuntimeException(String Message, Object Context) {

        super(Message);

        this.Context = Context;

    }
}

As shown, the Message member has no direct counterpart in the respective Java class. Instead, the constructor argument Message is used to initialize the base class, which is a Java exception. The message is accessible through the inherited getMessage() method. All other members of a UNO exception type are mapped to public fields with the same name and corresponding Java type. A generated Java exception class always has a default constructor that initializes all members with default values, and a constructor which takes values for all members.

If an exception inherits from another exception, the generated class extends the class of the inherited exception. 

Mapping of Interface Types

A UNO interface type is mapped to a public Java interface with the same name. Unlike for Java classes that represent UNO sequence, enum, struct, and exception types, a null reference is actually a legal value for a Java interface that represents a UNO interface type—the Java null reference represents the UNO null reference. 

If a UNO interface type inherits one ore more other interface types, the Java interface extends the corresponding Java interfaces. 

The UNO interface type com.sun.star.uno.XInterface is special: Only when that type is used as a base type of another interface type is it mapped to the Java type com.sun.star.uno.XInterface. In all other cases (when used as the component type of a sequence type, as a member of a struct or exception type, or as a parameter or return type of an interface method) it is mapped to java.lang.Object. Nevertheless, valid Java values of that type are only the Java null reference and references to those instances of java.lang.Object that implement com.sun.star.uno.XInterface.

A UNO interface attribute of the form 

[attribute] Type Name {
   get raises (ExceptionG1, ..., ExceptionGM);

    set raises (ExceptionS1, ..., ExceptionSM);
};

is represented by two Java interface methods 

Type getName() throws ExceptionG1, ..., ExceptionGM;
void setName(Type value) throws ExceptionS1, ..., ExceptionSM;

If the attribute is marked readonly, then there is no set method. Whether or not the attribute is marked bound has no impact on the signatures of the generated Java methods.

A UNO interface method of the form 

Type0 name([in] Type1 arg1, [out] Type2 arg2, [inout] Type3 arg3) raises (Exception1, ..., ExceptionN); 

is represented by a Java interface method 

Type0 name(Type1 arg1, Type2[] arg2, Type3[] arg3) throws Exception1, ..., ExceptionN; 

Whether or not the UNO method is marked oneway has no impact on the signature of the generated Java method. As can be seen, out and inout parameters are handled specially. To help explain this, take the example UNOIDL definitions

struct FooStruct {
   long nval;

    string strval;

}; 

 

interface XFoo { 

    string funcOne([in] string value);

    FooStruct funcTwo([inout] FooStruct value);

    sequence<byte> funcThree([out] sequence<byte> value);
};

The semantics of a UNO method call are such that the values of any in or inout parameters are passed from the caller to the callee, and, if the method is not marked oneway and the execution terminated successfully, the callee passes back to the caller the return value and the values of any out or inout parameters. Thus, the handling of in parameters and the return value maps naturally to the semantics of Java method calls. UNO out and inout parameters, however, are mapped to arrays of the corresponding Java types. Each such array must have at least one element (i.e., its length must be at least one; practically, there is no reason why it should ever be larger). Therefore, the Java interface corresponding to the UNO interface XFoo looks like the following:

public interface XFoo extends com.sun.star.uno.XInterface {
   String funcOne(String value);

    FooStruct funcTwo(FooStruct[] value);

    byte[] funcThree(byte[][] value);
}

This is how FooStruct would be mapped to Java:

public class FooStruct {
   public int nval;

    public String strval;

 

    public FooStruct() {

        strval="";

    }

 

    public FooStruct(int nval, String strval) {

        this.nval = nval;

        this.strval = strval;

    }
}

When providing a value as an inout parameter, the caller has to write the input value into the element at index zero of the array. When the function returns successfully, the value at index zero reflects the output value, which may be the unmodified input value, a modified copy of the input value, or a completely new value. The object obj implements XFoo:

// calling the interface in Java
obj.funcOne(null);                             // error, String value is null

obj.funcOne("");                               // OK

 

FooStruct[] inoutstruct= new FooStruct[1]; 

obj.funcTwo(inoutstruct);                      // error, inoutstruct[0] is null

 

inoutstruct[0]= new FooStruct();               // now we initialize inoutstruct[0]
obj.funcTwo(inoutstruct);                      // OK

When a method receives an argument that is an out parameter, upon successful return, it has to provide a value by storing it at index null of the array.

// method implementations of interface XFoo
public String funcOne(/*in*/ String value) {

  assert value != null;                        // otherwise, it is a bug of the caller

  return null;                                 // error; instead use: return "";

 

public FooStruct funcTwo(/*inout*/ FooStruct[] value) { 

  assert value != null && value.length >= 1 && value[0] != null;

  value[0] = null;                             // error; instead use: value[0] = new FooStruct();

  return null;                                 // error; instead use: return new FooStruct();

 

public byte[] funcThree(/*out*/ byte[][] value) { 

  assert value != null && value.length >= 1;

  value[0] = null;                             // error; instead use: value[0] = new byte[0];

  return null;                                 // error; instead use: return new byte[0];
}

Mapping of UNOIDL Typedefs

UNOIDL typedefs are not visible in the Java language binding. Each occurrence of a typedef is replaced with the aliased type when mapping from UNOIDL to Java. 

Mapping of Individual UNOIDL Constants

An individual UNOIDL constant 

module example {
   const long USERFLAG = 1;
};

is mapped to a public Java interface with the same name: 

package example; 

 

public interface USERFLAG { 

    int value = 1;
}

Note that the use of individual constants is deprecated. 

Mapping of UNOIDL Constant Groups

A UNOIDL constant group 

module example {
   constants User {

        const long FLAG1 = 1;

        const long FLAG2 = 2;

        const long FLAG3 = 3;

    };
};

is mapped to a public Java interface with the same name: 

package example; 

 

public interface User { 

    int FLAG1 = 1;

    int FLAG2 = 2;

    int FLAG3 = 3;
}

Each constant defined in the group is mapped to a field of the interface with the same name and corresponding type and value. 

Mapping of UNOIDL Modules

A UNOIDL module is mapped to a Java package with the same name. This follows from the fact that each named UNO and UNOIDL entity is mapped to a Java class with the same name. (UNOIDL uses “::” to separate the individual identifiers within a name, as in “com::sun::star::uno”, whereas UNO itself and Java both use “.”, as in “com.sun.star.uno”; therefore, the name of a UNOIDL entity has to be converted in the obvious way before it can be used as a name in Java.) UNO and UNOIDL entities not enclosed in any module (that is, whose names do not contain any “.” or “::”, respectively), are mapped to Java classes in an unnamed package.

Mapping of Services

A new-style services is mapped to a public Java class with the same name. The class has one or more public static methods that correspond to the explicit or implicit constructors of the service. 

For a new-style service with a given interface type XIfc, an explicit constructor of the form

name([in] Type1 arg1, [in] Type2 arg2) raises (Exception1, ..., ExceptionN); 

is represented by the Java method 

public static XIfc name(com.sun.star.uno.XComponentContext context, Type1 arg1, Type2 arg2)
   throws Exception1, ..., ExceptionN { ... }

A UNO rest parameter (any...) is mapped to a Java rest parameter (java.lang.Object...) in Java 1.5, and to java.lang.Object[] in older versions of Java.

If a new-style service has an implicit constructor, the corresponding Java method is of the form 

public static XIfc create(com.sun.star.uno.XComponentContext context) { ... } 

The semantics of both explicit and implicit service constructors in Java are as follows: 

Old-style services are not mapped into the Java language binding. 

Mapping of Singletons

A new-style singleton of the form 

singleton Name: XIfc; 

is mapped to a public Java class with the same name. The class has a single method 

public static XIfc get(com.sun.star.uno.XComponentContext context) { ... } 

The semantics of such a singleton getter method in Java are as follows: 

Old-style singletons are not mapped into the Java language binding. 

Inexact approximation of UNO Value Semantics

Some UNO types that are generally considered to be value types are mapped to reference types in Java. Namely, these are the UNO types string, type, any, and the UNO sequence, enum, struct, and exception types. The problem is that when a value of such a type (a Java object) is used

then Java does not create a clone of that object, but instead shares the object via multiple references to it. If the object is now modified through any one of its references, all other references observe the modification, too. This violates the intended value semantics. 

The solution chosen in the Java language binding is to forbid modification of any Java objects that are used to represent UNO values in any of the situations listed above. Note that for Java objects that represent values of the UNO type string, or a UNO enum type, this is trivially warranted, as the corresponding Java types are immutable. This would also hold for the UNO type type, if the Java class com.sun.star.Type were final.

In the sense used here, modifying a Java object A includes modifying any other Java object B that is both (1) reachable from A by following one or more references, and (2) used to represent a UNO value in any of the situations listed above. For a Java object that represents a UNO any value, the restriction to not modify it only applies to a wrapping object of type com.sun.star.uno.Any (which should really be immutable), or to an unwrapped object that represents a UNO value of type string or type, or of a sequence, enum, struct or exception type.

Note that the types java.lang.Boolean, java.lang.Byte, java.lang.Short, java.lang.Integer, java.lang.Long, java.lang.Float, java.lang.Double, and java.lang.Character, used to represent certain UNO values as any values or as parametric members of instantiated polymorphic struct types, are immutable, anyway, and so need not be considered specially here.

3.4.2  C++ Language Binding

This chapter describes the UNO C++ language binding. It provides an experienced C++ programmer the first steps in UNO to establish UNO interprocess connections to a remote OpenOffice.org and to use its UNO objects.  

Library Overview

Illustration 3.16: Shared Libraries for C++ UNO gives an overview about the core libraries of the UNO component model.

Overview about the base shared librariesIllustration 3.16: Shared Libraries for C++ UNO

These shared libraries can be found in the <officedir>/program folder of your OpenOffice.org installation. The label (C) in the illustration above means C linkage and (C++) means C++ linkage. For all libraries, a C++ compiler to build is required.

The basis for all UNO libraries is the sal library. It contains the system abstraction layer (sal) and additional runtime library functionality, but does not contain any UNO-specific information. The commonly used C-functions of the sal library can be accessed through C++ inline wrapper classes. This allows functions to be called from any other programming language, because most programming languages have some mechanism to call a C function.

The salhelper library is a small C++ library which offers additional runtime library functionality, that could not be implemented inline.  

The cppu (C++ UNO) library is the core UNO library. It offers methods to access the UNO type library, and allows the creation, copying and comparing values of UNO data types in a generic manner. Moreover, all UNO bridges (= mappings + environments) are administered in this library.

The examples msci_uno.dll, libsunpro5_uno.so and libgcc2_uno.so are only examples for language binding libraries for certain C++ compilers.

The cppuhelper library is a C++ library that contains important base classes for UNO objects and functions to bootstrap the UNO core. C++ Components and UNO programs have to link the cppuhelper library. 

All the libraries shown above will be kept compatible in all future releases of UNO. You will be able to build and link your application and component once, and run it with the current and later versions of OpenOffice.org. 

System Abstraction Layer

C++ UNO client programs and C++ UNO components use the system abstraction layer (sal) for types, files, threads, interprocess communication, and string handling. The sal library offers operating system dependent functionality as C functions. The aim is to minimize or to eliminate operating system dependent #ifdef in libraries above sal. Sal offers high performance access because sal is a thin layer above the API offered by each operating system.

Note graphics marks a special text section

In OpenOffice.org GUI APIs are encapsulated in the vcl library. 

Sal exports only C symbols. The inline C++ wrapper exists for convenience. Refer to the UNO C++ reference that is part of the OpenOffice.org SDK or in the References section of udk.openoffice.org to gain a full overview of the features provided by the sal library. In the following sections, the C++ wrapper classes will be discussed. The sal types used for UNO types are discussed in section 3.4.2 Professional UNO - UNO Language Bindings - C++ Language Binding - Type Mappings. If you want to use them, look up the names of the appropriate include files in the C++ reference.

File Access

The classes listed below manage platform independent file access. They are C++ classes that call corresponding C functions internally. 

An unfamiliar concept is the use of absolute filenames throughout the whole API. In a multithreaded program, the current working directory cannot be relied on, thus relative paths must be explicitly made absolute by the caller. 

Threadsafe Reference Counting

The functions osl_incrementInterlockedCount() and osl_decrementInterlockedCount() in the global C++ namespace increase and decrease a 4-byte counter in a threadsafe manner. This is needed for reference counted objects. Many UNO APIs control object lifetime through refcounting. Since concurrent incrementing the same counter does not increase the reference count reliably, these functions should be used. This is faster than using a mutex on most platforms.

Threads and Thread Synchronization

The class osl::Thread is meant to be used as a base class for your own threads. Overwrite the run() method.

The following classes are commonly used synchronization primitives: 

osl::Mutex 

Socket and Pipe

The following classes allow you to use interprocess communication in a platform independent manner: 

Strings

The classes rtl::OString (8-bit, encoded) and rtl::OUString (16-bit, UTF-16) are the base-string classes for UNO programs. The strings store their data in a heap memory block. The string is refcounted and incapable of changing, thus it makes copying faster and creation is an expensive operation. An OUString can be created using the static function OUString::createFromASCII() or it can be constructed from an 8-bit string with encoding using this constructor:

OUString( const sal_Char * value,  

        sal_Int32 length,

        rtl_TextEncoding encoding,

        sal_uInt32 convertFlags = OSTRING_TO_OUSTRING_CVTFLAGS );

It can be converted into an 8-bit string, for example, for printf() using the rtl::OUStringTo­OString() function that takes an encoding, such as RTL_TEXTENCODING_ASCII_US.

For fast string concatenation, the classes rtl::OStringBuffer and rtl::OUStringBuffer should be used, because they offer methods to concatenate strings and numbers. After preparing a new string buffer, use the makeStringAndClear() method to create the new OUString or OString. The following example illustrates this:

    sal_Int32 n = 42;

    double pi = 3.14159;

 

    // create a buffer with a suitable size, rough guess is sufficient

    // stringbuffer extends if necessary

    OUStringBuffer buf( 128 );

 

    // append an ascii string

    buf.appendAscii( "pi ( here " );

 

    // numbers can be simply appended

    buf.append( pi );

    // RTL_CONSTASCII_STRINGPARAM()

    // lets the compiler count the stringlength, so this is more efficient than

    // the above appendAscii call, where the length of the string must be calculated at

    // runtime

    buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(" ) multiplied with " ) );

    buf.append( n );

    buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(" gives ") );

    buf.append( (double)( n * pi ) );

    buf.appendAscii( RTL_CONSTASCII_STRINGPARAM( "." ) );

 

    // now transfer the buffer into the string.

    // afterwards buffer is empty and may be reused again !

    OUString string = buf.makeStringAndClear();

 

    // You could of course use the OStringBuffer directly to get an OString

    OString oString = rtl::OUStringToOString( string , RTL_TEXTENCODING_ASCII_US );

 

    // just to print something

    printf( "%s\n" ,oString.getStr() );

Establishing Interprocess Connections

Any language binding supported by UNO establishes interprocess connections using a local service manager to create the services necessary to connect to the office. Refer to chapter 3.3.1 Professional UNO - UNO Concepts - UNO Interprocess Connections for additional information. The following client program connects to a running office and retrieves the com.sun.star.lang.XMultiServiceFactory in C++: (ProfUNO/CppBinding/office_connect.cxx)

#include <stdio.h> 

 

#include <cppuhelper/bootstrap.hxx> 

#include <com/sun/star/bridge/XUnoUrlResolver.hpp> 

#include <com/sun/star/lang/XMultiServiceFactory.hpp> 

 

using namespace com::sun::star::uno; 

using namespace com::sun::star::lang; 

using namespace com::sun::star::bridge; 

using namespace rtl; 

using namespace cppu; 

 

int main( ) 

    // create the initial component context

    Reference< XComponentContext > rComponentContext =

                defaultBootstrap_InitialComponentContext();

 

    // retrieve the service manager from the context

    Reference< XMultiComponentFactory > rServiceManager =

                rComponentContext->getServiceManager();

 

    // instantiate a sample service with the service manager.

    Reference< XInterface > rInstance =

                rServiceManager->createInstanceWithContext(

            OUString::createFromAscii("com.sun.star.bridge.UnoUrlResolver" ),

            rComponentContext );

       

    // Query for the XUnoUrlResolver interface

    Reference< XUnoUrlResolver > rResolver( rInstance, UNO_QUERY );

 

    if( ! rResolver.is() )

    {

                printf( "Error: Couldn't instantiate com.sun.star.bridge.UnoUrlResolver service\n" );

                return 1;

    }

    try

    {

                // resolve the uno-URL

                rInstance = rResolver->resolve( OUString::createFromAscii(

            "uno:socket,host=localhost,port=2002;urp;StarOffice.ServiceManager" ) );

       

        if( ! rInstance.is() )

        {

            printf( "StarOffice.ServiceManager is not exported from remote process\n" );

            return 1;

        }

 

                // query for the simpler XMultiServiceFactory interface, sufficient for scripting

                Reference< XMultiServiceFactory > rOfficeServiceManager (rInstance, UNO_QUERY);

 

                if( ! rOfficeServiceManager.is() )

        {

            printf( "XMultiServiceFactory interface is not exported\n" );

            return 1;

        }

 

        printf( "Connected sucessfully to the office\n" );

    }       

    catch( Exception &e )

    {

        OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );

        printf( "Error: %s\n", o.pData->buffer );

        return 1;

    }

    return 0;

Transparent Use of Office UNO Components

When writing C++ client applications, the office component context can be obtained in a more transparent way. For more details see section 3.4.1 Professional UNO - UNO Language Bindings - Java Language Binding - Transparent Use of Office UNO Components.

The bootstrap function

Also for C++, a bootstrap function is provided, which bootstraps the component context from a UNO installation. An example for a simple client application shows the following code snipplet: (ProfUNO/SimpleBootstrap_cpp/SimpleBootstrap_cpp.cxx

// get the remote office component context 

Reference< XComponentContext > xContext( ::cppu::bootstrap() ); 

 

// get the remote office service manager 

Reference< XMultiComponentFactory > xServiceManager( 

    xContext->getServiceManager() );

 

// get an instance of the remote office desktop UNO service 

// and query the XComponentLoader interface 

Reference < XComponentLoader > xComponentLoader( 

    xServiceManager->createInstanceWithContext( OUString(

    RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.frame.Desktop" ) ),

    xContext ), UNO_QUERY_THROW );

The ::cppu::bootstrap() function is implemented in a similar way as the Java com.sun.star.comp.helper.Bootstrap.bootstrap() method. It first bootstraps a local component context by calling the ::cppu::defaultBootstrap_InitialComponentContext() function and then tries to establish a named pipe connection to a running office by using the com.sun.star.bridge.UnoUrlResolver service. If no office is running, an office process is started. If the connection succeeds, the remote component context is returned.

Pay attention to the following important text section

The ::cppu::bootstrap() function is only available since OpenOffice.org 2.0.

SDK tooling

For convenience , the OpenOffice.org Software Development Kit (SDK) provides some tooling for writing C++ client applications. 

Application Loader

A C++ client application that uses UNO is linked to the C++ UNO libraries, which can be found in the program directory of a UNO installation. When running the client application, the C++ UNO libraries are found only, if the UNO program directory is included in the PATH (Windows) or LD_LIBRARY_PATH (Unix/Linux) environment variable.

As this requires the knowledge of the location of a UNO installation, the SDK provides an application loader (unoapploader.exe for Windows, unoapploader for Unix/Linux), which detects a UNO installation on the system and adds the program directory of the UNO installation to the PATH / LD_LIBRARY_PATH environment variable. After that, the application process is loaded and started, whereby the new process inherits the environment of the calling process, including the modified PATH / LD_LIBRARY_PATH environment variable.

The SDK tooling allows to build a client executable file (e.g. SimpleBootstrap_cpp for Unix/Linux), which can be invoked by

./SimpleBootstrap_cpp

In this case, the SimpleBootstrap_cpp executable is simply the renamed unoapploader executable. All the application code is part of a second executable file, which must have the same name as the first executable, but prefixed by a underscore '_'; that means in the example above the second executable is named _SimpleBootstrap_cpp.

On the Unix/Linux platforms the application loader writes error messages to the stderr stream. On the Windows platform error messages are written to the error file <application name>-error.log in the application's executable file directory. If this fails, the error file is written to the directory designated for temporary files.

Finding a UNO Installation

A UNO installation can be specified by the user by setting the UNO_PATH environment variable to the program directory of a UNO installation, e.g.

setenv UNO_PATH /opt/OpenOffice.org/program

If no UNO installation is specified by the user, the default installation on the system is taken. 

On the Windows platform, the default installation is read from the default value of the key 'Software\OpenOffice.org\UNO\InstallPath' from the root key HKEY_CURRENT_USER in the Windows Registry. If this key is missing, the key is read from the root key HKEY_LOCAL_MACHINE. 

On the Unix/Linux platforms, the default installation is found from the PATH environment variable. This requires that the soffice executable or a symbolic link is in one of the directories listed in the PATH environment variable.

Type Mappings

Mapping of Simple Types

The following table shows the mapping of simple UNO types to the corresponding C++ types. 

UNO 

C++ 

void 

void 

boolean 

sal_Bool 

byte 

sal_Int8 

short 

sal_Int16 

unsigned short 

sal_uInt16 

long 

sal_Int32 

unsigned long 

sal_uInt32 

hyper 

sal_Int64 

unsigned hyper 

sal_uInt64 

float 

float 

double 

double 

char 

sal_Unicode 

string 

rtl::OUString 

type 

com::sun::star::uno::Type 

any 

com::sun::star::uno::Any 

For historic reasons, the UNO type boolean is mapped to some C++ type sal_Bool, which has two distinct values sal_False and sal_True, and which need not be the C++ bool type. The mapping between the values of UNO boolean and sal_False and sal_True is straightforward, but it is an error to use any potential value of sal_Bool that is distinct from both sal_False and sal_True.

The UNO integer types are mapped to C++ integer types with ranges that are guaranteed to be at least as large as the ranges of the corresponding UNO types. However, the ranges of the C++ types might be larger, in which case it would be an error to use values outside of the range of the corresponding UNO types within the context of UNO. Currently, it would not be possible to create C++ language bindings for C++ environments that offer no suitable integral types that meet the minimal range guarantees. 

The UNO floating point types float and double are mapped to C++ floating point types float and double, which must be capable of representing at least all the values of the corresponding UNO types. However, the C++ types might be capable of representing more values, for which it is implementation-defined how they are handled in the context of UNO. Currently, it would not be possible to create C++ language bindings for C++ environments that offer no suitable float and double types.

The UNO char type is mapped to the integral C++ type sal_Unicode, which is guaranteed to at least encompass the range from 0 to 65535. Values of UNO char are mapped to values of sal_Unicode in the obvious manner. If the range of sal_Unicode is larger, it is an error to use values outside of that range.

For the C++ typedef types sal_Bool, sal_Int8, sal_Int16, sal_Int32, sal_Int64, and sal_Unicode, it is guaranteed that no two of them are synonyms for the same fundamental C++ type. This guarantee does not extend to the three types sal_uInt8, sal_uInt16, and sal_uInt32, however.

Mapping of String

The mapping between the UNO string type and rtl::OUString is straightforward, except for two details:

static sal_Unicode const chars[] = { 0xD800 }; 

rtl::OUString(chars, 1); 

is illegal in this context, while the string 

static sal_Unicode const chars[] = { 0xD800, 0xDC00 }; 

rtl::OUString(chars, 2); 

would be legal. See www.unicode.org for more information on the details of Unicode.

Mapping of Type

The UNO type type is mapped to com::sun::star::uno::Type. It holds the name of a type and the com.sun.star.uno.TypeClass. The type allows you to obtain a com::sun::star::uno::TypeDescription that contains all the information defined in the IDL. For a given UNO type, a corresponding com::sun::star::Type instance can be obtained through the cppu::UnoTxpe class template:

// Get the UNO type long: 

com::sun::star::uno::Type longType = cppu::UnoType< sal_Int32 >::get(); 

 

// Get the UNO type char: 

com::sun::star::uno::Type charTpye = cppu::UnoType< cppu::UnoCharType >::get(); 

 

// Get the UNO type string: 

com::sun::star::uno::Type stringType = cppu::UnoType< rtl::OUString >::get(); 

 

// Get the UNO interface type com.sun.star.container.XEnumeration: 

com::sun::star::uno::Type enumerationType = 

    cppu::UnoType< com::sun::star::container::XEnumeration >::get();

Some C++ types that represent UNO types cannot be used as C++ template arguments, or ambiguously represent more than one UNO type, so there are special C++ types cppu::UnoVoidType, cppu::UnoUnsignedShortType, cppu::UnoCharType, and cppu::UnoSequenceType that can be used as arguments for cppu::UnoType in those cases.

The overloaded getCppuType function was an older mechanism to obtain com::sun::star::uno::Type instances. It is deprecated now (certain uses of getCppuType in template code would not work as intended), and cppu::UnoType should be used instead.

Mapping of Any

The IDL any is mapped to com::sun::star::uno::Any. It holds an instance of an arbitrary UNO type. Only UNO types can be stored within the any, because the data from the type library are required for any handling.

A default constructed Any contains the void type and no value. You can assign a value to the Any using the operator <<= and retrieve a value using the operator >>=.

// default construct an any 

Any any; 

 

sal_Int32 n = 3; 

 

// Store the value into the any 

any <<= n; 

 

// extract the value again 

sal_Int32 n2; 

any >>= n2; 

assert( n2 == n ); 

assert( 3 == n2 ); 

The extraction operator >>= carries out widening conversions when no loss of data can occur, but data cannot be directed downward. If the extraction was successful, the operator returns sal_True, otherwise sal_False.

Any any; 

sal_Int16 n = 3; 

any <<= n; 

 

 

sal_Int8 aByte = 0; 

sal_Int16 aShort = 0;
sal_Int32 aLong = 0;

 

// this will succeed, conversion from int16 to int32 is OK. 

assert( any >>= aLong ); 

assert( 3 == aLong ); 

 

// this will succeed, conversion from int16 to int16 is OK 

assert( any >>= aShort ); 

assert( 3 == aShort  

 

// the following two assertions will FAIL, because conversion  

// from int16 to int8 may involve loss of data.. 

 

// Even if a downcast is possible for a certain value, the operator refuses to work 

assert( any >>= aByte ); 

assert( 3 == aByte ); 

Instead of using the operator for extracting, you can also get a pointer to the data within the Any. This may be faster, but it is more complicated to use. With the pointer, care has to be used during  casting and proper type handling, and the lifetime of the Any must exceed the pointer usage.

Any a = ...; 

if( a.getTypeClass() == TypeClass_LONG && 3 ==  *(sal_Int32 *)a.getValue() )

You can also construct an Any from a pointer to a C++ UNO type that can be useful. For instance: 

Any foo() 

    sal_Int32 i = 3;

    if( ... )

        i = ..;

    return Any( &i, cppu::UnoType< sal_Int32 >::get() );

Mapping of Struct Types

A plain UNO struct type is mapped to a C++ struct with the same name. Each member of the UNO struct type is mapped to a public data member with the same name and corresponding type. The C++ struct provides a default constructor which initializes all members with default values, and a constructor which takes explicit values for all members. If a plain struct type inherits from another struct type, the generated C++ struct derives from the C++ struct corresponding to the inherited UNO struct type. 

A polymorphic UNO struct type template with a list of type parameters is mapped to a C++ struct template with a corresponding list of type parameters. For example, the C++ template corresponding to com.sun.star.beans.Optional looks something like 

template< typename T > struct Optional {
   sal_Bool IsPresent;

    T Value;

 

    Optional(): IsPresent(sal_False), Value() {}

 

    Optional(sal_Bool theIsPresent, T const & theValue): IsPresent(theIsPresent), Value(theValue) {}
};

As can be seen in the example above, the default constructor uses default initialization to give values to any parametric data members. This has a number of consequences: 

On some platforms, the C++ typedef types sal_uInt16 (representing the UNO type unsigned short) and sal_Unicode (representing the UNO type char) are synonyms for the same fundamental C++ type. This could lead to problems when either of those types is used as a type argument of a polymorphic struct type. The chosen solution is to generally forbid the (deprecated) UNO types unsigned short, unsigned long, and unsigned hyper as type arguments of polymorphic struct types.

getCppuType(static_cast< com::sun::star::beans::Optional< sal_Unicode > >(0)) 

and 

getCppuType(static_cast< com::sun::star::beans::Optional< sal_uInt16 > >(0)) 

cannot return different data for the two different UNO types (as the two function calls are to the same identical function on those platforms). The chosen solution is to generally forbid the (deprecated) UNO types unsigned short, unsigned int, and unsigned long as type arguments of polymorphic struct types.

Mapping of Interface Types

A value of a UNO interface type (which is a null reference or a reference to an object implementing the given interface type) is mapped to the template class:

template< class t > 

com::sun::star::uno::Reference< t >  

The template is used to get a type safe interface reference, because only a correctly typed interface pointer can be assigned to the reference. The example below assigns an instance of the desktop service to the rDesktop reference:

// the xSMgr reference gets constructed somehow 

    ...

    // construct a deskop object and acquire it

    Reference< XInterface > rDesktop = xSMgr->createInstance(

    OUString::createFromAscii("com.sun.star.frame.Desktop"”));

    ...

    // reference goes out of scope now, release is called on the interface

The constructor of Reference calls acquire() on the interface and the destructor calls release() on the interface. These references are often called smart pointers. Always use the Reference template consistently to avoid reference counting bugs.

The Reference class makes it simple to invoke queryInterface() for a certain type:

// construct a deskop object and acquire it 

Reference< XInterface > rDesktop = xSMgr->createInstance(

    OUString::createFromAscii("com.sun.star.frame.Desktop"));

 

// query it for the XFrameLoader interface 

Reference< XFrameLoader > rLoader( rDesktop , UNO_QUERY );

 

// check, if the frameloader interface is supported 

if( rLoader.is() ) 

    // now do something with the frame loader

    ...

The UNO_QUERY is a dummy parameter that tells the constructor to query the first constructor argument for the XFrameLoader interface. If the queryInterface() returns successfully, it is assigned to the rLoader reference. You can check if querying was successful by calling is() on the new reference.

Methods on interfaces can be invoked using the operator ->:

xSMgr->createInstance(...); 

The operator ->() returns the interface pointer without acquiring it, that is, without incrementing the refcount.

Tip graphics marks a hint section in the text

If you need the direct pointer to an interface for some purpose, you can also call get() at the reference class.

You can explicitly release the interface reference by calling clear()at the reference or by assigning a default constructed reference.

You can check if two interface references belong to the same object using the operator ==.

Mapping of Sequence Types

An IDL sequence is mapped to:

template< class t > 

com::sun::star::uno::Sequence< t >  

The sequence class is a reference to a reference counted handle that is allocated on the heap. 

The sequence follows a copy-on-modify strategy. If a sequence is about to be modified, it is checked if the reference count of the sequence is 1. If this is the case, it gets modified directly, otherwise a copy of the sequence is created that has a reference count of 1. 

A sequence can be created with an arbitrary UNO type as element type, but do not use a non-UNO type. The full reflection data provided by the type library are needed for construction, destruction and comparison. 

You can construct a sequence with an initial number of elements. Each element is default constructed. 

    // create an integer sequence with 3 elements,

    // elements default to zero.

    Sequence< sal_Int32 > seqInt( 3 );

 

    // get a read/write array pointer (this method checks for

    // the refcount and does a copy on demand).

    sal_Int32 *pArray = seqInt.getArray();

 

    // if you know, that the refocunt is one

    // as in this case, where the sequence has just been

    // constructed, you could avoid the check,

    // which is a C-call overhead,

    // by writing sal_Int32 *pArray = (sal_Int32*) seqInt.getConstArray();

 

    // modify the members

    pArray[0] = 4;

    pArray[1] = 5;

    pArray[2] = 3;

You can also initialize a sequence from an array of the same type by using a different constructor. The new sequence is allocated on the heap and all elements are copied from the source. 

    sal_Int32 sourceArray[3] = {3,5,3};

 

    // result is the same as above, but we initialize from a buffer.

    Sequence< sal_Int32 > seqInt( sourceArray , 3 );

Complex UNO types like structs can be stored within sequences, too: 

{

    // construct a sequence of Property structs,

    // the structs are default constructed

    Sequence< Property > seqProperty(2);

    seqProperty[0].Name = OUString::createFromAscii( "A" );

    seqProperty[0].Handle = 0;

    seqProperty[1].Name = OUString::createFromAscii( "B" );

    seqProperty[1].Handle = 1;

 

    // copy construct the sequence (The refcount is raised)

    Sequence< Property > seqProperty2 = seqProperty;

                               

    // access a sequence

    for( sal_Int32 i = 0 ; i < seqProperty.getLength() ; i ++ )

    {

        // Please NOTE : seqProperty.getArray() would also work, but  

        //               it is more expensive, because a

        //               unnessecary copy construction

        //               of the sequence takes place.

        printf( "%d\n" , seqProperty.getConstArray()[i].Handle );

    }

The size of sequences can be changed using the realloc() method, which takes the new number of elements as a parameter. For instance:

// construct an empty sequence 

Sequence < Any > anySequence; 

 

// get your enumeration from somewhere 

Reference< XEnumeration > rEnum = ...; 

 

// iterate over the enumeration 

while( rEnum->hasMoreElements() ) 

{       

    anySequence.realloc( anySequence.getLength() + 1 );

    anySequence[anySequence.getLength()-1] = rEnum->nextElement();

The above code shows an enumeration is transformed into a sequence,using an inefficient method. The realloc() default constructs a new element at the end of the sequence. If the sequence is shrunk by realloc, the elements at the end are destroyed.

The sequence is meant as a transportation container only, therefore it lacks methods for efficient insertion and removal of elements. Use a C++ Standard Template Library vector as an intermediate container to manipulate a list of elements and finally copy the elements into the sequence. 

Sequences of a specific type are a fully supported UNO type. There can also be a sequence of sequences. This is similar to a multidimensional array with the exception that each row may vary in length. For instance: 

    sal_Int32 a[ ] = { 1,2,3 }, b[] = {4,5,6}, c[] = {7,8,9,10};

    Sequence< Sequence< sal_Int32 > > aaSeq ( 3 );

    aaSeq[0] = Sequence< sal_Int32 >( a , 3 );

    aaSeq[1] = Sequence< sal_Int32 >( b , 3 );

    aaSeq[2] = Sequence< sal_Int32 >( c , 4 );

is a valid sequence of sequence< sal_Int32>. 

The maximal length of a com::sun::star::uno::Sequence is limited; therefore, it is an error if a UNO sequence that is too long is used in the context of the C++ language binding.

Mapping of Services

A new-style service is mapped to a C++ class with the same name. The class has one or more public static member functions that correspond to the explicit or implicit constructors of the service. 

For a new-style service with a given interface type XIfc, an explicit constructor of the form

name([in] Type1 arg1, [in] Type2 arg2) raises (Exception1, ..., ExceptionN); 

is represented by the C++ member function 

public:
static com::sun::star::uno::Reference< XIfc > name(

    com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext > const & context,

    Type1 arg1, Type2 arg2)
   throw (Exception1, ..., ExceptionN, com::sun::star::uno::RuntimeException) { ... }

If a service constructor has a rest parameter (any...), it is mapped to a parameter of type com::sun::star::uno::Sequence< com::sun::star::uno::Any > const & in C++.

If a new-style service has an implicit constructor, the corresponding C++ member function is of the form 

public:
static com::sun::star::uno::Reference< XIfc > create(

    com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext > const & context)
   throw (com::sun::star::uno::RuntimeException) { ... }

The semantics of both explicit and implicit service constructors in C++ are as follows. They are the same as for Java: 

Old-style services are not mapped into the C++ language binding. 

Mapping of Singletons

A new-style singleton of the form 

singleton Name: XIfc; 

is mapped to a C++ class with the same name. The class has a single member function 

public:
static com::sun::star::uno::Reference< XIfc > get(

    com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext > const & context)
   throw (com::sun::star::uno::RuntimeException) { ... }

The semantics of such a singleton getter function in C++ are as follows (they are the same as for Java): 

Old-style services are not mapped into the C++ language binding. 

Using Weak References

The C++ binding offers a method to hold UNO objects weakly, that is, not holding a hard reference to it. A hard reference prevents an object from being destroyed, whereas an object that is held weakly can be deleted anytime. The advantage of weak references is used to avoid cyclic references between objects.

An object must actively support weak references by supporting the com.sun.star.uno.XWeak interface. The concept is explained in detail in chapter 3.3.8 Professional UNO - UNO Concepts - Lifetime of UNO Objects.

Weak references are often used for caching. For instance, if you want to reuse an existing object, but do not want to hold it forever to avoid cyclic references. 

Weak references are implemented as a template class: 

template< class t > 

class com::sun::star::uno::WeakReference<t>  

You can simply assign weak references to hard references and conversely. The following examples stress this: 

// forward declaration of a function that  

Reference< XFoo > getFoo(); 

 

int main() 

    // default construct a weak reference.

    // this reference is empty

    WeakReference < XFoo > weakFoo;

    {

        // obtain a hard reference to an XFoo object

        Reference< XFoo > hardFoo = getFoo();

        assert( hardFoo.is() );

 

        // assign the hard reference to weak referencecount

        weakFoo = hardFoo;

 

        // the hardFoo reference goes out of scope. The object itself

        // is now destroyed, if no one else keeps a reference to it.

        // Nothing happens, if someone else still keeps a reference to it

    }

 

    // now make the reference hard again

    Reference< XFoo > hardFoo2 = weakFoo;

 

       

    // check, if this was successful

    if( hardFoo2.is() )

    {

        // the object is still alive, you can invoke calls on it again

        hardFoo2->foo();

    }

    else

    {

        // the objects has died, you can't do anything with it anymore.

    }

A call on a weak reference can not be invoked directly. Make the weak reference hard and check whether it succeeded or not. You never know if you will get the reference, therefore always handle both cases properly.  

It is more expensive to use weak references instead of hard references. When assigning a weak reference to a hard reference, a mutex gets locked and some heap allocation may occur. When the object is located in a different process, at least one remote call takes place, meaning an overhead of approximately a millisecond. 

The XWeak mechanism does not support notification at object destruction. For this purpose, objects must export XComponent and add com.sun.star.lang.XEventListener.

Exception Handling in C++

For throwing and catching of UNO exceptions, use the normal C++ exception handling mechanisms. Calls to UNO interfaces may only throw the com::sun::star::uno::Exception or derived exceptions. The following example catches every possible exception:

try  

    Reference< XInterface > rInitialObject =

        xUnoUrlResolver->resolve( OUString::createFromAsci(

            “uno:socket,host=localhost,port=2002;urp;StarOffice.ServiceManager” ) );

catch( com::sun::star::uno::Exception &e ) 

    OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );

    printf( "An error occurred: %s\n", o.pData->buffer );

If you want to react differently for each possible exception type, look up the exceptions that may be thrown by a certain method. For instance the resolve() method in com.sun.star.bridge.XUnoUrlResolver is allowed to throw three kinds of exceptions. Catch each exception type separately:

try 

    Reference< XInterface > rInitialObject =

    xUnoUrlResolver->resolve( OUString::createFromAsci(

        “uno:socket,host=localhost,port=2002;urp;StarOffice.ServiceManager” ) );

catch( ConnectionSetupException &e ) 

    OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );

    printf( "%s\n", o.pData->buffer );

    printf( "couldn't access local resource ( possible security resons )\n" );

catch( NoConnectException &e ) 

    OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );

    printf( "%s\n", o.pData->buffer );

    printf( "no server listening on the resource\n" );

catch( IllegalArgumentException &e ) 

    OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );

    printf( "%s\n", o.pData->buffer );

    printf( "uno URL invalid\n" );

catch( RuntimeException & e ) 

    OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US );

    printf( "%s\n", o.pData->buffer );

    printf( "an unknown error has occurred\n" );

When implementing your own UNO objects (see 4.6 Writing UNO Components - C++ Component), throw exceptions using the normal C++ throw statement:

void MyUnoObject::initialize( const Sequence< Any > & args.getLength() ) throw( Exception )
{

    // we expect 2 elements in this sequence

    if( 2 != args.getLength() )

    {

        // create an error message

        OUStringBuffer buf;

        buf.appendAscii( “MyUnoObject::initialize, expected 2 args, got ” );

        buf.append( args.getLength() );

        buf.append( “.” );

 

        // throw the exception

        throw Exception( buf.makeStringAndClear() , *this );

    }

    ...

Note that only exceptions derived from com::sun::star::uno::Exception may be thrown at UNO interface methods. Other exceptions (for instance the C++ std::exception) cannot be bridged by the UNO runtime if the caller and called object are not within the same UNO Runtime Environment. Moreover, most current Unix C++ compilers, for instance gcc 3.0.x, do not compile code. During compilation, exception specifications are loosen in derived classes by throwing exceptions other than the exceptions specified in the interface that it is derived. Throwing unspecified exceptions leads to a std::unexpected exception and causes the program to abort on Unix systems.

OpenOffice.org Basic provides access to the OpenOffice.org API from within the office application. It hides the complexity of interfaces and simplifies the use of properties by making UNO objects look like Basic objects. It offers convenient Runtime Library (RTL) functions and special Basic properties for UNO. Furthermore, Basic procedures can be easily hooked up to GUI elements, such as menus, toolbar icons and GUI event handlers. 

This chapter describes how to access UNO using the OpenOffice.org Basic scripting language. In the following sections, OpenOffice.org Basic is referred to as Basic. 

Handling UNO Objects

Accessing UNO Services

UNO objects are used through their interface methods and properties. Basic simplifies this by mapping UNO interfaces and properties to Basic object methods and properties. 

First, in Basic it is not necessary to distinguish between the different interfaces an object supports when calling a method. The following illustration shows an example of an UNO service that supports three interfaces: 

UMl diagram showing an example service with three interfacesIllustration 3.17: Basic Hides Interfaces

In Java and C++, it is necessary to obtain a reference to each interface before calling one of its methods. In Basic, every method of every supported interface can be called directly at the object without querying for the appropriate interface in advance. The '.' operator is used:

    ' Basic

    oExample = getExampleObjectFromSomewhere()

    oExample.doNothing()                ' Calls method doNothing of XFoo1

    oExample.doSomething()                ' Calls method doSomething of XFoo2

    oExample.doSomethingElse(42)        ' Calls method doSomethingElse of XFoo2

 

Additionally, OpenOffice.org Basic interprets pairs of get and set methods at UNO objects as Basic object properties if they follow this pattern: 

SomeType getSomeProperty()

void setSomeProperty(SomeType aValue)

In this pattern, OpenOffice.org Basic offers a property of type SomeType named SomeProperty. This functionality is based on the com.sun.star.beans.Introspection service. For additional details, see 6.2.3 Advanced UNO - Language Bindings - UNO Reflection API.

The get and set methods can always be used directly. In our example service above, the methods getIt() and setIt(), or read and write a Basic property It are used:

    Dim x as Integer

    x = oExample.getIt()    ' Calls getIt method of XFoo3

 

    ' is the same as

 

    x = oExample.It        ' Read property It represented by XFoo3

 

    oExample.setIt( x )    ' Calls setIt method of XFoo3

 

    ' is the same as

 

    oExample.It = x        ' Modify property It represented by XFoo3

 

If there is only a get method, but no associated set method, the property is considered to be read only. 

    Dim x as Integer, y as Integer

    x = oExample.getMore()    ' Calls getMore method of XFoo1

    y = oExample.getLess()    ' Calls getLess method of XFoo1

 

    ' is the same as

 

    x = oExample.More    ' Read property More represented by XFoo1

    y = oExample.Less    ' Read property Less represented by XFoo1

 

    ' but

 

    oExample.More = x    ' Runtime error “Property is read only”

    oExample.Less = y    ' Runtime error “Property is read only”

 

Properties an object provides through com.sun.star.beans.XPropertySet are available through the . operator. The methods of com.sun.star.beans.XPropertySet can be used also. The object oExample2 in the following example has three integer properties Value1, Value2 and Value3 :

    Dim x as Integer, y as Integer, z as Integer

    x = oExample2.Value1

    y = oExample2.Value2

    z = oExample2.Value3

 

    ' is the same as

 

    x = oExample2.getPropertyValue( “Value1” )

    y = oExample2.getPropertyValue( “Value2” )

    z = oExample2.getPropertyValue( “Value3” )

 

    ' and

 

    oExample2.Value1 = x

    oExample2.Value2 = y

    oExample2.Value3 = z

 

    ' is the same as

 

    oExample2.setPropertyValue( “Value1”, x )

    oExample2.setPropertyValue( “Value2”, y )

    oExample2.setPropertyValue( “Value3”, z )

 

Basic uses com.sun.star.container.XNameAccess to provide named elements in a collection through the . operator. However, XNameAccess only provides read access. If a collection offers write access through com.sun.star.container.XNameReplace or com.sun.star.container.XNameContainer, use the appropriate methods explicitly:

    ' oNameAccessible is an object that supports XNameAccess

    ' including the names “Value1”, “Value2”

    x = oNameAccessible.Value1

    y = oNameAccessible.Value2

 

    ' is the same as

 

    x = oNameAccessible.getByName( “Value1” )

    y = oNameAccessible.getByName( “Value2” )

 

    ' but

 

    oNameAccessible.Value1 = x        ' Runtime Error, Value1 cannot be changed

    oNameAccessible.Value2 = y        ' Runtime Error, Value2 cannot be changed

 

    ' oNameReplace is an object that supports XNameReplace

    ' replaceByName() sets the element Value1 to 42

    oNameReplace.replaceByName( "Value1", 42 )

 

Instantiating UNO Services

In Basic, instantiate services using the Basic Runtime Library (RTL) function createUnoService(). This function expects a fully qualified service name and returns an object supporting this service, if it is available:

    oSimpleFileAccess = CreateUnoService( "com.sun.star.ucb.SimpleFileAccess" )

This call instantiates the com.sun.star.ucb.SimpleFileAccess service. To ensure that the function was successful, the returned object can be checked with the IsNull function:

    oSimpleFileAccess = CreateUnoService( "com.sun.star.ucb.SimpleFileAccess" )

    bError = IsNull( oSimpleFileAccess )        ' bError is set to False

 

    oNoService = CreateUnoService( "com.sun.star.nowhere.ThisServiceDoesNotExist" )

    bError = IsNull( oNoService )                ' bError is set to True

Instead of using CreateUnoService() to instantiate a service, it is also possible to get the global UNO com.sun.star.lang.ServiceManager of the OpenOffice.org process by calling GetProcessServiceManager(). Once obtained, use createInstance() directly:

    oServiceMgr = GetProcessServiceManager()

    oSimpleFileAccess = oServiceMgr.createInstance( "com.sun.star.ucb.SimpleFileAccess" )

 

    ' is the same as

 

    oSimpleFileAccess = CreateUnoService( "com.sun.star.ucb.SimpleFileAccess" )

The advantage of GetProcessServiceManager() is that additional information and pass in arguments is received when services are instantiated using the service manager. For instance, to initialize a service with arguments, the createInstanceWithArguments() method of com.sun.star.lang.XMultiServiceFactory has to be used at the service manager, because there is no appropriate Basic RTL function to do that. Example:

    Dim args(1)

    args(0) = "Important information"

    args(1) = "Even more important information"

    oService = oServiceMgr.createInstanceWithArguments _

        ( "com.sun.star.nowhere.ServiceThatNeedsInitialization", args() )

The object returned by GetProcessServiceManager() is a normal Basic UNO object supporting com.sun.star.lang.ServiceManager. Its properties and methods are accessed as described above.

In addition, the Basic RTL provides special properties as API entry points. They are described in more detail in 12.3 OpenOffice.org Basic and Dialogs - Features of OpenOffice.org Basic:

OpenOffice.org Basic RTL Property 

Description 

ThisComponent 

Only exists in Basic code which is embedded in a Writer, Calc, Draw or Impress document. It contains the document model the Basic code is embedded in. 

StarDesktop 

The com.sun.star.frame.Desktop singleton of the office application. It loads document components and handles the document windows. For instance, the document in the top window can be retrieved using
oDoc = StarDesktop.CurrentComponent

Getting Information about UNO Objects

The Basic RTL retrieves information about UNO objects. There are functions to evaluate objects during runtime and object properties used to inspect objects during debugging. 

Checking for interfaces during runtime 

Although Basic does not support the queryInterface concept like C++ and Java, it can be useful to know if a certain interface is supported by a UNO Basic object or not. The function HasUnoInterfaces() detects this.

The first parameter HasUnoInterfaces() expects the object that should be tested. Parameter(s) of one or more fully qualified interface names can be passed to the function next. The function returns True if all these interfaces are supported by the object, otherwise False.

Sub Main 

    Dim oSimpleFileAccess

    oSimpleFileAccess = CreateUnoService( "com.sun.star.ucb.SimpleFileAccess" )

 

    Dim bSuccess

    Dim IfaceName1$, IfaceName2$, IfaceName3$

    IfaceName1$ = "com.sun.star.uno.XInterface"

    IfaceName2$ = "com.sun.star.ucb.XSimpleFileAccess2"

    IfaceName3$ = "com.sun.star.container.XPropertySet"

 

    bSuccess = HasUnoInterfaces( oSimpleFileAccess, IfaceName1$ )

    MsgBox bSuccess    ' Displays True because XInterface is supported

 

    bSuccess = HasUnoInterfaces( oSimpleFileAccess, IfaceName1$, IfaceName2$ )

    MsgBox bSuccess    ' Displays True because XInterface

                       ' and XSimpleFileAccess2 are supported

 

    bSuccess = HasUnoInterfaces( oSimpleFileAccess, IfaceName3$ )

    MsgBox bSuccess    ' Displays False because XPropertySet is NOT supported

 

    bSuccess = HasUnoInterfaces( oSimpleFileAccess, IfaceName1$, IfaceName2$, IfaceName3$ )

    MsgBox bSuccess    ' Displays False because XPropertySet is NOT supported

End Sub 

Testing if an object is a struct during runtime 

As described in the section 3.4.3 Professional UNO - UNO Language Bindings - OpenOffice.org Basic - Type Mappings - Structs above, structs are handled differently from objects, because they are treated as values. Use the IsUnoStruct () function to check it the UNO Basic object represents an object or a struct. This function expects one parameter and returns True if this parameter is a UNO struct, otherwise False. Example:

Sub Main 

    Dim bIsStruct

        ' Instantiate a service

    Dim oSimpleFileAccess

    oSimpleFileAccess = CreateUnoService( "com.sun.star.ucb.SimpleFileAccess" )

    bIsStruct = IsUnoStruct( oSimpleFileAccess )

    MsgBox bIsStruct    ' Displays False because oSimpleFileAccess is NO struct

                        ' Instantiate a Property struct

    Dim aProperty As New com.sun.star.beans.Property

    bIsStruct = IsUnoStruct( aProperty )

    MsgBox bIsStruct    ' Displays True because aProperty is a struct

    bIsStruct = IsUnoStruct( 42 )

    MsgBox bIsStruct    ' Displays False because 42 is NO struct

End Sub 

Testing objects for identity during runtime 

To find out if two UNO OpenOffice.org Basic objects refer to the same UNO object instance, use the function EqualUnoObjects(). Basic is not able to apply the comparison operator = to arguments of type object, for example, If Obj1 = Obj2 Then which leads to a runtime error.

Sub Main 

    Dim bIdentical

    Dim oSimpleFileAccess, oSimpleFileAccess2, oSimpleFileAccess3

        ' Instantiate a service

    oSimpleFileAccess = CreateUnoService( "com.sun.star.ucb.SimpleFileAccess" )

    oSimpleFileAccess2 = oSimpleFileAccess    ' Copy the object reference

    bIdentical = EqualUnoObjects( oSimpleFileAccess, oSimpleFileAccess2 )

    MsgBox bIdentical    ' Displays True because the objects are identical

       ' Instantiate the service a second time

    oSimpleFileAccess3 = CreateUnoService( "com.sun.star.ucb.SimpleFileAccess" )

    bIdentical = EqualUnoObjects( oSimpleFileAccess, oSimpleFileAccess3 )

    MsgBox bIdentical    ' Displays False, oSimpleFileAccess3 is another instance

 

    bIdentical = EqualUnoObjects( oSimpleFileAccess, 42 )

    MsgBox bIdentical    ' Displays False, 42 is not even an object

       ' Instantiate a Property struct

    Dim aProperty As New com.sun.star.beans.Property

    Dim aProperty2

    aProperty2 = aProperty    ' Copy the struct

    bIdentical = EqualUnoObjects( aProperty, aProperty2 )

    MsgBox bIdentical    ' Displays False because structs are values

                         ' and so aProperty2 is a copy of aProperty

End Sub 

Basic hides interfaces behind OpenOffice.org Basic objects that could lead to problems when developers are using API structures. It can be difficult to understand the API reference and find the correct method of accessing an object to reach a certain goal. 

To assist during development and debugging, every UNO object in OpenOffice.org Basic has special properties that provide information about the object structure. These properties are all prefixed with Dbg_ to emphasize their use for development and debugging purposes. The type of these properties is String. To display the properties use the MsgBox function.

Inspecting interfaces during debugging 

The Dbg_SupportedInterfaces lists all interfaces supported by the object. In the following example, the object returned by the function GetProcessServiceManager() described in the previous section is taken as an example object.

    oServiceManager = GetProcessServiceManager()

    MsgBox oServiceManager.Dbg_SupportedInterfaces

This call displays a message box: 

Screenshot shwoing the output of dbg_supportedInterfacesIllustration 3.18: Dbg_SupportedInterfaces Property

The list contains all interfaces supported by the object. For interfaces that are derived from other interfaces, the super interfaces are indented as shown above for com.sun.star.container.XSet, which is derived from com.sun.star.container.XEnumerationAccess based upon com.sun.star.container.XElementAccess.

Note graphics marks a special text section

If the text “(ERROR: Not really supported!)” is printed behind an interface name, the implementation of the object usually has a bug, because the object pretends to support this interface (per com.sun.star.lang.XTypeProvider, but a query for it fails. For details, see 6.2.3 Advanced UNO - Language Bindings - UNO Reflection API).

Inspecting properties during debugging 

The Dbg_Properties lists all properties supported by the object through com.sun.star.beans.XPropertySet and through get and set methods that could be mapped to Basic object properties:

    oServiceManager = GetProcessServiceManager()

    MsgBox oServiceManager.Dbg_Properties

This code produces a message box like the following example: 

Screenshot showing the output of dbg_propertiesIllustration 3.19: Dbg_Properties

Inspecting Methods During Debugging 

The Dbg_Methods lists all methods supported by an object. Example:

    oServiceManager = GetProcessServiceManager()

    MsgBox oServiceManager.Dbg_Methods

This code displays: 

Screenshot showing the output of dbg_methodsIllustration 3.20: Dbg_Methods

The notations used in Dbg_Properties and Dbg_Methods refer to internal implementation type names in Basic. The Sbx prefix can be ignored. The remaining names correspond with the normal Basic type notation. The SbxEMPTY is the same type as Variant. Additional information about Basic types is available in the next chapter.

Note graphics marks a special text section

Basic uses the com.sun.star.lang.XTypeProvider interface to detect which interfaces an object supports. Therefore, it is important to support this interface when implementing a component that should be accessible from Basic. For details, see 4 Writing UNO Components.

Mapping of UNO and Basic Types

Basic and UNO use different type systems. While OpenOffice.orgBasic is compatible to Visual Basic and its type system, UNO types correspond to the IDL specification (see 3.2.1 Professional UNO - API Concepts - Data Types), therefore it is necessary to map these two type systems. This chapter describes which Basic types have to be used for the different UNO types.

Mapping of Simple Types

In general, the OpenOffice.orgBasic type system is not rigid. Unlike C++ and Java, OpenOffice.orgBasic does not require the declaration of variables, unless the Option Explicit command is used that forces the declaration. To declare variables, the Dim command is used. Also, a OpenOffice.orgBasic type can be optionally specified through the Dim command. The general syntax is:

    Dim VarName [As Type][, VarName [As Type]]...

All variables declared without a specific type have the type Variant. Variables of type Variant can be assigned values of arbitrary Basic types. Undeclared variables are Variant unless type postfixes are used with their names. Postfixes can be used in Dim commands as well. The following table contains a complete list of types supported by Basic and their corresponding postfixes:

Type 

Postfix 

Range 

Boolean

 

True or False

Integer

-32768 to 32767

Long

-2147483648 to 2147483647

Single

Floating point number
negative: -3.402823E38 to -1.401298E-45
positive: 1.401298E-45 to 3.402823E38

Double

Double precision floating point number
negative: -1.79769313486232E308 to -4.94065645841247E-324
positive: 4.94065645841247E-324 to 1.79769313486232E308

Currency

Fixed point number with four decimal places
-922,337,203,685,477.5808 to 922,337,203,685,477.5807

Date

 

01/01/100 to 12/31/9999

Object

 

Basic Object 

String

Character string 

Variant

 

arbitrary Basic type 

Consider the following Dim examples.

    Dim a, b            ' Type of a and b is Variant

    Dim c as Variant    ' Type of c is Variant

 

    Dim d as Integer    ' Type of d is Integer (16 bit!)

 

    ' The type only refers to the preceding variable

    Dim e, f as Double  ' ATTENTION! Type of e is Variant!

                        '   Only the type of f is Double

 

    Dim g as String     ' Type of g is String

 

    Dim i as Date       ' Type of g is Date

 

    ' Usage of Postfixes

    Dim i%              ' is the same as

    Dim i as Integer

 

    Dim d#              ' is the same as

    Dim d as Double

 

    Dim s$              ' is the same as

    Dim s as String

The correlation below is used to map types from UNO to Basic and vice versa.  

UNO 

Basic 

void

internal type 

boolean

Boolean

byte

Integer

short

Integer

unsigned short

internal type 

long

Long

unsigned long

internal type 

hyper

internal type 

unsigned hyper

internal type 

float

Single

double

Double

char

internal type 

string

String

type

com.sun.star.reflection.XIdlClass

any

Variant

The simple UNO type type is mapped to the com.sun.star.reflection.XIdlClass interface to retrieve type specific information. For further details, refer to 6.2.3 Advanced UNO - Language Bindings - UNO Reflection API.

When UNO methods or properties are accessed, and the target UNO type is known, Basic automatically chooses the appropriate types: 

    ' The UNO object oExample1 has a property “Count” of type short

    a% = 42

    oExample1.Count = a%    ' a% has the right type (Integer)

 

    pi = 3,141593

    oExample1.Count = pi    ' pi will be converted to short, so Count will become 3

 

    s$ = “111”

    oExample1.Count = s$    ' s$ will be converted to short, so Count will become 111

Occasionally, OpenOffice.orgBasic does not know the required target type, especially if a parameter of an interface method or a property has the type any. In this situation, OpenOffice.orgBasic mechanically converts the OpenOffice.orgBasic type into the UNO type shown in the table above, although a different type may be expected. The only mechanism provided by OpenOffice.orgBasic is an automatic downcast of numeric values:

Long and Integer values are always converted to the shortest possible integer type:

The Single/Double values are converted to integers in the same manner if they have no decimal places.

This mechanism is used, because some internal C++ tools used to implement UNO functionality in OpenOffice.org provide an automatic upcast but no downcast. Therefore, it can be successful to pass a byte value to an interface expecting a long value, but not vice versa.

In the following example, oNameCont is an object that supports com.sun.star.container.XNameContainer and contains elements of type short. Assume FirstValue is a valid entry.

    a% = 42

    oNameCount.replaceByName( “FirstValue”, a% )    ' Ok, a% is downcasted to type byte

 

    b% = 123456

    oNameCount.replaceByName( “FirstValue”, b% )    ' Fails, b% is outside the short range

The method call fails, therefore the implementation should throw the appropriate exception that is converted to a OpenOffice.orgBasic error by the OpenOffice.orgBasic RTL. It may happen that an implementation also accepts unsuitable types and does not throw an exception. Ensure that the values used are suitable for their UNO target by using numeric values that do not exceed the target range or converting them to the correct Basic type before applying them to UNO.  

Always use the type Variant to declare variables for UNO Basic objects, not the type Object. The OpenOffice.orgBasic type Object is tailored for pure OpenOffice.orgBasic objects and not for UNO OpenOffice.orgBasic objects. The Variant variables are best for UNO Basic objects to avoid problems that can result from the OpenOffice.orgBasic specific behavior of the type Object:

    Dim oService1    ' Ok

    oService1 = CreateUnoService( "com.sun.star.anywhere.Something" )

 

    Dim oService2 as Object    ' NOT recommended

    oService2 = CreateUnoService( "com.sun.star.anywhere.SomethingElse" )

Mapping of Sequences and Arrays

Many UNO interfaces use sequences, as well as simple types. The OpenOffice.orgBasic counterpart for sequences are arrays. Arrays are standard elements of the Basic language. The example below shows how they are declared: 

    Dim a1( 100 )    ' Variant array, index range: 0-100 -> 101 elements

 

    Dim a2%( 5 )     ' Integer array, index range: 0-5 -> 6 elements

 

    Dim a3$( 0 )     ' String array, index range: 0-0 -> 1 element

 

    Dim a4&( 9, 19 ) ' Long array, index range: (0-9) x (0-19) -> 200 elements

Basic does not have a special index operator like [] in C++ and Java. Array elements are accessed using normal parentheses ():

    Dim i%, a%( 10 )

    for i% = 0 to 10            ' this loop initializes the array

       a%(i%) = i%

    next i%

 

    dim s$

    for i% = 0 to 10            ' this loop adds all array elements to a string

       s$ = s$ + " " + a%(i%)

    next i%

    msgbox s$                   ' Displays the string containing all array elements

 

    Dim b( 2, 3 )

    b( 2, 3 ) = 23

    b( 0, 0 ) = 0

    b( 2, 4 ) = 24              ' Error ”Subscript out of range”

As the examples show, the indices in Dim commands differ from C++ and Java array declarations. They do not describe the number of elements, but the largest allowed index. There is one more array element than the given index. This is important for the mapping of OpenOffice.orgBasic arrays to UNO sequences, because UNO sequences follow the C++/Java array semantic.

When the UNO API requires a sequence, the Basic programmer uses an appropriate array. In the following example, oSequenceContainer is an object that has a property TheSequence of type sequence<short>. To assign a sequence of length 10 with the values 0, 1, 2, ... 9 to this property, the following code can be used:

    Dim i%, a%( 9 )    ' Maximum index 9 -> 10 elements

    for i% = 0 to 9    ' this loop initializes the array

       a%(i%) = i%

    next i%

 

    oSequenceContainer.TheSequence = a%()

 

    ' If “TheSequence” is based on XPropertySet alternatively

    oSequenceContainer.setPropertyValue( “TheSequence”, a%() )

The Basic programmer must be aware of the different index semantics during programming. In the following example, the programmer passed a sequence with one element, but actually passed two elements: 

    ' Pass a sequence of length 1 to the TheSequence property:

    Dim a%( 1 )     ' WRONG: The array has 2 elements, not only 1!

    a%( 0 ) = 3     ' Only Element 0 is initialized,

                    ' Element 1 remains 0 as initialized by Dim

 

    ' Now a sequence with two values (3,0) is passed what

    ' may result in an error or an unexpected behavior!

    oSequenceContainer.setPropertyValue( “TheSequence”, a%() )

Note graphics marks a special text section

When using Basic arrays as a whole for parameters or for property access, they should always be followed by '()' in the Basic code, otherwise errors may occur in some situations.

It can be useful to use a OpenOffice.orgBasic RTL function called Array() to create, initialize and assign it to a Variant variable in a single step, especially for small sequences:

    Dim a        ' should be declared as Variant

    a = Array( 1, 2, 3 )

 

    ' is the same as

 

    Dim a(2)

    a( 0 ) = 1

    a( 1 ) = 2

    a( 2 ) = 3

Sometimes it is necessary to pass an empty sequence to a UNO interface. In Basic, empty sequences can be declared by omitting the index from the Dim command:

    Dim a%()    ' empty array/sequence of type Integer

 

    Dim b$()    ' empty array/sequence of String

Sequences returned by UNO are also represented in Basic as arrays, but these arrays do not have to be declared as arrays beforehand. Variables used to accept a sequence should be declared as Variant. To access an array returned by UNO, it is necessary to get information about the number of elements it contains with the Basic RTL functions LBound() and UBound().

The function LBound() returns the lower index and UBound() returns the upper index. The following code shows a loop going through all elements of a returned sequence:

    Dim aResultArray    ' should be declared as Variant

    aResultArray = oSequenceContainer.TheSequence

 

    dim i%, iFrom%, iTo%

    iFrom% = LBound( aResultArray() )

    iTo%   = UBound( aResultArray() )

    for i% = iFrom% to iTo%    ' this loop displays all array elements

       msgbox aResultArray(i%)

    next i%

The function LBound() is a standard Basic function and is not specific in a UNO context. Basic arrays do not necessarily start with index 0, because it is possible to write something similar to:

Dim a (3 to 5 ) 

This causes the array to have a lower index of 3. However, sequences returned by UNO always have the start index 0. Usually only UBound() is used and the example above can be simplified to:

    Dim aResultArray    ' should be declared as Variant

    aResultArray = oSequenceContainer.TheSequence

 

    Dim i%, iTo%

    iTo%   = UBound( aResultArray() )

    For i% = 0 To iTo%    ' this loop displays all array elements

       MsgBox aResultArray(i%)

    Next i%

The element count of a sequence/array can be calculated easily: 

    u% = UBound( aResultArray() )

    ElementCount% = u% + 1

For empty arrays/sequences UBound returns -1. This way the semantic of UBound stays consistent as the element count is then calculated correctly as:

    ElementCount% = u% + 1        ' = -1 + 1 = 0

Note graphics marks a special text section

The mapping between UNO sequences and Basic arrays depends on the fact that both use a zero-based index system. To avoid problems, the syntax
Dim a ( IndexMin to IndexMin )
or the Basic command Option Base 1 should not be used. Both cause all Basic arrays to start with an index other than 0.

UNO also supports sequences of sequences. In Basic, this corresponds with arrays of arrays. Do not mix up sequences of sequences with multidimensional arrays. In multidimensional arrays, all sub arrays always have the same number of elements, whereas in sequences of sequences every element sequence can have a different size. Example: 

    Dim aArrayOfArrays    ' should be declared as Variant

    aArrayOfArrays = oExample.ShortSequences    ' returns a sequence of sequences of short

 

    Dim i%, NumberOfSequences%

    Dim j%, NumberOfElements%

    Dim aElementArray

 

    NumberOfSequences% = UBound( aArrayOfArrays() ) + 1

    For i% = 0 to NumberOfSequences% - 1        ' loop over all sequences

       aElementArray = aArrayOfArrays( i% )

       NumberOfElements% = UBound( aElementArray() ) + 1

 

       For j% = 0 to NumberOfElements% - 1    ' loop over all elements

          MsgBox aElementArray( j% )

       Next j%

    Next i%

To create an array of arrays in Basic, sub arrays are used as elements of a master array: 

    ' Declare master array

    Dim aArrayOfArrays( 2 )

 

    ' Declare sub arrays

    Dim aArray0( 3 )

    Dim aArray1( 2 )

    Dim aArray2( 0 )

 

    ' Initialise sub arrays

    aArray0( 0 ) = 0

    aArray0( 1 ) = 1

    aArray0( 2 ) = 2

    aArray0( 3 ) = 3

 

    aArray1( 0 ) = 42

    aArray1( 1 ) = 0

    aArray1( 2 ) = -42

 

    aArray2( 0 ) = 1

 

    ' Assign sub arrays to the master array

    aArrayOfArrays( 0 ) = aArray0()

    aArrayOfArrays( 1 ) = aArray1()

    aArrayOfArrays( 2 ) = aArray2()

 

    ' Assign the master array to the array property

    oExample.ShortSequences = aArrayOfArrays()

In this situation, the runtime function Array() is useful. The example code can then be written much shorter:

    ' Declare master array

    Dim aArrayOfArrays( 2 )

 

    ' Create and assign sub arrays

    aArrayOfArrays( 0 ) = Array( 0, 1, 2, 3 )

    aArrayOfArrays( 1 ) = Array( 42, 0, -42 )

    aArrayOfArrays( 2 ) = Array( 1 )

 

    ' Assign the master array to the array property

    oExample.ShortSequences = aArrayOfArrays()

If you nest Array(), more compact code can be written, but it becomes difficult to understand the resulting arrays:

    ' Declare master array variable as variant

    Dim aArrayOfArrays

 

    ' Create and assign master array and sub arrays

    aArrayOfArrays = Array( Array( 0, 1, 2, 3 ), Array( 42, 0, -42 ), Array( 1 ) )

 

    ' Assign the master array to the array property

    oExample.ShortSequences = aArrayOfArrays()

 

Sequences of higher order can be handled accordingly. 

Mapping of Structs

UNO struct types can be instantiated with the Dim As New command as a single instance and array.

    ' Instantiate a Property struct

    Dim aProperty As New com.sun.star.beans.Property

 

    ' Instantiate an array of Locale structs

    Dim Locales(10) As New com.sun.star.lang.Locale

For instantiated polymorphic struct types, there is a special syntax of the Dim As New command, giving the type as a string literal instead of as a name:

    Dim o As New "com.sun.star.beans.Optional<long>"

The string literal representing a UNO name is built according to the following rules: 

No spurious spaces or other characters may be introduced into these string representations. 

UNO struct instances are handled like UNO objects. Struct members are accessed using the . operator. The Dbg_Properties property is supported. The properties Dbg_SupportedInterfaces and Dbg_Methods are not supported because they do not apply to structs.:

    ' Instantiate a Locale struct

    Dim aLocale As New com.sun.star.lang.Locale

 

    ' Display properties

    MsgBox aLocale.Dbg_Properties

 

    ' Access “Language” property

    aLocale.Language = "en"

Objects and structs are different. Objects are handled as references and structs as values. When structs are assigned to variables, the structs are copied. This is important when modifying an object property that is a struct, because a struct property has to be reassigned to the object after reading and modifying it. 

In the following example, oExample is an object that has the properties MyObject and MyStruct.

Both oExample.MyObject.ObjectName and oExample.MyStruct.StructName should be modified. The following code shows how this is done for an object:

    ' Accessing the object

    Dim oObject

    oObject = oExample.MyObject

    oObject.ObjectName = “Tim”    ' Ok!

 

        ' or shorter

 

    oExample.MyObject.ObjectName = “Tim”    ' Ok!

The following code shows how it is done correctly for the struct (and possible mistakes): 

    ' Accessing the struct

    Dim aStruct

    aStruct = oExample.MyStruct    ' aStruct is a copy of oExample.MyStruct!

    aStruct.StructName = “Tim”     ' Affects only the property of the copy!

 

        ' If the code ended here, oExample.MyStruct wouldn't be modified!

 

    oExample.MyStruct = aStruct    ' Copy back the complete struct! Now it's ok!

 

 

    ' Here the other variant does NOT work at all, because

    ' only a temporary copy of the struct is modified!

    oExample.MyStruct.StructName = “Tim”    ' WRONG! oExample.MyStruct is not modified!

Mapping of Enums and Constant Groups

Use the fully qualified names to address the values of an enum type by their names. The following examples assume that oExample and oExample2 support com.sun.star.beans.XPropertySet with a property Status of the enum type com.sun.star.beans.PropertyState:

    Dim EnumValue

    EnumValue = com.sun.star.beans.PropertyState.DEFAULT_VALUE

    MsgBox EnumValue    ' displays 1

 

    eExample.Status = com.sun.star.beans.PropertyState.DEFAULT_VALUE

Basic does not support Enum types. In Basic, enum values coming from UNO are converted to Long values. As long as Basic knows if a property or an interface method parameter expects an enum type, then the Long value is internally converted to the right enum type. Problems appear with Basic when interface access methods expect an Any:

    Dim EnumValue

    EnumValue = oExample.Status    ' EnumValue is of type Long

 

    ' Accessing the property implicitly

    oExample2.Status = EnumValue         ' Ok! EnumValue is converted to the right enum type

 

    ' Accessing the property explicitly using XPropertySet methods

    oExample2.setPropertyValue( “Status”, EnumValue )    ' WRONG! Will probably fail!

The explicit access could fail, because EnumValue is passed as parameter of type Any to setPropertyValue(), therefore Basic does not know that a value of type PropertyState is expected. There is still a problem, because the Basic type for com.sun.star.beans.PropertyState is Long. This problem is solved in the implementation of the com.sun.star.beans.XPropertySet interface. For enum types, the implicit property access using the Basic property syntax Object.Property is preferred to calling generic methods using the type Any. In situations where only a generic interface method that expects an enum for an Any, there is no solution for Basic.

Constant groups are used to specify a set of constant values in IDL. In Basic, these constants can be accessed using their fully qualified names. The following code displays some constants from com.sun.star.beans.PropertyConcept:

    MsgBox com.sun.star.beans.PropertyConcept.DANGEROUS    ' Displays 1

    MsgBox com.sun.star.beans.PropertyConcept.PROPERTYSET  ' Displays 2

A constant group or enum can be assigned to an object. This method is used to shorten code if more than one enum or constant value has to be accessed:  

    Dim oPropConcept

    oPropConcept = com.sun.star.beans.PropertyConcept

    msgbox oPropConcept.DANGEROUS    ' Displays 1

    msgbox oPropConcept.PROPERTYSET  ' Displays 2

Case Sensitivity

Generally Basic is case insensitive. However, this does not always apply to the communication between UNO and Basic. To avoid problems with case sensitivity write the UNO related code as if Basic was case sensitive. This facilitates the translation of a Basic program to another language, and Basic code becomes easier to read and understand. The following discusses problems that might occur. 

Identifiers that differ in case are considered to be identical when they are used with UNO object properties, methods and struct members. 

    Dim ALocale As New com.sun.star.lang.Locale

    alocale.language = "en"    ' Ok

    MsgBox aLocale.Language    ' Ok

The exceptions to this is if a Basic property is obtained through com.sun.star.container.XNameAccess as described above, its name has to be written exactly as it is in the API reference. Basic uses the name as a string parameter that is not interpreted when accessing com.sun.star.container.XNameAccess using its methods.

        ' oNameAccessible is an object that supports XNameAccess

    ' including the names “Value1”, “Value2”

    x = oNameAccessible.Value1    ' Ok

    y = oNameAccessible.VaLUe2    ' Runtime Error, Value2 is not written correctly

 

                ' is the same as

 

    x = oNameAccessible.getByName( “Value1” )    ' Ok

    y = oNameAccessible.getByName( “VaLUe2” )    ' Runtime Error, Value2 is not written correctly

Exception Handling

Unlike UNO, Basic does not support exceptions. All exceptions thrown by UNO are caught by the Basic runtime system and transformed to a Basic error. Executing the following code results in a Basic error that interrupts the code execution and displays an error message:

    Sub Main

        Dim oLib

        oLib = BasicLibraries.getByName( "InvalidLibraryName" )

    End Sub

The BasicLibraries object used in the example contains all the available Basic libraries in a running office instance. The Basic libraries contained in BasicLibraries is accessed using com.sun.star.container.XNameAccess. An exception was provoked by trying to obtain a non-existing library. The BasicLibraries object is explained in more detail in 12.4 OpenOffice.org Basic and Dialogs - Advanced Library Organization.

The call to getByName() results in this error box:

Screenshot showing an error box of an unhandled exception in BasicIllustration 3.21: Unhandled UNO Exception

However, the Basic runtime system is not always able to recognize the Exception type. Sometimes only the exception message can be displayed that has to be provided by the object implementation.  

Exceptions transformed to Basic errors can be handled just like any Basic error using the On Error GoTo command:

    Sub Main

        On Error Goto ErrorHandler    ' Enables error handling

 

        Dim oLib

        oLib = BasicLibraries.getByName( "InvalidLibraryName" )

        MsgBox "After the Error"

        Exit Sub

 

    ' Label

    ErrorHandler:

        MsgBox "Error code: " + Err + Chr$(13) + Error$

        Resume Next    ' Continues execution at the command following the error command

    End Sub

When the exception occurs, the execution continues at the ErrorHandler label. In the error handler, some properties are used to get information about the error. The Err is the error code that is 1 for UNO exceptions. The Error$ contains the text of the error message. Executing the program results in the following output:

Screenshot showing an error box of an handled exception in BasicIllustration 3.22: Handled UNO Exception

Another message box “After the Error” is displayed after the above dialog box, because Resume Next goes to the code line below the line where the exception was thrown. The Exit Sub command is required so that the error handler code would be executed again.

Listeners

Many interfaces in UNO are used to register listener objects implementing special listener interfaces, so that a listener gets feedback when its appropriate listener methods are called. OpenOffice.org Basic does not support the concept of object implementation, therefore a special RTL function named CreateUnoListener() has been introduced. It uses a prefix for method names that can be called back from UNO. The CreateUnoListener() expects a method name prefix and the type name of the desired listener interface. It returns an object that supports this interface that can be used to register the listener.

The following example instantiates an com.sun.star.container.XContainerListener. Note the prefix ContListener_:

    Dim oListener

    oListener = CreateUnoListener( "ContListener_", "com.sun.star.container.XContainerListener" )

The next step is to implement the listener methods. In this example, the listener interface has the following methods: 

Methods of com.sun.star.container.XContainerListener

disposing()

Method of the listener base interface com.sun.star.lang.XEventListener, contained in every listener interface, because all listener interfaces must be derived from this base interface. Takes a com.sun.star.lang.EventObject

elementInserted()

Method of interface com.sun.star.container.XContainerListener. Takes a com.sun.star.container.ContainerEvent.

elementRemoved()

Method of interface com.sun.star.container.XContainerListener. Takes a com.sun.star.container.ContainerEvent.

elementReplaced()

Method of interface com.sun.star.container.XContainerListener. Takes a com.sun.star.container.ContainerEvent.

In the example, ContListener_ is specified as a name prefix, therefore the following subs have to be implemented in Basic.

Every listener type has a corresponding Event struct type that contains information about the event. When a listener method is called, an instance of this Event type is passed as a parameter. In the Basic listener methods these Event objects can be evaluated by adding an appropriate Variant parameter to the procedure header. The following code shows how the listener methods in the example could be implemented:

    Sub ContListener_disposing( oEvent )

        MsgBox "disposing"

        MsgBox oEvent.Dbg_Properties

    End Sub

 

    Sub ContListener_elementInserted( oEvent )

        MsgBox "elementInserted"

        MsgBox oEvent.Dbg_Properties

    End Sub

 

    Sub ContListener_elementRemoved( oEvent )

        MsgBox "elementRemoved"

        MsgBox oEvent.Dbg_Properties

    End Sub

 

    Sub ContListener_elementReplaced( oEvent )

        MsgBox "elementReplaced"

        MsgBox oEvent.Dbg_Properties

    End Sub

It is necessary to implement all listener methods, including the listener methods of the parent interfaces of a listener. Basic runtime errors will occur whenever an event occurs and no corresponding Basic sub is found, especially with disposing(), because the broadcaster might be destroyed a long time after the Basic program was ran. In this situation, Basic shows a "Method not found" message. There is no indication of which method cannot be found or why Basic is looking for a method.

We are listening for events at the basic library container. Our simple implementation for events triggered by user actions in the Tools - Macro - Organizer dialog displays a message box with the corresponding listener method name and a message box with the Dbg_Properties of the event struct. For the disposing() method, the type of the event object is com.sun.star.lang.EventObject. All other methods belong to com.sun.star.container.XContainerListener, therefore the type of the event object is com.sun.star.container.ContainerEvent. This type is derived from com.sun.star.lang.EventObject and contains additional container related information.

If the event object is not needed, the parameter could be left out of the implementation. For example, the disposing() method could be:

    ' Minimal implementation of Sub disposing

    Sub ContListener_disposing

    End Sub

The event objects passed to the listener methods can be accessed like other struct objects. The following code shows an enhanced implementation of the elementRemoved() method that evaluates the com.sun.star.container.ContainerEvent to display the name of the module removed from Library1 and the module source code:

    sub ContListener_ElementRemoved( oEvent )

        MsgBox "Element " + oEvent.Accessor + " removed"

        MsgBox "Source =" + Chr$(13) + Chr$(13) + oEvent.Element

    End Sub

When the user removes Module1, the following message boxes are displayed by ContListener_ElementRemoved():

Screenshot of a ContListener_ElementRemoved event callbackScreenshot of a ContListener_ElementRemoved event callbackIllustration 3.23: ContListener_ElementRemoved Event Callback

When all necessary listener methods are implemented, add the listener to the broadcaster object by calling the appropriate add method. To register an XContainerListener, the corresponding registration method at our container is addContainerListener():

    Dim oLib

    oLib = BasicLibraries.Library1            ' Library1 must exist!

    oLib.addContainerListener( oListener )    ' Register the listener

Tip graphics marks a hint section in the text

The naming scheme XSomeEventListener <> addSomeEventListener() is used throughout the OpenOffice.org API.

The listener for container events is now registered permanently. When a container event occurs, the container calls the appropriate method of the com.sun.star.container.XContainerListener interface in our Basic code.

3.4.3.5  Automation Bridge

Introduction

The OpenOffice.org software supports Microsoft's Automation technology. This offers programmers the possibility to control the office from external programs. There is a range of efficient IDEs and tools available for developers to choose from.

Automation is language independent. The respective compilers or interpreters must, however, support Automation. The compilers transform the source code into Automation compatible computing instructions. For example, the string and array types of your language can be used without caring about their internal representation in Automation, which is BSTR and SAFEARRAY. A client program that controls OpenOffice.org can be represented by an executable (Visual Basic, C++) or a script (JScript, VB Script). The latter requires an additional program to run the scripts, such as Windows Scripting Host (WSH) or Internet Explorer.

UNO was not designed to be compatible with Automation and COM, although there are similarities. OpenOffice.org deploys a bridging mechanism provided by the Automation Bridge to make UNO and Automation work together. The bridge consists of UNO services, however, it is not necessary to have a special knowledge about them to write Automation clients for OpenOffice.org. For additional information, refer to (see 3.4.4 Professional UNO - UNO Language Bindings - Automation Bridge - The Bridge Services).

Different languages have different capabilities. There are differences in the manner that the same task is handled, depending on the language used. Examples in Visual Basic, VB Script and JScript are provided. They will show when a language requires special handling or has a quality to be aware of. Although Automation is supposed to work across languages, there are subtleties that require a particular treatment by the bridge or a style of coding. For example, JScript does not know out parameters, therefore Array objects have to be used. Currently, the bridge has been tested with C++, JScript, VBScript and Visual Basic, although other languages can be used as well.

The name Automation Bridge implies the use of the Automation technology. Automation is part of the collection of technologies commonly referred to as ActiveX or OLE, therefore the term OLE Bridge is misleading and should be avoided. Sometimes the bridge is called COM bridge, which is also wrong, since the only interfaces which are processed by the bridge are IUnknown and IDispatch.

Requirements

The Automation technology can only be used with OpenOffice.org on a Windows platform (Windows 95, 98, NT4, ME, 2000, XP). There are COM implementations on Macintosh OS and UNIX, but there has been no effort to support Automation on these platforms. 

Using Automation involves creating objects in a COM-like fashion, that is, using functions like CreateObject() in VB or CoCreateInstance() in C. This requires the OpenOffice.org automation objects to be registered with the Windows system registry. This registration is carried out whenever an office is installed on the system. If the registration did not take place, for example because the binaries were just copied to a certain location, then Automation clients will not work correctly or not at all. Refer to 3.4.4 Professional UNO - UNO Language Bindings - Automation Bridge - The Service Manager Component for additional information.

A Quick Tour

The following example shows how to access OpenOffice.org functionality through Automation. Note the inline comments. The only automation specific call is WScript.CreateObject() in the first line, the remaining are OpenOffice.org API calls. The helper functions createStruct() and insertIntoCell() are shown at the end of the listing

'This is a VBScript example 

'The service manager is always the starting point 

'If there is no office running then an office is started up 

Set objServiceManager= WScript.CreateObject("com.sun.star.ServiceManager")

 

'Create the CoreReflection service that is later used to create structs 

Set objCoreReflection= objServiceManager.createInstance("com.sun.star.reflection.CoreReflection") 

 

'Create the Desktop 

Set objDesktop= objServiceManager.createInstance("com.sun.star.frame.Desktop") 

 

'Open a new empty writer document 

Dim args() 

Set objDocument= objDesktop.loadComponentFromURL("private:factory/swriter", "_blank", 0, args) 

 

'Create a text object 

Set objText= objDocument.getText 

 

'Create a cursor object 

Set objCursor= objText.createTextCursor 

 

'Inserting some Text 

objText.insertString objCursor, "The first line in the newly created text document." & vbLf, false 

 

'Inserting a second line 

objText.insertString objCursor, "Now we're in the second line", false 

 

'Create instance of a text table with 4 columns and 4 rows 

Set objTable= objDocument.createInstance( "com.sun.star.text.TextTable") 

objTable.initialize 4, 4 

 

'Insert the table 

objText.insertTextContent objCursor, objTable, false 

 

'Get first row 

Set objRows= objTable.getRows 

Set objRow= objRows.getByIndex( 0) 

 

'Set the table background color 

objTable.setPropertyValue "BackTransparent", false 

objTable.setPropertyValue "BackColor", 13421823 

 

'Set a different background color for the first row 

objRow.setPropertyValue "BackTransparent", false 

objRow.setPropertyValue "BackColor", 6710932 

 

'Fill the first table row 

insertIntoCell "A1","FirstColumn", objTable // insertIntoCell is a helper function, see below 

insertIntoCell "B1","SecondColumn", objTable 

insertIntoCell "C1","ThirdColumn", objTable 

insertIntoCell "D1","SUM", objTable 

 

objTable.getCellByName("A2").setValue 22.5 

objTable.getCellByName("B2").setValue 5615.3 

objTable.getCellByName("C2").setValue -2315.7 

objTable.getCellByName("D2").setFormula"sum " 

 

objTable.getCellByName("A3").setValue 21.5 

objTable.getCellByName("B3").setValue 615.3 

objTable.getCellByName("C3").setValue -315.7 

objTable.getCellByName("D3").setFormula "sum " 

 

objTable.getCellByName("A4").setValue 121.5 

objTable.getCellByName("B4").setValue -615.3 

objTable.getCellByName("C4").setValue 415.7 

objTable.getCellByName("D4").setFormula "sum " 

 

'Change the CharColor and add a Shadow 

objCursor.setPropertyValue "CharColor", 255 

objCursor.setPropertyValue "CharShadowed", true 

 

'Create a paragraph break 

'The second argument is a com::sun::star::text::ControlCharacter::PARAGRAPH_BREAK constant 

objText.insertControlCharacter objCursor, 0 , false 

 

'Inserting colored Text. 

objText.insertString objCursor, " This is a colored Text - blue with shadow" & vbLf, false 

 

'Create a paragraph break ( ControlCharacter::PARAGRAPH_BREAK). 

objText.insertControlCharacter objCursor, 0, false  

 

'Create a TextFrame. 

Set objTextFrame= objDocument.createInstance("com.sun.star.text.TextFrame") 

 

'Create a Size struct. 

Set objSize= createStruct("com.sun.star.awt.Size") // helper function, see below 

objSize.Width= 15000 

objSize.Height= 400 

objTextFrame.setSize( objSize) 

 

' TextContentAnchorType.AS_CHARACTER = 1 

objTextFrame.setPropertyValue "AnchorType", 1 

 

'insert the frame 

objText.insertTextContent objCursor, objTextFrame, false 

 

'Get the text object of the frame 

Set objFrameText= objTextFrame.getText 

 

'Create a cursor object 

Set objFrameTextCursor= objFrameText.createTextCursor 

 

'Inserting some Text 

objFrameText.insertString objFrameTextCursor, "The first line in the newly created text frame.", _ 

false 

objFrameText.insertString objFrameTextCursor, _ 

vbLf & "With this second line the height of the frame raises.", false  

 

'Create a paragraph break 

'The second argument is a com::sun::star::text::ControlCharacter::PARAGRAPH_BREAK constant 

objFrameText.insertControlCharacter objCursor, 0 , false 

 

'Change the CharColor and add a Shadow 

objCursor.setPropertyValue "CharColor", 65536 

objCursor.setPropertyValue "CharShadowed", false 

 

'Insert another string 

objText.insertString objCursor, " That's all for now !!", false 

 

On Error Resume Next 

    If Err Then

    MsgBox "An error occurred"

End If 

 

 

Sub insertIntoCell( strCellName, strText, objTable)

    Set objCellText= objTable.getCellByName( strCellName)

    Set objCellCursor= objCellText.createTextCursor

    objCellCursor.setPropertyValue "CharColor",16777215

    objCellText.insertString objCellCursor, strText, false

End Sub 

 

Function createStruct( strTypeName)

    Set classSize= objCoreReflection.forName( strTypeName)

    Dim aStruct

    classSize.createObject aStruct

    Set createStruct= aStruct

End Function 

This script created a new document and started the office, if necessary. The script also wrote text, created and populated a table, used different background and pen colors. Only one object is created as an ActiveX component called com.sun.star.ServiceManager. The service manager is then used to create additional objects which in turn provided other objects. All those objects provide functionality that can be used by invoking the appropriate functions and properties. A developer must learn which objects provide the desired functionality and how to obtain them. The chapter 2 First Steps introduces the main OpenOffice.org objects available to the programmer.

The Service Manager Component

Instantiation

The service manager is the starting point for all Automation clients. The service manager requires to be created before obtaining any UNO object. Since the service manager is a COM component, it has a CLSID and a programmatic identifier which is com.sun.star.ServiceManager. It is instantiated like any ActiveX component, depending on the language used:

//C++ 

IDispatch* pdispFactory= NULL;  

CLSID clsFactory= {0x82154420,0x0FBF,0x11d4,{0x83, 0x13,0x00,0x50,0x04,0x52,0x6A,0xB4}};  

hr= CoCreateInstance( clsFactory, NULL, CLSCTX_ALL, __uuidof(IDispatch), (void**)&pdispFactory); 

In Visual C++, use classes which facilitate the usage of COM pointers. If you use the Active Template Library (ATL), then the following example looks like this: 

CComPtr<IDispatch> spDisp; 

if( SUCCEEDED( spDisp.CoCreateInstance("com.sun.star.ServiceManager"))) 

    // do something

JScript: 

var objServiceManager= new ActiveXObject("com.sun.star.ServiceManager"); 

Visual Basic: 

Dim objManager As Object 

Set objManager= CreateObject("com.sun.star.ServiceManager") 

VBScript with WSH: 

Set objServiceManager= WScript.CreateObject("com.sun.star.ServiceManager")  

JScript with WSH: 

var objServiceManager= WScript.CreateObject("com.sun.star.ServiceManager"); 


The service manager can also be created remotely, that is. on a different machine, taking the security aspects into account. For example, set up launch and access rights for the service manager in the system registry (see “DCOM”).

The code for the service manager resides in the office executable soffice.exe. COM starts up the executible whenever a client tries to obtain the class factory for the service manager, so that the client can use it.

Registry Entries

For the instantiation to succeed, the service manager must be properly registered with the system registry. The keys and values shown in the tables below are all written during setup. It is not necessary to edit them to use the Automation capability of the office. Automation works immediately after installation. There are three different keys under HKEY_CLASSES_ROOT that have the following values and subkeys:

Key 

Value 

CLSID\{82154420-0FBF-11d4-8313-005004526AB4}  

"StarOffice Service Manager (Ver 1.0)"

Sub Keys 

LocalServer32 

"<OfficePath>\program\soffice.exe”

NotInsertable 

 

ProgIDcom.sun.star.ServiceManager.1 

"com.sun.star.ServiceManager.1"

Programmable 

 

VersionIndependentProgID 

"com.sun.star.ServiceManager" 

 

Key 

Value 

com.sun.star.ServiceManager 

"StarOffice Service Manager"

Sub Keys 

CLSID 

"{82154420-0FBF-11d4-8313-005004526AB4}"

CurVer 

"com.sun.star.ServiceManager.1"

 

Key 

Value 

com.sun.star.ServiceManager.1 

"StarOffice Service Manager (Ver 1.0)"

Sub Keys 

CLSID 

"{82154420-0FBF-11d4-8313-005004526AB4}"

The value of the key CLSID\{82154420-0FBF-11d4-8313-005004526AB4}\LocalServer32 reflects the path of the office executable.

All keys have duplicates under HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.

The service manager is an ActiveX component, but does not support self-registration. That is, the office does not support the command line arguments -RegServer or -UnregServer.
The service manager, as well as all the objects that it creates and that originate from it indirectly as return values of function calls are proper automation objects. They can also be accessed remotely through DCOM.

From UNO Objects to Automation Objects

The service manager is based on the UNO service manager and similar to all other UNO components, is not compatible with Automation. The service manager can be accessed through the COM API, because the service manager is an Active X component contained in an executable that is the OpenOffice.org. When a client creates the service manager, for example by calling CreateObject(), and the office is not running, it is started up by the COM system. The office then creates a class factory for the service manager and registers it with COM. At that point, COM uses the factory to instantiate the service manager and return it to the client.

When the function IClassFactory::CreateInstance is called, the UNO service manager is converted into an Automation object. The actual conversion is carried out by the UNO service com.sun.star.bridge.oleautomation.BridgeSupplier (see 3.4.4 Professional UNO - UNO Language Bindings - Automation Bridge - The Bridge Services). The resulting Automation object contains the UNO object and translates calls to IDispatch::Invoke into calls to the respective UNO interface function. The supplied function arguments, as well as the return values of the UNO function are converted according to the defined mappings (see 3.4.4 Professional UNO - UNO Language Bindings - Automation Bridge - Type Mappings). Returned objects are converted into Automation objects, so that all objects obtained are always proper Automation objects.

Using UNO from Automation

With the IDL descriptions and documentation, start writing code that uses an interface. This requires knowledge about the programming language, especially how UNO interfaces can be accessed in that language and how function calls work.  

In some languages, such as C++, the use of interfaces and their functions is simple, because the IDL descriptions map well with the respective C++ counterparts. For example, the syntax of functions are similar, and interfaces and out parameters can also be realized. The C++ language is not the best choice for Automation, because all interface calls have to use IDispatch, which is difficult to use in C++. In other languages, such as VB and JScript, the IDispatch interface is hidden behind an object syntax that leads to shorter and more understandable code.

Different interfaces can have functions with the same name. There is no way to call a function which belongs to a particular interface, because interfaces can not be requested in Automation . If a UNO object provides two functions with the same name, it is undefined which function will be called. A solution for this issue is planned for the future. 

Not all languages treat method parameters in the same manner, especially when it comes to input parameters that are reused as output parameters. From the perspective of a VB programmer an out parameter does not look different from an in parameter. However, to realize out parameters in Jscript, use an Array or Value Object that is a special construct provided by the Automation bridge. JScript does not support out parameters through calls by reference.

Cal