bump product version to 4.1.6.2
[LibreOffice.git] / ridljar / com / sun / star / uno / UnoRuntime.java
blob1ebde7d98094b1fef854f0ddd77e11e2ff04caec
1 /*
2 * This file is part of the LibreOffice project.
4 * This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 * This file incorporates work covered by the following license notice:
10 * Licensed to the Apache Software Foundation (ASF) under one or more
11 * contributor license agreements. See the NOTICE file distributed
12 * with this work for additional information regarding copyright
13 * ownership. The ASF licenses this file to you under the Apache
14 * License, Version 2.0 (the "License"); you may not use this file
15 * except in compliance with the License. You may obtain a copy of
16 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
19 package com.sun.star.uno;
21 import java.io.IOException;
22 import java.lang.reflect.Array;
23 import java.lang.reflect.Constructor;
24 import java.util.ArrayList;
25 import java.util.Iterator;
26 import com.sun.star.lib.uno.typedesc.TypeDescription;
27 import com.sun.star.lib.util.WeakMap;
29 /**
30 * The central class needed for implementing or using UNO components in Java.
32 * <p>The methods <code>queryInterface</code> and <code>areSame</code> delegate
33 * calls to the implementing objects and are used instead of casts,
34 * <code>instanceof</code>, <code>==</code>, and <code>equals</code>.<p>
36 * <p>For historic reasons, this class is not <code>final</code>, and has a
37 * <code>public</code> constructor. These artifacts are considered mistakes,
38 * which might be corrected in a future version of this class, so client code
39 * should not rely on them.</p>
41 * @see com.sun.star.uno.IBridge
42 * @see com.sun.star.uno.IEnvironment
43 * @see com.sun.star.uno.IQueryInterface
45 public class UnoRuntime {
46 /**
47 * @deprecated As of UDK&nbsp;3.2.0, do not create instances of this class.
48 * It is considered a historic mistake to have a <code>public</code>
49 * constructor for this class, which only has <code>static</code> members.
50 * Also, this class might be changed to become <code>final</code> in a
51 * future version.
53 public UnoRuntime() {}
55 /**
56 * Generates a world wide unique identifier string.
58 * <p>It is guaranteed that every invocation of this method generates a new
59 * ID, which is unique within the VM. The quality of &ldquo;world wide
60 * unique&rdquo; will depend on the actual implementation, you should look
61 * at the source to determine if it meets your requirements.</p>
63 * @return a unique <code>String</code>
65 public static String getUniqueKey() {
66 synchronized (uniqueKeyLock) {
67 if (uniqueKeyCount == Long.MAX_VALUE) {
68 long time;
69 for (time = System.currentTimeMillis(); time == uniqueKeyTime;)
71 // Conservatively sleep for 100 millisecond to wait for
72 // System.currentTimeMillis() to change:
73 try {
74 Thread.sleep(100);
75 } catch (InterruptedException e) {
76 Thread.currentThread().interrupt();
79 uniqueKeyTime = time;
80 uniqueKeyCount = Long.MIN_VALUE;
82 return uniqueKeyHostPrefix + Long.toString(uniqueKeyTime, 16) + ":"
83 + Long.toString(uniqueKeyCount++, 16);
87 /**
88 * Generates a world wide unique object identifier (OID) for the given
89 * Java object.
91 * <p>It is guaranteed that subsequent calls to this method with the same
92 * Java object will give the same ID.</p>
94 * <p>This method is generally of little use for client code. It should be
95 * considered a mistake that this method is published at all.</p>
97 * @param object any object for which a OID shall be generated; must not be
98 * <code>null</code>
99 * @return the generated OID
100 * @see com.sun.star.uno.IQueryInterface#getOid
102 public static String generateOid(Object object) {
103 String oid = null;
104 if (object instanceof IQueryInterface) {
105 oid = ((IQueryInterface) object).getOid();
107 return oid == null ? object.hashCode() + oidSuffix : oid;
111 * Queries the given UNO object for the given UNO interface type.
113 * <p>This method returns <code>null</code> in case the given UNO object
114 * does not support the given UNO interface type (or is itself
115 * <code>null</code>). Otherwise, a reference to a Java object implementing
116 * the Java interface type corresponding to the given UNO interface is
117 * returned. In the latter case, it is unspecified whether the returned
118 * Java object is the same as the given object, or is another facet of that
119 * UNO object.</p>
121 * @param type the requested UNO interface type; must be a <code>Type</code>
122 * object representing a UNO interface type
123 * @param object a reference to any Java object representing (a facet of) a
124 * UNO object; may be <code>null</code>
125 * @return a reference to the requested UNO interface type if available,
126 * otherwise <code>null</code>
127 * @see com.sun.star.uno.IQueryInterface#queryInterface
129 public static Object queryInterface(Type type, Object object) {
130 // Gracefully handle those situations where the passed in UNO object is
131 // wrapped in an Any. Strictly speaking, such a situation constitutes a
132 // bug, but it is anticipated that such situations will arise quite
133 // often in practice (especially since UNO Anys containing an XInterface
134 // reference are not wrapped in a Java Any, but UNO Anys containing any
135 // other interface reference are wrapped in a Java Any, which can lead
136 // to confusion).
137 if (object instanceof Any) {
138 Any a = (Any) object;
139 if (a.getType().getTypeClass() == TypeClass.INTERFACE) {
140 object = a.getObject();
143 if (object instanceof IQueryInterface) {
144 object = ((IQueryInterface) object).queryInterface(type);
145 if (object instanceof Any) {
146 Any a = (Any) object;
147 object = a.getType().getTypeClass() == TypeClass.INTERFACE
148 ? a.getObject() : null;
151 // Ensure that the object implements the requested interface type:
152 Class<?> c = type.getZClass();
153 if (c == null || !c.isInstance(object)) {
154 object = null;
156 return object;
160 * Queries the given UNO object for the given Java class (which must
161 * represent a UNO interface type).
163 * @param zInterface a Java class representing a UNO interface type
164 * @param object a reference to any Java object representing (a facet of) a
165 * UNO object; may be <code>null</code>
166 * @return a reference to the requested UNO interface type if available,
167 * otherwise <code>null</code>
168 * @see #queryInterface(Type, Object)
170 @SuppressWarnings("unchecked")
171 public static <T> T queryInterface(Class<T> zInterface, Object object) {
172 return (T) queryInterface(new Type(zInterface), object);
176 Tests two UNO <code>ANY</code> values for equality.
178 <p>Two UNO values are <dfn>equal</dfn> if and only if they are of the
179 same UNO type&nbsp;<var>t</var>, and they meet the following condition,
180 depending on&nbsp;<var>t</var>:</p>
181 <ul>
182 <li>If <var>t</var> is a primitive type, then both values must denote
183 the same element of the set of values of&nbsp;<var>t</var>.</li>
185 <li>If <var>t</var> is a structured type, then both values must
186 recursively contain corresponding values that are equal.</li>
188 <li>If <var>t</var> is an interface type, then the two values must be
189 either both null references, or both references to the same UNO
190 object.</li>
191 </ul>
193 @param any1 a Java value representing a UNO <code>ANY</code> value.
195 @param any2 a Java value representing a UNO <code>ANY</code> value.
197 @return <code>true</code> if and only if the two arguments represent
198 equal UNO values.
200 public static boolean areSame(Object any1, Object any2) {
201 Any a1 = Any.complete(any1);
202 Any a2 = Any.complete(any2);
203 Type t = a1.getType();
204 if (!a2.getType().equals(t)) {
205 return false;
207 Object v1 = a1.getObject();
208 Object v2 = a2.getObject();
209 switch (t.getTypeClass().getValue()) {
210 case TypeClass.VOID_value:
211 return true;
212 case TypeClass.BOOLEAN_value:
213 case TypeClass.BYTE_value:
214 case TypeClass.SHORT_value:
215 case TypeClass.UNSIGNED_SHORT_value:
216 case TypeClass.LONG_value:
217 case TypeClass.UNSIGNED_LONG_value:
218 case TypeClass.HYPER_value:
219 case TypeClass.UNSIGNED_HYPER_value:
220 case TypeClass.FLOAT_value:
221 case TypeClass.DOUBLE_value:
222 case TypeClass.CHAR_value:
223 case TypeClass.STRING_value:
224 case TypeClass.TYPE_value:
225 return v1.equals(v2);
226 case TypeClass.SEQUENCE_value:
227 int n = Array.getLength(v1);
228 if (n != Array.getLength(v2)) {
229 return false;
231 for (int i = 0; i < n; ++i) {
232 // Recursively using areSame on Java values that are (boxed)
233 // elements of Java arrays representing UNO sequence values,
234 // instead of on Java values that are representations of UNO ANY
235 // values, works by chance:
236 if (!areSame(Array.get(v1, i), Array.get(v2, i))) {
237 return false;
240 return true;
241 case TypeClass.ENUM_value:
242 return v1 == v2;
243 case TypeClass.STRUCT_value:
244 case TypeClass.EXCEPTION_value:
245 IFieldDescription[] fs;
246 try {
247 fs = TypeDescription.getTypeDescription(t).
248 getFieldDescriptions();
249 } catch (ClassNotFoundException e) {
250 throw new java.lang.RuntimeException(e.toString());
252 for (int i = 0; i< fs.length; ++i) {
253 Type ft = new Type(fs[i].getTypeDescription());
254 try {
255 // Recursively using areSame on Java values that are (boxed)
256 // fields of Java classes representing UNO struct or
257 // exception values, instead of on Java values that are
258 // representations of UNO ANY values, works by chance:
259 if (!areSame(
260 completeValue(ft, fs[i].getField().get(v1)),
261 completeValue(ft, fs[i].getField().get(v2))))
263 return false;
265 } catch (IllegalAccessException e) {
266 throw new java.lang.RuntimeException(e.toString());
269 return true;
270 case TypeClass.INTERFACE_value:
271 return v1 == v2
272 || (v1 instanceof IQueryInterface
273 && ((IQueryInterface) v1).isSame(v2))
274 || (v2 instanceof IQueryInterface
275 && ((IQueryInterface) v2).isSame(v1));
276 default:
277 throw new java.lang.RuntimeException(
278 "com.sun.star.uno.Any has bad com.sun.star.uno.TypeClass");
283 Complete a UNO value (make sure it is no invalid <code>null</code>
284 value).
286 <p>This is useful for members of parameterized type of instantiated
287 polymorphic struct types, as <code>null</code> is a valid value there
288 (and only there, for all types except <code>ANY</code> and interface
289 types).</p>
291 @param type a non-void, non-exception UNO type.
293 @param value a Java value representing a UNO value of the given UNO type,
294 or <code>null</code>.
296 @return the given value, or the neutral value of the given type, if the
297 given value was an invalid <code>null</code> value.
299 @since UDK 3.2.3
301 public static final Object completeValue(Type type, Object value) {
302 if (value != null) {
303 return value;
305 switch (type.getTypeClass().getValue()) {
306 case TypeClass.BOOLEAN_value:
307 return Boolean.FALSE;
308 case TypeClass.BYTE_value:
309 return new Byte((byte) 0);
310 case TypeClass.SHORT_value:
311 case TypeClass.UNSIGNED_SHORT_value:
312 return new Short((short) 0);
313 case TypeClass.LONG_value:
314 case TypeClass.UNSIGNED_LONG_value:
315 return new Integer(0);
316 case TypeClass.HYPER_value:
317 case TypeClass.UNSIGNED_HYPER_value:
318 return new Long(0L);
319 case TypeClass.FLOAT_value:
320 return new Float(0.0f);
321 case TypeClass.DOUBLE_value:
322 return new Double(0.0);
323 case TypeClass.CHAR_value:
324 return new Character('\u0000');
325 case TypeClass.STRING_value:
326 return "";
327 case TypeClass.TYPE_value:
328 return Type.VOID;
329 case TypeClass.ANY_value:
330 case TypeClass.INTERFACE_value:
331 return null;
332 case TypeClass.SEQUENCE_value:
333 return Array.newInstance(type.getZClass().getComponentType(), 0);
334 case TypeClass.STRUCT_value:
335 try {
336 return type.getZClass().getConstructor((Class[]) null).
337 newInstance((Object[]) null);
338 } catch (java.lang.RuntimeException e) {
339 throw e;
340 } catch (java.lang.Exception e) {
341 throw new java.lang.RuntimeException(e.toString());
343 case TypeClass.ENUM_value:
344 try {
345 return type.getZClass().getMethod("getDefault", (Class[]) null).
346 invoke(null, (Object[]) null);
347 } catch (java.lang.RuntimeException e) {
348 throw e;
349 } catch (java.lang.Exception e) {
350 throw new java.lang.RuntimeException(e.toString());
352 default:
353 throw new IllegalArgumentException(
354 "com.sun.star.uno.UnoRuntime.completeValue called with bad"
355 + " com.sun.star.uno.Type");
360 * Gets the current context of the current thread, or <code>null</code> if
361 * no context has been set for the current thread.
363 * <p>The current context is thread local, which means that this method
364 * returns the context that was last set for this thread.</p>
366 * @return the current context of the current thread, or <code>null</code>
367 * if no context has been set for the current thread
369 public static XCurrentContext getCurrentContext() {
370 return currentContext.get();
374 * Sets the current context for the current thread.
376 * <p>The current context is thread local. To support a stacking behaviour,
377 * every function that sets the current context should reset it to the
378 * original value when exiting (for example, within a <code>finally</code>
379 * block).</p>
381 * @param context the context to be set; if <code>null</code>, any
382 * previously set context will be removed
384 public static void setCurrentContext(XCurrentContext context) {
385 // optimize this by using Java 1.5 ThreadLocal.remove if context == null
386 currentContext.set(context);
390 * Retrieves an environment of type <code>name</code> with context
391 * <code>context</code>.
393 * <p>Environments are held weakly by this class. If the requested
394 * environment already exists, this methods simply returns it. Otherwise,
395 * this method looks for it under
396 * <code>com.sun.star.lib.uno.environments.<var>name</var>.<!--
397 * --><var>name</var>_environment</code>.</p>
399 * @param name the name of the environment
400 * @param context the context of the environment
401 * @see com.sun.star.uno.IEnvironment
403 * @deprecated As of UDK&nbsp;3.2.0, this method is deprecated, without
404 * offering a replacement.
406 public static IEnvironment getEnvironment(String name, Object context)
407 throws java.lang.Exception
409 synchronized (environments) {
410 IEnvironment env = WeakMap.getValue(
411 environments.get(name + context));
412 if (env == null) {
413 Class<?> c = Class.forName(
414 "com.sun.star.lib.uno.environments." + name + "." + name
415 + "_environment");
416 Constructor<?> ctor = c.getConstructor(
417 new Class[] { Object.class });
418 env = (IEnvironment) ctor.newInstance(new Object[] { context });
419 environments.put(name + context, env);
421 return env;
426 * Gets a bridge from environment <code>from</code> to environment
427 * <code>to</code>.
429 * <p>Creates a new bridge, if the requested bridge does not yet exist, and
430 * hands the arguments to the bridge.</p>
432 * <p>If the requested bridge does not exist, it is searched for in package
433 * <code>com.sun.star.lib.uno.bridges.<var>from</var>_<var>to</var>;</code>
434 * and the root classpath as
435 * <code><var>from</var>_<var>to</var>_bridge</code>.</p>
437 * @param from the source environment
438 * @param to the target environment
439 * @param args the initial arguments for the bridge
440 * @return the requested bridge
441 * @see #getBridgeByName
442 * @see com.sun.star.uno.IBridge
443 * @see com.sun.star.uno.IEnvironment
445 * @deprecated As of UDK&nbsp;3.2.0, this method is deprecated, without
446 * offering a replacement.
448 public static IBridge getBridge(
449 IEnvironment from, IEnvironment to, Object[] args)
450 throws java.lang.Exception
452 synchronized (bridges) {
453 String name = from.getName() + "_" + to.getName();
454 String hashName = from.getName() + from.getContext() + "_"
455 + to.getName() + to.getContext();
456 IBridge bridge = WeakMap.getValue(bridges.get(hashName));
457 if(bridge == null) {
458 Class<?> zClass = null;
459 String className = name + "_bridge";
460 try {
461 zClass = Class.forName(className);
462 } catch (ClassNotFoundException e) {
463 className = "com.sun.star.lib.uno.bridges." + name + "."
464 + className;
465 zClass = Class.forName(className);
467 Class<?>[] signature = {
468 IEnvironment.class, IEnvironment.class, args.getClass() };
469 Constructor<?> constructor = zClass.getConstructor(signature);
470 Object[] iargs = { from, to, args };
471 bridge = (IBridge) constructor.newInstance(iargs);
472 bridges.put(hashName, bridge);
474 return bridge;
479 * Gets a bridge from environment <code>from</code> to environment
480 * <code>to</code>.
482 * <p>Creates a new bridge, if the requested bridge does not yet exist, and
483 * hands the arguments to the bridge.</p>
485 * <p>If the requested bridge does not exist, it is searched for in package
486 * <code>com.sun.star.lib.uno.bridges.<var>from</var>_<var>to</var>;</code>
487 * and the root classpath as
488 * <code><var>from</var>_<var>to</var>_bridge</code>. The used environments
489 * are retrieved through <code>getEnvironment</code>.</p>
491 * @param from the name of the source environment
492 * @param fromContext the context for the source environment
493 * @param to the name of the target environment
494 * @param toContext the context for the target environment
495 * @param args the initial arguments for the bridge
496 * @return the requested bridge
497 * @see #getBridge
498 * @see #getEnvironment
499 * @see com.sun.star.uno.IBridge
500 * @see com.sun.star.uno.IEnvironment
502 * @deprecated As of UDK&nbsp;3.2.0, this method is deprecated, without
503 * offering a replacement.
505 public static IBridge getBridgeByName(
506 String from, Object fromContext, String to, Object toContext,
507 Object[] args) throws java.lang.Exception
509 return getBridge(
510 getEnvironment(from, fromContext), getEnvironment(to, toContext),
511 args);
515 * Returns an array of all active bridges.
517 * @return an array of <code>IBridge</code> objects
518 * @see com.sun.star.uno.IBridge
520 * @deprecated As of UDK&nbsp;3.2.0, this method is deprecated, without
521 * offering a replacement.
523 public static IBridge[] getBridges() {
524 ArrayList<Object> l = new ArrayList<Object>();
525 synchronized (bridges) {
526 for (Iterator<java.lang.ref.WeakReference<IBridge>> i = bridges.values().iterator(); i.hasNext();) {
527 IBridge o = WeakMap.getValue(i.next());
528 if (o != null) {
529 l.add(o);
533 return l.toArray(new IBridge[l.size()]);
537 * Gets a mapping from environment <code>from</code> to environment
538 * <code>to</code>.
540 * <p>Mappings are like bridges, except that with mappings one can only map
541 * in one direction. Mappings are here for compatibility with the binary
542 * UNO API. Mappings are implemented as wrappers around bridges.</p>
544 * @param from the source environment
545 * @param to the target environment
546 * @return the requested mapping
547 * @see com.sun.star.uno.IEnvironment
548 * @see com.sun.star.uno.IMapping
550 * @deprecated As of UDK&nbsp;3.2.0, this method is deprecated, without
551 * offering a replacement.
553 public static IMapping getMapping(IEnvironment from, IEnvironment to)
554 throws java.lang.Exception
556 IBridge bridge;
557 try {
558 bridge = getBridge(from, to, null);
560 catch (ClassNotFoundException e) {
561 bridge = new BridgeTurner(getBridge(to, from, null));
563 return new MappingWrapper(bridge);
567 * Gets a mapping from environment <code>from</code> to environment
568 * <code>to</code>.
570 * <p>The used environments are retrieved through
571 * <code>getEnvironment</code>.</p>
573 * @param from the name of the source environment
574 * @param to the name of the target environment
575 * @return the requested mapping
576 * @see #getEnvironment
577 * @see #getMapping
578 * @see com.sun.star.uno.IMapping
580 * @deprecated As of UDK&nbsp;3.2.0, this method is deprecated, without
581 * offering a replacement.
583 public static IMapping getMappingByName(String from, String to)
584 throws java.lang.Exception
586 return getMapping(getEnvironment(from, null), getEnvironment(to, null));
590 * Resets this <code>UnoRuntime</code> to its initial state.
592 * <p>Releases all references to bridges and environments.</p>
594 * @deprecated As of UDK&nbsp;3.2.0, this method is deprecated, without
595 * offering a replacement.
597 static public boolean reset() {
598 synchronized (bridges) {
599 for (Iterator<java.lang.ref.WeakReference<IBridge>> i = bridges.values().iterator(); i.hasNext();) {
600 IBridge b = WeakMap.getValue(i.next());
601 if (b != null) {
602 // The following call to dispose was originally made to
603 // com.sun.star.lib.sandbox.Disposable.dispose, which cannot
604 // throw an InterruptedException or IOException:
605 try {
606 b.dispose();
607 } catch (InterruptedException e) {
608 Thread.currentThread();
609 Thread.interrupted();
610 throw new RuntimeException(
611 "Unexpected exception in UnoRuntime.reset: " + e);
612 } catch (IOException e) {
613 throw new RuntimeException(
614 "Unexpected exception in UnoRuntime.reset: " + e);
618 bridges.clear();
620 environments.clear();
621 return bridges.isEmpty() && environments.isEmpty();
625 * @deprecated As of UDK&nbsp;3.2.0, do not use this internal field.
627 static public final boolean DEBUG = false;
629 private static final class BridgeTurner implements IBridge {
630 public BridgeTurner(IBridge bridge) {
631 this.bridge = bridge;
634 public Object mapInterfaceTo(Object object, Type type) {
635 return bridge.mapInterfaceFrom(object, type);
638 public Object mapInterfaceFrom(Object object, Type type) {
639 return bridge.mapInterfaceTo(object, type);
642 public IEnvironment getSourceEnvironment() {
643 return bridge.getTargetEnvironment();
646 public IEnvironment getTargetEnvironment() {
647 return bridge.getSourceEnvironment();
650 public void acquire() {
651 bridge.acquire();
654 public void release() {
655 bridge.release();
658 public void dispose() throws InterruptedException, IOException {
659 bridge.dispose();
662 private final IBridge bridge;
665 private static final class MappingWrapper implements IMapping {
666 public MappingWrapper(IBridge bridge) {
667 this.bridge = bridge;
670 public Object mapInterface(Object object, Type type) {
671 return bridge.mapInterfaceTo(object, type);
674 private final IBridge bridge;
677 private static final String uniqueKeyHostPrefix
678 = Integer.toString(new Object().hashCode(), 16) + ":";
679 private static final Object uniqueKeyLock = new Object();
680 private static long uniqueKeyTime = System.currentTimeMillis();
681 private static long uniqueKeyCount = Long.MIN_VALUE;
683 private static final String oidSuffix = ";java[];" + getUniqueKey();
685 private static final ThreadLocal<XCurrentContext> currentContext = new ThreadLocal<XCurrentContext>();
687 private static final WeakMap<String,IEnvironment> environments = new WeakMap<String,IEnvironment>();
688 private static final WeakMap<String,IBridge> bridges = new WeakMap<String,IBridge>();