1 /************************************************************************* 2 * 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * Copyright 2000, 2010 Oracle and/or its affiliates. 6 * 7 * OpenOffice.org - a multi-platform office productivity suite 8 * 9 * This file is part of OpenOffice.org. 10 * 11 * OpenOffice.org is free software: you can redistribute it and/or modify 12 * it under the terms of the GNU Lesser General Public License version 3 13 * only, as published by the Free Software Foundation. 14 * 15 * OpenOffice.org is distributed in the hope that it will be useful, 16 * but WITHOUT ANY WARRANTY; without even the implied warranty of 17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 * GNU Lesser General Public License version 3 for more details 19 * (a copy is included in the LICENSE file that accompanied this code). 20 * 21 * You should have received a copy of the GNU Lesser General Public License 22 * version 3 along with OpenOffice.org. If not, see 23 * <http://www.openoffice.org/license.html> 24 * for a copy of the LGPLv3 License. 25 * 26 ************************************************************************/ 27 28 package com.sun.star.uno; 29 30 import java.io.IOException; 31 import java.lang.reflect.Array; 32 import java.lang.reflect.Constructor; 33 import java.util.ArrayList; 34 import java.util.Iterator; 35 import com.sun.star.lib.uno.typedesc.TypeDescription; 36 import com.sun.star.lib.util.WeakMap; 37 38 /** 39 * The central class needed for implementing or using UNO components in Java. 40 * 41 * <p>The methods <code>queryInterface</code> and <code>areSame</code> delegate 42 * calls to the implementing objects and are used instead of casts, 43 * <code>instanceof</code>, <code>==</code>, and <code>equals</code>.<p> 44 * 45 * <p>For historic reasons, this class is not <code>final</code>, and has a 46 * <code>public</code> constructor. These artifacts are considered mistakes, 47 * which might be corrected in a future version of this class, so client code 48 * should not rely on them.</p> 49 * 50 * @see com.sun.star.uno.IBridge 51 * @see com.sun.star.uno.IEnvironment 52 * @see com.sun.star.uno.IQueryInterface 53 */ 54 public class UnoRuntime { 55 /** 56 * @deprecated As of UDK 3.2.0, do not create instances of this class. 57 * It is considered a historic mistake to have a <code>public</code> 58 * constructor for this class, which only has <code>static</code> members. 59 * Also, this class might be changed to become <code>final</code> in a 60 * future version. 61 */ 62 public UnoRuntime() {} 63 64 /** 65 * Generates a world wide unique identifier string. 66 * 67 * <p>It is guaranteed that every invocation of this method generates a new 68 * ID, which is unique within the VM. The quality of “world wide 69 * unique” will depend on the actual implementation, you should look 70 * at the source to determine if it meets your requirements.</p> 71 * 72 * @return a unique <code>String</code> 73 */ 74 public static String getUniqueKey() { 75 synchronized (uniqueKeyLock) { 76 if (uniqueKeyCount == Long.MAX_VALUE) { 77 long time; 78 for (time = System.currentTimeMillis(); time == uniqueKeyTime;) 79 { 80 // Conservatively sleep for 100 millisecond to wait for 81 // System.currentTimeMillis() to change: 82 try { 83 Thread.sleep(100); 84 } catch (InterruptedException e) { 85 Thread.currentThread().interrupt(); 86 } 87 } 88 uniqueKeyTime = time; 89 uniqueKeyCount = Long.MIN_VALUE; 90 } 91 return uniqueKeyHostPrefix + Long.toString(uniqueKeyTime, 16) + ":" 92 + Long.toString(uniqueKeyCount++, 16); 93 } 94 } 95 96 /** 97 * Generates a world wide unique object identifier (OID) for the given 98 * Java object. 99 * 100 * <p>It is guaranteed that subsequent calls to this method with the same 101 * Java object will give the same ID.</p> 102 * 103 * <p>This method is generally of little use for client code. It should be 104 * considered a mistake that this method is published at all.</p> 105 * 106 * @param object any object for which a OID shall be generated; must not be 107 * <code>null</code> 108 * @return the generated OID 109 * @see com.sun.star.uno.IQueryInterface#getOid 110 */ 111 public static String generateOid(Object object) { 112 String oid = null; 113 if (object instanceof IQueryInterface) { 114 oid = ((IQueryInterface) object).getOid(); 115 } 116 return oid == null ? object.hashCode() + oidSuffix : oid; 117 } 118 119 /** 120 * Queries the given UNO object for the given UNO interface type. 121 * 122 * <p>This method returns <code>null</code> in case the given UNO object 123 * does not support the given UNO interface type (or is itself 124 * <code>null</code>). Otherwise, a reference to a Java object implementing 125 * the Java interface type corresponding to the given UNO interface is 126 * returned. In the latter case, it is unspecified whether the returned 127 * Java object is the same as the given object, or is another facet of that 128 * UNO object.</p> 129 * 130 * @param type the requested UNO interface type; must be a <code>Type</code> 131 * object representing a UNO interface type 132 * @param object a reference to any Java object representing (a facet of) a 133 * UNO object; may be <code>null</code> 134 * @return a reference to the requested UNO interface type if available, 135 * otherwise <code>null</code> 136 * @see com.sun.star.uno.IQueryInterface#queryInterface 137 */ 138 public static Object queryInterface(Type type, Object object) { 139 // Gracefully handle those situations where the passed in UNO object is 140 // wrapped in an Any. Strictly speaking, such a situation constitutes a 141 // bug, but it is anticipated that such situations will arise quite 142 // often in practice (especially since UNO Anys containing an XInterface 143 // reference are not wrapped in a Java Any, but UNO Anys containing any 144 // other interface reference are wrapped in a Java Any, which can lead 145 // to confusion). 146 if (object instanceof Any) { 147 Any a = (Any) object; 148 if (a.getType().getTypeClass() == TypeClass.INTERFACE) { 149 object = a.getObject(); 150 } 151 } 152 if (object instanceof IQueryInterface) { 153 object = ((IQueryInterface) object).queryInterface(type); 154 if (object instanceof Any) { 155 Any a = (Any) object; 156 object = a.getType().getTypeClass() == TypeClass.INTERFACE 157 ? a.getObject() : null; 158 } 159 } 160 // Ensure that the object implements the requested interface type: 161 Class c = type.getZClass(); 162 if (c == null || !c.isInstance(object)) { 163 object = null; 164 } 165 return object; 166 } 167 168 /** 169 * Queries the given UNO object for the given Java class (which must 170 * represent a UNO interface type). 171 * 172 * @param ifc a Java class representing a UNO interface type 173 * @param object a reference to any Java object representing (a facet of) a 174 * UNO object; may be <code>null</code> 175 * @return a reference to the requested UNO interface type if available, 176 * otherwise <code>null</code> 177 * @see #queryInterface(Type, Object) 178 */ 179 @SuppressWarnings("unchecked") 180 public static <T> T queryInterface(Class<T> zInterface, Object object) { 181 return (T) queryInterface(new Type(zInterface), object); 182 } 183 184 /** 185 Tests two UNO <code>ANY</code> values for equality. 186 187 <p>Two UNO values are <dfn>equal</dfn> if and only if they are of the 188 same UNO type <var>t</var>, and they meet the following condition, 189 depending on <var>t</var>:</p> 190 <ul> 191 <li>If <var>t</var> is a primitive type, then both values must denote 192 the same element of the set of values of <var>t</var>.</li> 193 194 <li>If <var>t</var> is a structured type, then both values must 195 recursively contain corresponding values that are equal.</li> 196 197 <li>If <var>t</var> is an interface type, then the two values must be 198 either both null references, or both references to the same UNO 199 object.</li> 200 </ul> 201 202 @param any1 a Java value representing a UNO <code>ANY</code> value. 203 204 @param any2 a Java value representing a UNO <code>ANY</code> value. 205 206 @return <code>true</code> if and only if the two arguments represent 207 equal UNO values. 208 */ 209 public static boolean areSame(Object any1, Object any2) { 210 Any a1 = Any.complete(any1); 211 Any a2 = Any.complete(any2); 212 Type t = a1.getType(); 213 if (!a2.getType().equals(t)) { 214 return false; 215 } 216 Object v1 = a1.getObject(); 217 Object v2 = a2.getObject(); 218 switch (t.getTypeClass().getValue()) { 219 case TypeClass.VOID_value: 220 return true; 221 case TypeClass.BOOLEAN_value: 222 case TypeClass.BYTE_value: 223 case TypeClass.SHORT_value: 224 case TypeClass.UNSIGNED_SHORT_value: 225 case TypeClass.LONG_value: 226 case TypeClass.UNSIGNED_LONG_value: 227 case TypeClass.HYPER_value: 228 case TypeClass.UNSIGNED_HYPER_value: 229 case TypeClass.FLOAT_value: 230 case TypeClass.DOUBLE_value: 231 case TypeClass.CHAR_value: 232 case TypeClass.STRING_value: 233 case TypeClass.TYPE_value: 234 return v1.equals(v2); 235 case TypeClass.SEQUENCE_value: 236 int n = Array.getLength(v1); 237 if (n != Array.getLength(v2)) { 238 return false; 239 } 240 for (int i = 0; i < n; ++i) { 241 // Recursively using areSame on Java values that are (boxed) 242 // elements of Java arrays representing UNO sequence values, 243 // instead of on Java values that are representations of UNO ANY 244 // values, works by chance: 245 if (!areSame(Array.get(v1, i), Array.get(v2, i))) { 246 return false; 247 } 248 } 249 return true; 250 case TypeClass.ENUM_value: 251 return v1 == v2; 252 case TypeClass.STRUCT_value: 253 case TypeClass.EXCEPTION_value: 254 IFieldDescription[] fs; 255 try { 256 fs = TypeDescription.getTypeDescription(t). 257 getFieldDescriptions(); 258 } catch (ClassNotFoundException e) { 259 throw new java.lang.RuntimeException(e.toString()); 260 } 261 for (int i = 0; i< fs.length; ++i) { 262 Type ft = new Type(fs[i].getTypeDescription()); 263 try { 264 // Recursively using areSame on Java values that are (boxed) 265 // fields of Java classes representing UNO struct or 266 // exception values, instead of on Java values that are 267 // representations of UNO ANY values, works by chance: 268 if (!areSame( 269 completeValue(ft, fs[i].getField().get(v1)), 270 completeValue(ft, fs[i].getField().get(v2)))) 271 { 272 return false; 273 } 274 } catch (IllegalAccessException e) { 275 throw new java.lang.RuntimeException(e.toString()); 276 } 277 } 278 return true; 279 case TypeClass.INTERFACE_value: 280 return v1 == v2 281 || (v1 instanceof IQueryInterface 282 && ((IQueryInterface) v1).isSame(v2)) 283 || (v2 instanceof IQueryInterface 284 && ((IQueryInterface) v2).isSame(v1)); 285 default: 286 throw new java.lang.RuntimeException( 287 "com.sun.star.uno.Any has bad com.sun.star.uno.TypeClass"); 288 } 289 } 290 291 /** 292 Complete a UNO value (make sure it is no invalid <code>null</code> 293 value). 294 295 <p>This is useful for members of parameterized type of instantiated 296 polymorphic struct types, as <code>null</code> is a valid value there 297 (and only there, for all types except <code>ANY</code> and interface 298 types).</p> 299 300 @param type a non-void, non-exception UNO type. 301 302 @param value a Java value representing a UNO value of the given UNO type, 303 or <code>null</code>. 304 305 @return the given value, or the neutral value of the given type, if the 306 given value was an invalid <code>null</code> value. 307 308 @since UDK 3.2.3 309 */ 310 public static final Object completeValue(Type type, Object value) { 311 if (value != null) { 312 return value; 313 } 314 switch (type.getTypeClass().getValue()) { 315 case TypeClass.BOOLEAN_value: 316 return Boolean.FALSE; 317 case TypeClass.BYTE_value: 318 return new Byte((byte) 0); 319 case TypeClass.SHORT_value: 320 case TypeClass.UNSIGNED_SHORT_value: 321 return new Short((short) 0); 322 case TypeClass.LONG_value: 323 case TypeClass.UNSIGNED_LONG_value: 324 return new Integer(0); 325 case TypeClass.HYPER_value: 326 case TypeClass.UNSIGNED_HYPER_value: 327 return new Long(0L); 328 case TypeClass.FLOAT_value: 329 return new Float(0.0f); 330 case TypeClass.DOUBLE_value: 331 return new Double(0.0); 332 case TypeClass.CHAR_value: 333 return new Character('\u0000'); 334 case TypeClass.STRING_value: 335 return ""; 336 case TypeClass.TYPE_value: 337 return Type.VOID; 338 case TypeClass.ANY_value: 339 case TypeClass.INTERFACE_value: 340 return null; 341 case TypeClass.SEQUENCE_value: 342 return Array.newInstance(type.getZClass().getComponentType(), 0); 343 case TypeClass.STRUCT_value: 344 try { 345 return type.getZClass().getConstructor(null).newInstance(null); 346 } catch (java.lang.RuntimeException e) { 347 throw e; 348 } catch (java.lang.Exception e) { 349 throw new java.lang.RuntimeException(e.toString()); 350 } 351 case TypeClass.ENUM_value: 352 try { 353 return type.getZClass().getMethod("getDefault", null).invoke( 354 null, null); 355 } catch (java.lang.RuntimeException e) { 356 throw e; 357 } catch (java.lang.Exception e) { 358 throw new java.lang.RuntimeException(e.toString()); 359 } 360 default: 361 throw new IllegalArgumentException( 362 "com.sun.star.uno.UnoRuntime.completeValue called with bad" 363 + " com.sun.star.uno.Type"); 364 } 365 } 366 367 /** 368 * Gets the current context of the current thread, or <code>null</code> if 369 * no context has been set for the current thread. 370 * 371 * <p>The current context is thread local, which means that this method 372 * returns the context that was last set for this thread.</p> 373 * 374 * @return the current context of the current thread, or <code>null</code> 375 * if no context has been set for the current thread 376 */ 377 public static XCurrentContext getCurrentContext() { 378 return (XCurrentContext) currentContext.get(); 379 } 380 381 /** 382 * Sets the current context for the current thread. 383 * 384 * <p>The current context is thread local. To support a stacking behaviour, 385 * every function that sets the current context should reset it to the 386 * original value when exiting (for example, within a <code>finally</code> 387 * block).</p> 388 * 389 * @param context the context to be set; if <code>null</code>, any 390 * previously set context will be removed 391 */ 392 public static void setCurrentContext(XCurrentContext context) { 393 // optimize this by using Java 1.5 ThreadLocal.remove if context == null 394 currentContext.set(context); 395 } 396 397 /** 398 * Retrieves an environment of type <code>name</code> with context 399 * <code>context</code>. 400 * 401 * <p>Environments are held weakly by this class. If the requested 402 * environment already exists, this methods simply returns it. Otherwise, 403 * this method looks for it under 404 * <code>com.sun.star.lib.uno.environments.<var>name</var>.<!-- 405 * --><var>name</var>_environment</code>.</p> 406 * 407 * @param name the name of the environment 408 * @param context the context of the environment 409 * @see com.sun.star.uno.IEnvironment 410 * 411 * @deprecated As of UDK 3.2.0, this method is deprecated, without 412 * offering a replacement. 413 */ 414 public static IEnvironment getEnvironment(String name, Object context) 415 throws java.lang.Exception 416 { 417 synchronized (environments) { 418 IEnvironment env = (IEnvironment) WeakMap.getValue( 419 environments.get(name + context)); 420 if (env == null) { 421 Class c = Class.forName( 422 "com.sun.star.lib.uno.environments." + name + "." + name 423 + "_environment"); 424 Constructor ctor = c.getConstructor( 425 new Class[] { Object.class }); 426 env = (IEnvironment) ctor.newInstance(new Object[] { context }); 427 environments.put(name + context, env); 428 } 429 return env; 430 } 431 } 432 433 /** 434 * Gets a bridge from environment <code>from</code> to environment 435 * <code>to</code>. 436 * 437 * <p>Creates a new bridge, if the requested bridge does not yet exist, and 438 * hands the arguments to the bridge.</p> 439 * 440 * <p>If the requested bridge does not exist, it is searched for in package 441 * <code>com.sun.star.lib.uno.bridges.<var>from</var>_<var>to</var>;</code> 442 * and the root classpath as 443 * <code><var>from</var>_<var>to</var>_bridge</code>.</p> 444 * 445 * @param from the source environment 446 * @param to the target environment 447 * @param args the initial arguments for the bridge 448 * @return the requested bridge 449 * @see #getBridgeByName 450 * @see com.sun.star.uno.IBridge 451 * @see com.sun.star.uno.IEnvironment 452 * 453 * @deprecated As of UDK 3.2.0, this method is deprecated, without 454 * offering a replacement. 455 */ 456 public static IBridge getBridge( 457 IEnvironment from, IEnvironment to, Object[] args) 458 throws java.lang.Exception 459 { 460 synchronized (bridges) { 461 String name = from.getName() + "_" + to.getName(); 462 String hashName = from.getName() + from.getContext() + "_" 463 + to.getName() + to.getContext(); 464 IBridge bridge = (IBridge) WeakMap.getValue(bridges.get(hashName)); 465 if(bridge == null) { 466 Class zClass = null; 467 String className = name + "_bridge"; 468 try { 469 zClass = Class.forName(className); 470 } catch (ClassNotFoundException e) { 471 className = "com.sun.star.lib.uno.bridges." + name + "." 472 + className; 473 zClass = Class.forName(className); 474 } 475 Class[] signature = { 476 IEnvironment.class, IEnvironment.class, args.getClass() }; 477 Constructor constructor = zClass.getConstructor(signature); 478 Object[] iargs = { from, to, args }; 479 bridge = (IBridge) constructor.newInstance(iargs); 480 bridges.put(hashName, bridge); 481 } 482 return bridge; 483 } 484 } 485 486 /** 487 * Gets a bridge from environment <code>from</code> to environment 488 * <code>to</code>. 489 * 490 * <p>Creates a new bridge, if the requested bridge does not yet exist, and 491 * hands the arguments to the bridge.</p> 492 * 493 * <p>If the requested bridge does not exist, it is searched for in package 494 * <code>com.sun.star.lib.uno.bridges.<var>from</var>_<var>to</var>;</code> 495 * and the root classpath as 496 * <code><var>from</var>_<var>to</var>_bridge</code>. The used environments 497 * are retrieved through <code>getEnvironment</code>.</p> 498 * 499 * @param from the name of the source environment 500 * @param fromContext the context for the source environment 501 * @param to the name of the target environment 502 * @param toContext the context for the target environment 503 * @param args the initial arguments for the bridge 504 * @return the requested bridge 505 * @see #getBridge 506 * @see #getEnvironment 507 * @see com.sun.star.uno.IBridge 508 * @see com.sun.star.uno.IEnvironment 509 * 510 * @deprecated As of UDK 3.2.0, this method is deprecated, without 511 * offering a replacement. 512 */ 513 public static IBridge getBridgeByName( 514 String from, Object fromContext, String to, Object toContext, 515 Object[] args) throws java.lang.Exception 516 { 517 return getBridge( 518 getEnvironment(from, fromContext), getEnvironment(to, toContext), 519 args); 520 } 521 522 /** 523 * Returns an array of all active bridges. 524 * 525 * @return an array of <code>IBridge</code> objects 526 * @see com.sun.star.uno.IBridge 527 * 528 * @deprecated As of UDK 3.2.0, this method is deprecated, without 529 * offering a replacement. 530 */ 531 public static IBridge[] getBridges() { 532 ArrayList l = new ArrayList(); 533 synchronized (bridges) { 534 for (Iterator i = bridges.values().iterator(); i.hasNext();) { 535 Object o = WeakMap.getValue(i.next()); 536 if (o != null) { 537 l.add(o); 538 } 539 } 540 } 541 return (IBridge[]) l.toArray(new IBridge[l.size()]); 542 } 543 544 /** 545 * Gets a mapping from environment <code>from</code> to environment 546 * <code>to</code>. 547 * 548 * <p>Mappings are like bridges, except that with mappings one can only map 549 * in one direction. Mappings are here for compatibility with the binary 550 * UNO API. Mappings are implemented as wrappers around bridges.</p> 551 * 552 * @param from the source environment 553 * @param to the target environment 554 * @return the requested mapping 555 * @see com.sun.star.uno.IEnvironment 556 * @see com.sun.star.uno.IMapping 557 * 558 * @deprecated As of UDK 3.2.0, this method is deprecated, without 559 * offering a replacement. 560 */ 561 public static IMapping getMapping(IEnvironment from, IEnvironment to) 562 throws java.lang.Exception 563 { 564 IBridge bridge; 565 try { 566 bridge = getBridge(from, to, null); 567 } 568 catch (ClassNotFoundException e) { 569 bridge = new BridgeTurner(getBridge(to, from, null)); 570 } 571 return new MappingWrapper(bridge); 572 } 573 574 /** 575 * Gets a mapping from environment <code>from</code> to environment 576 * <code>to</code>. 577 * 578 * <p>The used environments are retrieved through 579 * <code>getEnvironment</code>.</p> 580 * 581 * @param from the name of the source environment 582 * @param to the name of the target environment 583 * @return the requested mapping 584 * @see #getEnvironment 585 * @see #getMapping 586 * @see com.sun.star.uno.IMapping 587 * 588 * @deprecated As of UDK 3.2.0, this method is deprecated, without 589 * offering a replacement. 590 */ 591 public static IMapping getMappingByName(String from, String to) 592 throws java.lang.Exception 593 { 594 return getMapping(getEnvironment(from, null), getEnvironment(to, null)); 595 } 596 597 /** 598 * Resets this <code>UnoRuntime</code> to its initial state. 599 * 600 * <p>Releases all references to bridges and environments.</p> 601 * 602 * @deprecated As of UDK 3.2.0, this method is deprecated, without 603 * offering a replacement. 604 */ 605 static public boolean reset() { 606 synchronized (bridges) { 607 for (Iterator i = bridges.values().iterator(); i.hasNext();) { 608 IBridge b = (IBridge) WeakMap.getValue(i.next()); 609 if (b != null) { 610 // The following call to dispose was originally made to 611 // com.sun.star.lib.sandbox.Disposable.dispose, which cannot 612 // throw an InterruptedException or IOException: 613 try { 614 b.dispose(); 615 } catch (InterruptedException e) { 616 Thread.currentThread().interrupted(); 617 throw new RuntimeException( 618 "Unexpected exception in UnoRuntime.reset: " + e); 619 } catch (IOException e) { 620 throw new RuntimeException( 621 "Unexpected exception in UnoRuntime.reset: " + e); 622 } 623 } 624 } 625 bridges.clear(); 626 } 627 environments.clear(); 628 return bridges.isEmpty() && environments.isEmpty(); 629 } 630 631 /** 632 * @deprecated As of UDK 3.2.0, do not use this internal field. 633 */ 634 static public final boolean DEBUG = false; 635 636 private static final class BridgeTurner implements IBridge { 637 public BridgeTurner(IBridge bridge) { 638 this.bridge = bridge; 639 } 640 641 public Object mapInterfaceTo(Object object, Type type) { 642 return bridge.mapInterfaceFrom(object, type); 643 } 644 645 public Object mapInterfaceFrom(Object object, Type type) { 646 return bridge.mapInterfaceTo(object, type); 647 } 648 649 public IEnvironment getSourceEnvironment() { 650 return bridge.getTargetEnvironment(); 651 } 652 653 public IEnvironment getTargetEnvironment() { 654 return bridge.getSourceEnvironment(); 655 } 656 657 public void acquire() { 658 bridge.acquire(); 659 } 660 661 public void release() { 662 bridge.release(); 663 } 664 665 public void dispose() throws InterruptedException, IOException { 666 bridge.dispose(); 667 } 668 669 private final IBridge bridge; 670 } 671 672 private static final class MappingWrapper implements IMapping { 673 public MappingWrapper(IBridge bridge) { 674 this.bridge = bridge; 675 } 676 677 public Object mapInterface(Object object, Type type) { 678 return bridge.mapInterfaceTo(object, type); 679 } 680 681 private final IBridge bridge; 682 } 683 684 private static final String uniqueKeyHostPrefix 685 = Integer.toString(new Object().hashCode(), 16) + ":"; 686 private static final Object uniqueKeyLock = new Object(); 687 private static long uniqueKeyTime = System.currentTimeMillis(); 688 private static long uniqueKeyCount = Long.MIN_VALUE; 689 690 private static final String oidSuffix = ";java[];" + getUniqueKey(); 691 692 private static final ThreadLocal currentContext = new ThreadLocal(); 693 694 private static final WeakMap environments = new WeakMap(); 695 private static final WeakMap bridges = new WeakMap(); 696 } 697