1 /*************************************************************************
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 * Copyright 2008 by Sun Microsystems, Inc.
7 * OpenOffice.org - a multi-platform office productivity suite
9 * $RCSfile: UnoRuntime.java,v $
12 * This file is part of OpenOffice.org.
14 * OpenOffice.org is free software: you can redistribute it and/or modify
15 * it under the terms of the GNU Lesser General Public License version 3
16 * only, as published by the Free Software Foundation.
18 * OpenOffice.org is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU Lesser General Public License version 3 for more details
22 * (a copy is included in the LICENSE file that accompanied this code).
24 * You should have received a copy of the GNU Lesser General Public License
25 * version 3 along with OpenOffice.org. If not, see
26 * <http://www.openoffice.org/license.html>
27 * for a copy of the LGPLv3 License.
29 ************************************************************************/
31 package com
.sun
.star
.uno
;
33 import java
.io
.IOException
;
34 import java
.lang
.reflect
.Array
;
35 import java
.lang
.reflect
.Constructor
;
36 import java
.util
.ArrayList
;
37 import java
.util
.Iterator
;
38 import com
.sun
.star
.lib
.uno
.typedesc
.TypeDescription
;
39 import com
.sun
.star
.lib
.util
.WeakMap
;
42 * The central class needed for implementing or using UNO components in Java.
44 * <p>The methods <code>queryInterface</code> and <code>areSame</code> delegate
45 * calls to the implementing objects and are used instead of casts,
46 * <code>instanceof</code>, <code>==</code>, and <code>equals</code>.<p>
48 * <p>For historic reasons, this class is not <code>final</code>, and has a
49 * <code>public</code> constructor. These artifacts are considered mistakes,
50 * which might be corrected in a future version of this class, so client code
51 * should not rely on them.</p>
53 * @see com.sun.star.uno.IBridge
54 * @see com.sun.star.uno.IEnvironment
55 * @see com.sun.star.uno.IQueryInterface
57 public class UnoRuntime
{
59 * @deprecated As of UDK 3.2.0, do not create instances of this class.
60 * It is considered a historic mistake to have a <code>public</code>
61 * constructor for this class, which only has <code>static</code> members.
62 * Also, this class might be changed to become <code>final</code> in a
65 public UnoRuntime() {}
68 * Generates a world wide unique identifier string.
70 * <p>It is guaranteed that every invocation of this method generates a new
71 * ID, which is unique within the VM. The quality of “world wide
72 * unique” will depend on the actual implementation, you should look
73 * at the source to determine if it meets your requirements.</p>
75 * @return a unique <code>String</code>
77 public static String
getUniqueKey() {
78 synchronized (uniqueKeyLock
) {
79 if (uniqueKeyCount
== Long
.MAX_VALUE
) {
81 for (time
= System
.currentTimeMillis(); time
== uniqueKeyTime
;)
83 // Conservatively sleep for 100 millisecond to wait for
84 // System.currentTimeMillis() to change:
87 } catch (InterruptedException e
) {
88 Thread
.currentThread().interrupt();
92 uniqueKeyCount
= Long
.MIN_VALUE
;
94 return uniqueKeyHostPrefix
+ Long
.toString(uniqueKeyTime
, 16) + ":"
95 + Long
.toString(uniqueKeyCount
++, 16);
100 * Generates a world wide unique object identifier (OID) for the given
103 * <p>It is guaranteed that subsequent calls to this method with the same
104 * Java object will give the same ID.</p>
106 * <p>This method is generally of little use for client code. It should be
107 * considered a mistake that this method is published at all.</p>
109 * @param object any object for which a OID shall be generated; must not be
111 * @return the generated OID
112 * @see com.sun.star.uno.IQueryInterface#getOid
114 public static String
generateOid(Object object
) {
116 if (object
instanceof IQueryInterface
) {
117 oid
= ((IQueryInterface
) object
).getOid();
119 return oid
== null ? object
.hashCode() + oidSuffix
: oid
;
123 * Queries the given UNO object for the given UNO interface type.
125 * <p>This method returns <code>null</code> in case the given UNO object
126 * does not support the given UNO interface type (or is itself
127 * <code>null</code>). Otherwise, a reference to a Java object implementing
128 * the Java interface type corresponding to the given UNO interface is
129 * returned. In the latter case, it is unspecified whether the returned
130 * Java object is the same as the given object, or is another facet of that
133 * @param type the requested UNO interface type; must be a <code>Type</code>
134 * object representing a UNO interface type
135 * @param object a reference to any Java object representing (a facet of) a
136 * UNO object; may be <code>null</code>
137 * @return a reference to the requested UNO interface type if available,
138 * otherwise <code>null</code>
139 * @see com.sun.star.uno.IQueryInterface#queryInterface
141 public static Object
queryInterface(Type type
, Object object
) {
142 // Gracefully handle those situations where the passed in UNO object is
143 // wrapped in an Any. Strictly speaking, such a situation constitutes a
144 // bug, but it is anticipated that such situations will arise quite
145 // often in practice (especially since UNO Anys containing an XInterface
146 // reference are not wrapped in a Java Any, but UNO Anys containing any
147 // other interface reference are wrapped in a Java Any, which can lead
149 if (object
instanceof Any
) {
150 Any a
= (Any
) object
;
151 if (a
.getType().getTypeClass() == TypeClass
.INTERFACE
) {
152 object
= a
.getObject();
155 if (object
instanceof IQueryInterface
) {
156 object
= ((IQueryInterface
) object
).queryInterface(type
);
157 if (object
instanceof Any
) {
158 Any a
= (Any
) object
;
159 object
= a
.getType().getTypeClass() == TypeClass
.INTERFACE
160 ? a
.getObject() : null;
163 // Ensure that the object implements the requested interface type:
164 Class c
= type
.getZClass();
165 if (c
== null || !c
.isInstance(object
)) {
172 * Queries the given UNO object for the given Java class (which must
173 * represent a UNO interface type).
175 * @param ifc a Java class representing a UNO interface type
176 * @param object a reference to any Java object representing (a facet of) a
177 * UNO object; may be <code>null</code>
178 * @return a reference to the requested UNO interface type if available,
179 * otherwise <code>null</code>
180 * @see #queryInterface(Type, Object)
182 @SuppressWarnings("unchecked")
183 public static <T
> T
queryInterface(Class
<T
> zInterface
, Object object
) {
184 return (T
) queryInterface(new Type(zInterface
), object
);
188 Tests two UNO <code>ANY</code> values for equality.
190 <p>Two UNO values are <dfn>equal</dfn> if and only if they are of the
191 same UNO type <var>t</var>, and they meet the following condition,
192 depending on <var>t</var>:</p>
194 <li>If <var>t</var> is a primitive type, then both values must denote
195 the same element of the set of values of <var>t</var>.</li>
197 <li>If <var>t</var> is a structured type, then both values must
198 recursively contain corresponding values that are equal.</li>
200 <li>If <var>t</var> is an interface type, then the two values must be
201 either both null references, or both references to the same UNO
205 @param any1 a Java value representing a UNO <code>ANY</code> value.
207 @param any2 a Java value representing a UNO <code>ANY</code> value.
209 @return <code>true</code> if and only if the two arguments represent
212 public static boolean areSame(Object any1
, Object any2
) {
213 Any a1
= Any
.complete(any1
);
214 Any a2
= Any
.complete(any2
);
215 Type t
= a1
.getType();
216 if (!a2
.getType().equals(t
)) {
219 Object v1
= a1
.getObject();
220 Object v2
= a2
.getObject();
221 switch (t
.getTypeClass().getValue()) {
222 case TypeClass
.VOID_value
:
224 case TypeClass
.BOOLEAN_value
:
225 case TypeClass
.BYTE_value
:
226 case TypeClass
.SHORT_value
:
227 case TypeClass
.UNSIGNED_SHORT_value
:
228 case TypeClass
.LONG_value
:
229 case TypeClass
.UNSIGNED_LONG_value
:
230 case TypeClass
.HYPER_value
:
231 case TypeClass
.UNSIGNED_HYPER_value
:
232 case TypeClass
.FLOAT_value
:
233 case TypeClass
.DOUBLE_value
:
234 case TypeClass
.CHAR_value
:
235 case TypeClass
.STRING_value
:
236 case TypeClass
.TYPE_value
:
237 return v1
.equals(v2
);
238 case TypeClass
.SEQUENCE_value
:
239 int n
= Array
.getLength(v1
);
240 if (n
!= Array
.getLength(v2
)) {
243 for (int i
= 0; i
< n
; ++i
) {
244 // Recursively using areSame on Java values that are (boxed)
245 // elements of Java arrays representing UNO sequence values,
246 // instead of on Java values that are representations of UNO ANY
247 // values, works by chance:
248 if (!areSame(Array
.get(v1
, i
), Array
.get(v2
, i
))) {
253 case TypeClass
.ENUM_value
:
255 case TypeClass
.STRUCT_value
:
256 case TypeClass
.EXCEPTION_value
:
257 IFieldDescription
[] fs
;
259 fs
= TypeDescription
.getTypeDescription(t
).
260 getFieldDescriptions();
261 } catch (ClassNotFoundException e
) {
262 throw new java
.lang
.RuntimeException(e
.toString());
264 for (int i
= 0; i
< fs
.length
; ++i
) {
265 Type ft
= new Type(fs
[i
].getTypeDescription());
267 // Recursively using areSame on Java values that are (boxed)
268 // fields of Java classes representing UNO struct or
269 // exception values, instead of on Java values that are
270 // representations of UNO ANY values, works by chance:
272 completeValue(ft
, fs
[i
].getField().get(v1
)),
273 completeValue(ft
, fs
[i
].getField().get(v2
))))
277 } catch (IllegalAccessException e
) {
278 throw new java
.lang
.RuntimeException(e
.toString());
282 case TypeClass
.INTERFACE_value
:
284 || (v1
instanceof IQueryInterface
285 && ((IQueryInterface
) v1
).isSame(v2
))
286 || (v2
instanceof IQueryInterface
287 && ((IQueryInterface
) v2
).isSame(v1
));
289 throw new java
.lang
.RuntimeException(
290 "com.sun.star.uno.Any has bad com.sun.star.uno.TypeClass");
295 Complete a UNO value (make sure it is no invalid <code>null</code>
298 <p>This is useful for members of parameterized type of instantiated
299 polymorphic struct types, as <code>null</code> is a valid value there
300 (and only there, for all types except <code>ANY</code> and interface
303 @param type a non-void, non-exception UNO type.
305 @param value a Java value representing a UNO value of the given UNO type,
306 or <code>null</code>.
308 @return the given value, or the neutral value of the given type, if the
309 given value was an invalid <code>null</code> value.
313 public static final Object
completeValue(Type type
, Object value
) {
317 switch (type
.getTypeClass().getValue()) {
318 case TypeClass
.BOOLEAN_value
:
319 return Boolean
.FALSE
;
320 case TypeClass
.BYTE_value
:
321 return new Byte((byte) 0);
322 case TypeClass
.SHORT_value
:
323 case TypeClass
.UNSIGNED_SHORT_value
:
324 return new Short((short) 0);
325 case TypeClass
.LONG_value
:
326 case TypeClass
.UNSIGNED_LONG_value
:
327 return new Integer(0);
328 case TypeClass
.HYPER_value
:
329 case TypeClass
.UNSIGNED_HYPER_value
:
331 case TypeClass
.FLOAT_value
:
332 return new Float(0.0f
);
333 case TypeClass
.DOUBLE_value
:
334 return new Double(0.0);
335 case TypeClass
.CHAR_value
:
336 return new Character('\u0000');
337 case TypeClass
.STRING_value
:
339 case TypeClass
.TYPE_value
:
341 case TypeClass
.ANY_value
:
342 case TypeClass
.INTERFACE_value
:
344 case TypeClass
.SEQUENCE_value
:
345 return Array
.newInstance(type
.getZClass().getComponentType(), 0);
346 case TypeClass
.STRUCT_value
:
348 return type
.getZClass().getConstructor(null).newInstance(null);
349 } catch (java
.lang
.RuntimeException e
) {
351 } catch (java
.lang
.Exception e
) {
352 throw new java
.lang
.RuntimeException(e
.toString());
354 case TypeClass
.ENUM_value
:
356 return type
.getZClass().getMethod("getDefault", null).invoke(
358 } catch (java
.lang
.RuntimeException e
) {
360 } catch (java
.lang
.Exception e
) {
361 throw new java
.lang
.RuntimeException(e
.toString());
364 throw new IllegalArgumentException(
365 "com.sun.star.uno.UnoRuntime.completeValue called with bad"
366 + " com.sun.star.uno.Type");
371 * Gets the current context of the current thread, or <code>null</code> if
372 * no context has been set for the current thread.
374 * <p>The current context is thread local, which means that this method
375 * returns the context that was last set for this thread.</p>
377 * @return the current context of the current thread, or <code>null</code>
378 * if no context has been set for the current thread
380 public static XCurrentContext
getCurrentContext() {
381 return (XCurrentContext
) currentContext
.get();
385 * Sets the current context for the current thread.
387 * <p>The current context is thread local. To support a stacking behaviour,
388 * every function that sets the current context should reset it to the
389 * original value when exiting (for example, within a <code>finally</code>
392 * @param context the context to be set; if <code>null</code>, any
393 * previously set context will be removed
395 public static void setCurrentContext(XCurrentContext context
) {
396 // optimize this by using Java 1.5 ThreadLocal.remove if context == null
397 currentContext
.set(context
);
401 * Retrieves an environment of type <code>name</code> with context
402 * <code>context</code>.
404 * <p>Environments are held weakly by this class. If the requested
405 * environment already exists, this methods simply returns it. Otherwise,
406 * this method looks for it under
407 * <code>com.sun.star.lib.uno.environments.<var>name</var>.<!--
408 * --><var>name</var>_environment</code>.</p>
410 * @param name the name of the environment
411 * @param context the context of the environment
412 * @see com.sun.star.uno.IEnvironment
414 * @deprecated As of UDK 3.2.0, this method is deprecated, without
415 * offering a replacement.
417 public static IEnvironment
getEnvironment(String name
, Object context
)
418 throws java
.lang
.Exception
420 synchronized (environments
) {
421 IEnvironment env
= (IEnvironment
) WeakMap
.getValue(
422 environments
.get(name
+ context
));
424 Class c
= Class
.forName(
425 "com.sun.star.lib.uno.environments." + name
+ "." + name
427 Constructor ctor
= c
.getConstructor(
428 new Class
[] { Object
.class });
429 env
= (IEnvironment
) ctor
.newInstance(new Object
[] { context
});
430 environments
.put(name
+ context
, env
);
437 * Gets a bridge from environment <code>from</code> to environment
440 * <p>Creates a new bridge, if the requested bridge does not yet exist, and
441 * hands the arguments to the bridge.</p>
443 * <p>If the requested bridge does not exist, it is searched for in package
444 * <code>com.sun.star.lib.uno.bridges.<var>from</var>_<var>to</var>;</code>
445 * and the root classpath as
446 * <code><var>from</var>_<var>to</var>_bridge</code>.</p>
448 * @param from the source environment
449 * @param to the target environment
450 * @param args the initial arguments for the bridge
451 * @return the requested bridge
452 * @see #getBridgeByName
453 * @see com.sun.star.uno.IBridge
454 * @see com.sun.star.uno.IEnvironment
456 * @deprecated As of UDK 3.2.0, this method is deprecated, without
457 * offering a replacement.
459 public static IBridge
getBridge(
460 IEnvironment from
, IEnvironment to
, Object
[] args
)
461 throws java
.lang
.Exception
463 synchronized (bridges
) {
464 String name
= from
.getName() + "_" + to
.getName();
465 String hashName
= from
.getName() + from
.getContext() + "_"
466 + to
.getName() + to
.getContext();
467 IBridge bridge
= (IBridge
) WeakMap
.getValue(bridges
.get(hashName
));
470 String className
= name
+ "_bridge";
472 zClass
= Class
.forName(className
);
473 } catch (ClassNotFoundException e
) {
474 className
= "com.sun.star.lib.uno.bridges." + name
+ "."
476 zClass
= Class
.forName(className
);
478 Class
[] signature
= {
479 IEnvironment
.class, IEnvironment
.class, args
.getClass() };
480 Constructor constructor
= zClass
.getConstructor(signature
);
481 Object
[] iargs
= { from
, to
, args
};
482 bridge
= (IBridge
) constructor
.newInstance(iargs
);
483 bridges
.put(hashName
, bridge
);
490 * Gets a bridge from environment <code>from</code> to environment
493 * <p>Creates a new bridge, if the requested bridge does not yet exist, and
494 * hands the arguments to the bridge.</p>
496 * <p>If the requested bridge does not exist, it is searched for in package
497 * <code>com.sun.star.lib.uno.bridges.<var>from</var>_<var>to</var>;</code>
498 * and the root classpath as
499 * <code><var>from</var>_<var>to</var>_bridge</code>. The used environments
500 * are retrieved through <code>getEnvironment</code>.</p>
502 * @param from the name of the source environment
503 * @param fromContext the context for the source environment
504 * @param to the name of the target environment
505 * @param toContext the context for the target environment
506 * @param args the initial arguments for the bridge
507 * @return the requested bridge
509 * @see #getEnvironment
510 * @see com.sun.star.uno.IBridge
511 * @see com.sun.star.uno.IEnvironment
513 * @deprecated As of UDK 3.2.0, this method is deprecated, without
514 * offering a replacement.
516 public static IBridge
getBridgeByName(
517 String from
, Object fromContext
, String to
, Object toContext
,
518 Object
[] args
) throws java
.lang
.Exception
521 getEnvironment(from
, fromContext
), getEnvironment(to
, toContext
),
526 * Returns an array of all active bridges.
528 * @return an array of <code>IBridge</code> objects
529 * @see com.sun.star.uno.IBridge
531 * @deprecated As of UDK 3.2.0, this method is deprecated, without
532 * offering a replacement.
534 public static IBridge
[] getBridges() {
535 ArrayList l
= new ArrayList();
536 synchronized (bridges
) {
537 for (Iterator i
= bridges
.values().iterator(); i
.hasNext();) {
538 Object o
= WeakMap
.getValue(i
.next());
544 return (IBridge
[]) l
.toArray(new IBridge
[l
.size()]);
548 * Gets a mapping from environment <code>from</code> to environment
551 * <p>Mappings are like bridges, except that with mappings one can only map
552 * in one direction. Mappings are here for compatibility with the binary
553 * UNO API. Mappings are implemented as wrappers around bridges.</p>
555 * @param from the source environment
556 * @param to the target environment
557 * @return the requested mapping
558 * @see com.sun.star.uno.IEnvironment
559 * @see com.sun.star.uno.IMapping
561 * @deprecated As of UDK 3.2.0, this method is deprecated, without
562 * offering a replacement.
564 public static IMapping
getMapping(IEnvironment from
, IEnvironment to
)
565 throws java
.lang
.Exception
569 bridge
= getBridge(from
, to
, null);
571 catch (ClassNotFoundException e
) {
572 bridge
= new BridgeTurner(getBridge(to
, from
, null));
574 return new MappingWrapper(bridge
);
578 * Gets a mapping from environment <code>from</code> to environment
581 * <p>The used environments are retrieved through
582 * <code>getEnvironment</code>.</p>
584 * @param from the name of the source environment
585 * @param to the name of the target environment
586 * @return the requested mapping
587 * @see #getEnvironment
589 * @see com.sun.star.uno.IMapping
591 * @deprecated As of UDK 3.2.0, this method is deprecated, without
592 * offering a replacement.
594 public static IMapping
getMappingByName(String from
, String to
)
595 throws java
.lang
.Exception
597 return getMapping(getEnvironment(from
, null), getEnvironment(to
, null));
601 * Resets this <code>UnoRuntime</code> to its initial state.
603 * <p>Releases all references to bridges and environments.</p>
605 * @deprecated As of UDK 3.2.0, this method is deprecated, without
606 * offering a replacement.
608 static public boolean reset() {
609 synchronized (bridges
) {
610 for (Iterator i
= bridges
.values().iterator(); i
.hasNext();) {
611 IBridge b
= (IBridge
) WeakMap
.getValue(i
.next());
613 // The following call to dispose was originally made to
614 // com.sun.star.lib.sandbox.Disposable.dispose, which cannot
615 // throw an InterruptedException or IOException:
618 } catch (InterruptedException e
) {
619 Thread
.currentThread().interrupted();
620 throw new RuntimeException(
621 "Unexpected exception in UnoRuntime.reset: " + e
);
622 } catch (IOException e
) {
623 throw new RuntimeException(
624 "Unexpected exception in UnoRuntime.reset: " + e
);
630 environments
.clear();
631 return bridges
.isEmpty() && environments
.isEmpty();
635 * @deprecated As of UDK 3.2.0, do not use this internal field.
637 static public final boolean DEBUG
= false;
639 private static final class BridgeTurner
implements IBridge
{
640 public BridgeTurner(IBridge bridge
) {
641 this.bridge
= bridge
;
644 public Object
mapInterfaceTo(Object object
, Type type
) {
645 return bridge
.mapInterfaceFrom(object
, type
);
648 public Object
mapInterfaceFrom(Object object
, Type type
) {
649 return bridge
.mapInterfaceTo(object
, type
);
652 public IEnvironment
getSourceEnvironment() {
653 return bridge
.getTargetEnvironment();
656 public IEnvironment
getTargetEnvironment() {
657 return bridge
.getSourceEnvironment();
660 public void acquire() {
664 public void release() {
668 public void dispose() throws InterruptedException
, IOException
{
672 private final IBridge bridge
;
675 private static final class MappingWrapper
implements IMapping
{
676 public MappingWrapper(IBridge bridge
) {
677 this.bridge
= bridge
;
680 public Object
mapInterface(Object object
, Type type
) {
681 return bridge
.mapInterfaceTo(object
, type
);
684 private final IBridge bridge
;
687 private static final String uniqueKeyHostPrefix
688 = Integer
.toString(new Object().hashCode(), 16) + ":";
689 private static final Object uniqueKeyLock
= new Object();
690 private static long uniqueKeyTime
= System
.currentTimeMillis();
691 private static long uniqueKeyCount
= Long
.MIN_VALUE
;
693 private static final String oidSuffix
= ";java[];" + getUniqueKey();
695 private static final ThreadLocal currentContext
= new ThreadLocal();
697 private static final WeakMap environments
= new WeakMap();
698 private static final WeakMap bridges
= new WeakMap();