ObjectCreator.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. /* ObjectCreator.java --
  2. Copyright (C) 2005 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package gnu.CORBA;
  32. import gnu.CORBA.CDR.UnknownExceptionCtxHandler;
  33. import gnu.CORBA.CDR.BufferredCdrInput;
  34. import gnu.CORBA.CDR.BufferedCdrOutput;
  35. import gnu.CORBA.CDR.AbstractCdrInput;
  36. import gnu.CORBA.GIOP.ServiceContext;
  37. import gnu.CORBA.typecodes.RecordTypeCode;
  38. import gnu.classpath.VMStackWalker;
  39. import org.omg.CORBA.Any;
  40. import org.omg.CORBA.CompletionStatus;
  41. import org.omg.CORBA.CompletionStatusHelper;
  42. import org.omg.CORBA.MARSHAL;
  43. import org.omg.CORBA.SystemException;
  44. import org.omg.CORBA.TCKind;
  45. import org.omg.CORBA.UNKNOWN;
  46. import org.omg.CORBA.UserException;
  47. import org.omg.CORBA.portable.IDLEntity;
  48. import org.omg.CORBA.portable.InputStream;
  49. import org.omg.CORBA.portable.OutputStream;
  50. import org.omg.CORBA.portable.ValueBase;
  51. import java.lang.reflect.Method;
  52. import java.util.Map;
  53. import java.util.WeakHashMap;
  54. import javax.rmi.CORBA.Util;
  55. /**
  56. * Creates java objects from the agreed IDL names for the simple case when the
  57. * CORBA object is directly mapped into the locally defined java class.
  58. *
  59. * @author Audrius Meskauskas (AudriusA@Bioinformatics.org)
  60. */
  61. public class ObjectCreator
  62. {
  63. /**
  64. * The standard OMG prefix.
  65. */
  66. public static final String OMG_PREFIX = "omg.org/";
  67. /**
  68. * The standard java prefix.
  69. */
  70. public static final String JAVA_PREFIX = "org.omg.";
  71. /**
  72. * The prefix for classes that are placed instide the gnu.CORBA namespace.
  73. */
  74. public static final String CLASSPATH_PREFIX = "gnu.CORBA.";
  75. /**
  76. * Maps classes to they IDL or RMI names. Computing RMI name is an expensive
  77. * operations, so frequently used RMI keys are reused. The map must be weak to
  78. * ensure that the class can be unloaded, when applicable.
  79. */
  80. public static Map m_names = new WeakHashMap();
  81. /**
  82. * Maps IDL strings into known classes. The map must be weak to ensure that
  83. * the class can be unloaded, when applicable.
  84. */
  85. public static Map m_classes = new WeakHashMap();
  86. /**
  87. * Maps IDL types to they helpers.
  88. */
  89. public static Map m_helpers = new WeakHashMap();
  90. /**
  91. * Try to instantiate an object with the given IDL name. The object must be
  92. * mapped to the local java class. The omg.org domain must be mapped into the
  93. * object in either org/omg or gnu/CORBA namespace.
  94. *
  95. * @param idl name
  96. * @return instantiated object instance or null if no such available.
  97. */
  98. public static java.lang.Object createObject(String idl, String suffix)
  99. {
  100. synchronized (m_classes)
  101. {
  102. Class known = (Class) (suffix == null ? m_classes.get(idl)
  103. : m_classes.get(idl + 0xff + suffix));
  104. Object object;
  105. if (known != null)
  106. {
  107. try
  108. {
  109. return known.newInstance();
  110. }
  111. catch (Exception ex)
  112. {
  113. RuntimeException rex = new RuntimeException(idl + " suffix "
  114. + suffix, ex);
  115. throw rex;
  116. }
  117. }
  118. else
  119. {
  120. if (suffix == null)
  121. suffix = "";
  122. try
  123. {
  124. known = forName(toClassName(JAVA_PREFIX, idl) + suffix);
  125. object = known.newInstance();
  126. }
  127. catch (Exception ex)
  128. {
  129. try
  130. {
  131. known = forName(toClassName(CLASSPATH_PREFIX, idl)
  132. + suffix);
  133. object = known.newInstance();
  134. }
  135. catch (Exception exex)
  136. {
  137. return null;
  138. }
  139. }
  140. m_classes.put(idl + 0xff + suffix, known);
  141. return object;
  142. }
  143. }
  144. }
  145. /**
  146. * Read the system exception from the given stream.
  147. *
  148. * @param input the CDR stream to read from.
  149. * @param contexts the service contexts in request/reply header/
  150. *
  151. * @return the exception that has been stored in the stream (IDL name, minor
  152. * code and completion status).
  153. */
  154. public static SystemException readSystemException(InputStream input,
  155. ServiceContext[] contexts)
  156. {
  157. SystemException exception;
  158. String idl = input.read_string();
  159. int minor = input.read_ulong();
  160. CompletionStatus completed = CompletionStatusHelper.read(input);
  161. try
  162. {
  163. exception = (SystemException) createObject(idl, null);
  164. exception.minor = minor;
  165. exception.completed = completed;
  166. }
  167. catch (Exception ex)
  168. {
  169. UNKNOWN u = new UNKNOWN("Unsupported system exception " + idl, minor,
  170. completed);
  171. u.initCause(ex);
  172. throw u;
  173. }
  174. try
  175. {
  176. // If UnknownExceptionInfo is present in the contexts, read it and
  177. // set as a cause of this exception.
  178. ServiceContext uEx = ServiceContext.find(
  179. ServiceContext.UnknownExceptionInfo, contexts);
  180. if (uEx != null)
  181. {
  182. BufferredCdrInput in = new BufferredCdrInput(uEx.context_data);
  183. in.setOrb(in.orb());
  184. if (input instanceof AbstractCdrInput)
  185. {
  186. ((AbstractCdrInput) input).cloneSettings(in);
  187. }
  188. Throwable t = UnknownExceptionCtxHandler.read(in, contexts);
  189. exception.initCause(t);
  190. }
  191. }
  192. catch (Exception ex)
  193. {
  194. // Unsupported context format. Do not terminate as the user program may
  195. // not need it.
  196. }
  197. return exception;
  198. }
  199. /**
  200. * Reads the user exception, having the given Id, from the input stream. The
  201. * id is expected to be in the form like
  202. * 'IDL:test/org/omg/CORBA/ORB/communication/ourUserException:1.0'
  203. *
  204. * @param idl the exception idl name.
  205. * @param input the stream to read from.
  206. *
  207. * @return the loaded exception.
  208. * @return null if the helper class cannot be found.
  209. */
  210. public static UserException readUserException(String idl, InputStream input)
  211. {
  212. try
  213. {
  214. Class helperClass = findHelper(idl);
  215. Method read = helperClass.getMethod("read",
  216. new Class[] { org.omg.CORBA.portable.InputStream.class });
  217. return (UserException) read.invoke(null, new Object[] { input });
  218. }
  219. catch (MARSHAL mex)
  220. {
  221. // This one is ok to throw
  222. throw mex;
  223. }
  224. catch (Exception ex)
  225. {
  226. ex.printStackTrace();
  227. return null;
  228. }
  229. }
  230. /**
  231. * Gets the helper class name from the string like
  232. * 'IDL:test/org/omg/CORBA/ORB/communication/ourUserException:1.0'
  233. *
  234. * @param IDL the idl name.
  235. */
  236. public static String toHelperName(String IDL)
  237. {
  238. String s = IDL;
  239. int a = s.indexOf(':') + 1;
  240. int b = s.lastIndexOf(':');
  241. s = IDL.substring(a, b);
  242. if (s.startsWith(OMG_PREFIX))
  243. s = JAVA_PREFIX + s.substring(OMG_PREFIX.length());
  244. return s.replace('/', '.') + "Helper";
  245. }
  246. /**
  247. * Writes the system exception data to CDR output stream.
  248. *
  249. * @param output a stream to write data to.
  250. * @param ex an exception to write.
  251. */
  252. public static void writeSystemException(OutputStream output,
  253. SystemException ex)
  254. {
  255. String exIDL = getRepositoryId(ex.getClass());
  256. output.write_string(exIDL);
  257. output.write_ulong(ex.minor);
  258. CompletionStatusHelper.write(output, ex.completed);
  259. }
  260. /**
  261. * Converts the given IDL name to class name.
  262. *
  263. * @param IDL the idl name.
  264. *
  265. */
  266. protected static String toClassName(String prefix, String IDL)
  267. {
  268. String s = IDL;
  269. int a = s.indexOf(':') + 1;
  270. int b = s.lastIndexOf(':');
  271. s = IDL.substring(a, b);
  272. if (s.startsWith(OMG_PREFIX))
  273. s = prefix + s.substring(OMG_PREFIX.length());
  274. return s.replace('/', '.');
  275. }
  276. /**
  277. * Converts the given IDL name to class name and tries to load the matching
  278. * class. The OMG prefix (omg.org) is replaced by the java prefix org.omg. No
  279. * other prefixes are added.
  280. *
  281. * @param IDL the idl name.
  282. *
  283. * @return the matching class or null if no such is available.
  284. */
  285. public static Class Idl2class(String IDL)
  286. {
  287. synchronized (m_classes)
  288. {
  289. Class c = (Class) m_classes.get(IDL);
  290. if (c != null)
  291. return c;
  292. else
  293. {
  294. String s = IDL;
  295. int a = s.indexOf(':') + 1;
  296. int b = s.lastIndexOf(':');
  297. s = IDL.substring(a, b);
  298. if (s.startsWith(OMG_PREFIX))
  299. s = JAVA_PREFIX + s.substring(OMG_PREFIX.length());
  300. String cn = s.replace('/', '.');
  301. try
  302. {
  303. c = forName(cn);
  304. m_classes.put(IDL, c);
  305. return c;
  306. }
  307. catch (ClassNotFoundException ex)
  308. {
  309. return null;
  310. }
  311. }
  312. }
  313. }
  314. /**
  315. * Converts the given IDL name to class name, tries to load the matching class
  316. * and create an object instance with parameterless constructor. The OMG
  317. * prefix (omg.org) is replaced by the java prefix org.omg. No other prefixes
  318. * are added.
  319. *
  320. * @param IDL the idl name.
  321. *
  322. * @return instantiated object instance or null if such attempt was not
  323. * successful.
  324. */
  325. public static java.lang.Object Idl2Object(String IDL)
  326. {
  327. Class cx = Idl2class(IDL);
  328. try
  329. {
  330. if (cx != null)
  331. return cx.newInstance();
  332. else
  333. return null;
  334. }
  335. catch (Exception ex)
  336. {
  337. return null;
  338. }
  339. }
  340. /**
  341. * Convert the class name to IDL or RMI name (repository id). If the class
  342. * inherits from IDLEntity, ValueBase or SystemException, returns repository
  343. * Id in the IDL:(..) form. If it does not, returns repository Id in the
  344. * RMI:(..) form.
  345. *
  346. * @param cx the class for that the name must be computed.
  347. *
  348. * @return the idl or rmi name.
  349. */
  350. public static synchronized String getRepositoryId(Class cx)
  351. {
  352. String name = (String) m_names.get(cx);
  353. if (name != null)
  354. return name;
  355. String cn = cx.getName();
  356. if (!(IDLEntity.class.isAssignableFrom(cx)
  357. || ValueBase.class.isAssignableFrom(cx) || SystemException.class.isAssignableFrom(cx)))
  358. {
  359. // Not an IDL entity.
  360. name = Util.createValueHandler().getRMIRepositoryID(cx);
  361. }
  362. else
  363. {
  364. if (cn.startsWith(JAVA_PREFIX))
  365. cn = OMG_PREFIX
  366. + cn.substring(JAVA_PREFIX.length()).replace('.', '/');
  367. else if (cn.startsWith(CLASSPATH_PREFIX))
  368. cn = OMG_PREFIX
  369. + cn.substring(CLASSPATH_PREFIX.length()).replace('.', '/');
  370. name = "IDL:" + cn + ":1.0";
  371. }
  372. m_names.put(cx, name);
  373. return name;
  374. }
  375. /**
  376. * Insert the passed parameter into the given Any, assuming that the helper
  377. * class is available. The helper class must have the "Helper" suffix and be
  378. * in the same package as the class of the object being inserted.
  379. *
  380. * @param into the target to insert.
  381. *
  382. * @param object the object to insert. It can be any object as far as the
  383. * corresponding helper is provided.
  384. *
  385. * @return true on success, false otherwise.
  386. */
  387. public static boolean insertWithHelper(Any into, Object object)
  388. {
  389. try
  390. {
  391. String helperClassName = object.getClass().getName() + "Helper";
  392. Class helperClass = forName(helperClassName);
  393. Method insert = helperClass.getMethod("insert", new Class[] {
  394. Any.class, object.getClass() });
  395. insert.invoke(null, new Object[] { into, object });
  396. return true;
  397. }
  398. catch (Exception exc)
  399. {
  400. // Failed due some reason.
  401. return false;
  402. }
  403. }
  404. /**
  405. * Insert the system exception into the given Any.
  406. */
  407. public static boolean insertSysException(Any into, SystemException exception)
  408. {
  409. try
  410. {
  411. BufferedCdrOutput output = new BufferedCdrOutput();
  412. String m_exception_id = getRepositoryId(exception.getClass());
  413. output.write_string(m_exception_id);
  414. output.write_ulong(exception.minor);
  415. CompletionStatusHelper.write(output, exception.completed);
  416. String name = getDefaultName(m_exception_id);
  417. GeneralHolder h = new GeneralHolder(output);
  418. into.insert_Streamable(h);
  419. RecordTypeCode r = new RecordTypeCode(TCKind.tk_except);
  420. r.setId(m_exception_id);
  421. r.setName(name);
  422. into.type(r);
  423. return true;
  424. }
  425. catch (Exception ex)
  426. {
  427. ex.printStackTrace();
  428. return false;
  429. }
  430. }
  431. /**
  432. * Get the type name from the IDL string.
  433. */
  434. public static String getDefaultName(String idl)
  435. {
  436. int f1 = idl.lastIndexOf("/");
  437. int p1 = (f1 < 0) ? 0 : f1;
  438. int p2 = idl.indexOf(":", p1);
  439. if (p2 < 0)
  440. p2 = idl.length();
  441. String name = idl.substring(f1 + 1, p2);
  442. return name;
  443. }
  444. /**
  445. * Insert this exception into the given Any. On failure, insert the UNKNOWN
  446. * exception.
  447. */
  448. public static void insertException(Any into, Throwable exception)
  449. {
  450. boolean ok = false;
  451. if (exception instanceof SystemException)
  452. ok = insertSysException(into, (SystemException) exception);
  453. else if (exception instanceof UserException)
  454. ok = insertWithHelper(into, exception);
  455. if (!ok)
  456. ok = insertSysException(into, new UNKNOWN());
  457. if (!ok)
  458. throw new InternalError("Exception wrapping broken");
  459. }
  460. /**
  461. * Find helper for the class with the given name.
  462. */
  463. public static Class findHelper(String idl)
  464. {
  465. synchronized (m_helpers)
  466. {
  467. Class c = (Class) m_helpers.get(idl);
  468. if (c != null)
  469. return c;
  470. try
  471. {
  472. String helper = toHelperName(idl);
  473. c = forName(helper);
  474. m_helpers.put(idl, c);
  475. return c;
  476. }
  477. catch (Exception ex)
  478. {
  479. return null;
  480. }
  481. }
  482. }
  483. /**
  484. * Load the class with the given name. This method tries to use the context
  485. * class loader first. If this fails, it searches for the suitable class
  486. * loader in the caller stack trace. This method is a central point where all
  487. * requests to find a class by name are delegated.
  488. */
  489. public static Class forName(String className) throws ClassNotFoundException
  490. {
  491. try
  492. {
  493. return Class.forName(className, true,
  494. Thread.currentThread().getContextClassLoader());
  495. }
  496. catch (ClassNotFoundException nex)
  497. {
  498. /**
  499. * Returns the first user defined class loader on the call stack, or
  500. * null when no non-null class loader was found.
  501. */
  502. Class[] ctx = VMStackWalker.getClassContext();
  503. for (int i = 0; i < ctx.length; i++)
  504. {
  505. // Since we live in a class loaded by the bootstrap
  506. // class loader, getClassLoader is safe to call without
  507. // needing to be wrapped in a privileged action.
  508. ClassLoader cl = ctx[i].getClassLoader();
  509. try
  510. {
  511. if (cl != null)
  512. return Class.forName(className, true, cl);
  513. }
  514. catch (ClassNotFoundException nex2)
  515. {
  516. // Try next.
  517. }
  518. }
  519. }
  520. throw new ClassNotFoundException(className);
  521. }
  522. }