1. /*
  2. * @(#)Beans.java 1.54 00/02/02
  3. *
  4. * Copyright 1996-2000 Sun Microsystems, Inc. All Rights Reserved.
  5. *
  6. * This software is the proprietary information of Sun Microsystems, Inc.
  7. * Use is subject to license terms.
  8. *
  9. */
  10. package java.beans;
  11. import java.applet.*;
  12. import java.awt.*;
  13. import java.beans.AppletInitializer;
  14. import java.beans.beancontext.BeanContext;
  15. import java.io.*;
  16. import java.lang.reflect.Constructor;
  17. import java.net.URL;
  18. import java.lang.reflect.Array;
  19. /**
  20. * This class provides some general purpose beans control methods.
  21. */
  22. public class Beans {
  23. /**
  24. * <p>
  25. * Instantiate a JavaBean.
  26. * </p>
  27. *
  28. * @param classLoader the class-loader from which we should create
  29. * the bean. If this is null, then the system
  30. * class-loader is used.
  31. * @param beanName the name of the bean within the class-loader.
  32. * For example "sun.beanbox.foobah"
  33. *
  34. * @exception java.lang.ClassNotFoundException if the class of a serialized
  35. * object could not be found.
  36. * @exception java.io.IOException if an I/O error occurs.
  37. */
  38. public static Object instantiate(ClassLoader cls, String beanName) throws java.io.IOException, ClassNotFoundException {
  39. return Beans.instantiate(cls, beanName, null, null);
  40. }
  41. /**
  42. * <p>
  43. * Instantiate a JavaBean.
  44. * </p>
  45. *
  46. * @param classLoader the class-loader from which we should create
  47. * the bean. If this is null, then the system
  48. * class-loader is used.
  49. * @param beanName the name of the bean within the class-loader.
  50. * For example "sun.beanbox.foobah"
  51. * @param beanContext The BeanContext in which to nest the new bean
  52. *
  53. * @exception java.lang.ClassNotFoundException if the class of a serialized
  54. * object could not be found.
  55. * @exception java.io.IOException if an I/O error occurs.
  56. */
  57. public static Object instantiate(ClassLoader cls, String beanName, BeanContext beanContext) throws java.io.IOException, ClassNotFoundException {
  58. return Beans.instantiate(cls, beanName, beanContext, null);
  59. }
  60. /**
  61. * Instantiate a bean.
  62. * <p>
  63. * The bean is created based on a name relative to a class-loader.
  64. * This name should be a dot-separated name such as "a.b.c".
  65. * <p>
  66. * In Beans 1.0 the given name can indicate either a serialized object
  67. * or a class. Other mechanisms may be added in the future. In
  68. * beans 1.0 we first try to treat the beanName as a serialized object
  69. * name then as a class name.
  70. * <p>
  71. * When using the beanName as a serialized object name we convert the
  72. * given beanName to a resource pathname and add a trailing ".ser" suffix.
  73. * We then try to load a serialized object from that resource.
  74. * <p>
  75. * For example, given a beanName of "x.y", Beans.instantiate would first
  76. * try to read a serialized object from the resource "x/y.ser" and if
  77. * that failed it would try to load the class "x.y" and create an
  78. * instance of that class.
  79. * <p>
  80. * If the bean is a subtype of java.applet.Applet, then it is given
  81. * some special initialization. First, it is supplied with a default
  82. * AppletStub and AppletContext. Second, if it was instantiated from
  83. * a classname the applet's "init" method is called. (If the bean was
  84. * deserialized this step is skipped.)
  85. * <p>
  86. * Note that for beans which are applets, it is the caller's responsiblity
  87. * to call "start" on the applet. For correct behaviour, this should be done
  88. * after the applet has been added into a visible AWT container.
  89. * <p>
  90. * Note that applets created via beans.instantiate run in a slightly
  91. * different environment than applets running inside browsers. In
  92. * particular, bean applets have no access to "parameters", so they may
  93. * wish to provide property get/set methods to set parameter values. We
  94. * advise bean-applet developers to test their bean-applets against both
  95. * the SDK appletviewer (for a reference browser environment) and the
  96. * BDK BeanBox (for a reference bean container).
  97. *
  98. * @param classLoader the class-loader from which we should create
  99. * the bean. If this is null, then the system
  100. * class-loader is used.
  101. * @param beanName the name of the bean within the class-loader.
  102. * For example "sun.beanbox.foobah"
  103. * @param beanContext The BeanContext in which to nest the new bean
  104. * @param initializer The AppletInitializer for the new bean
  105. *
  106. * @exception java.lang.ClassNotFoundException if the class of a serialized
  107. * object could not be found.
  108. * @exception java.io.IOException if an I/O error occurs.
  109. */
  110. public static Object instantiate(ClassLoader cls, String beanName, BeanContext beanContext, AppletInitializer initializer)
  111. throws java.io.IOException, ClassNotFoundException {
  112. java.io.InputStream ins;
  113. java.io.ObjectInputStream oins = null;
  114. Object result = null;
  115. boolean serialized = false;
  116. java.io.IOException serex = null;
  117. // If the given classloader is null, we check if an
  118. // system classloader is available and (if so)
  119. // use that instead.
  120. // Note that calls on the system class loader will
  121. // look in the bootstrap class loader first.
  122. if (cls == null) {
  123. try {
  124. cls = ClassLoader.getSystemClassLoader();
  125. } catch (SecurityException ex) {
  126. // We're not allowed to access the system class loader.
  127. // Drop through.
  128. }
  129. }
  130. // Try to find a serialized object with this name
  131. final String serName = beanName.replace('.','/').concat(".ser");
  132. final ClassLoader loader = cls;
  133. ins = (InputStream)java.security.AccessController.doPrivileged
  134. (new java.security.PrivilegedAction() {
  135. public Object run() {
  136. if (loader == null)
  137. return ClassLoader.getSystemResourceAsStream(serName);
  138. else
  139. return loader.getResourceAsStream(serName);
  140. }
  141. });
  142. if (ins != null) {
  143. try {
  144. if (cls == null) {
  145. oins = new ObjectInputStream(ins);
  146. } else {
  147. oins = new ObjectInputStreamWithLoader(ins, cls);
  148. }
  149. result = oins.readObject();
  150. serialized = true;
  151. oins.close();
  152. } catch (java.io.IOException ex) {
  153. ins.close();
  154. // Drop through and try opening the class. But remember
  155. // the exception in case we can't find the class either.
  156. serex = ex;
  157. } catch (ClassNotFoundException ex) {
  158. ins.close();
  159. throw ex;
  160. }
  161. }
  162. if (result == null) {
  163. // No serialized object, try just instantiating the class
  164. Class cl;
  165. try {
  166. if (cls == null) {
  167. cl = Class.forName(beanName);
  168. } else {
  169. cl = cls.loadClass(beanName);
  170. }
  171. } catch (ClassNotFoundException ex) {
  172. // There is no appropriate class. If we earlier tried to
  173. // deserialize an object and got an IO exception, throw that,
  174. // otherwise rethrow the ClassNotFoundException.
  175. if (serex != null) {
  176. throw serex;
  177. }
  178. throw ex;
  179. }
  180. /*
  181. * Try to instantiate the class.
  182. */
  183. try {
  184. result = cl.newInstance();
  185. } catch (Exception ex) {
  186. // We have to remap the exception to one in our signature.
  187. // But we pass extra information in the detail message.
  188. throw new ClassNotFoundException("" + cl + " : " + ex);
  189. }
  190. }
  191. if (result != null) {
  192. // Ok, if the result is an applet initialize it.
  193. AppletStub stub = null;
  194. if (result instanceof Applet) {
  195. Applet applet = (Applet) result;
  196. boolean needDummies = initializer == null;
  197. if (needDummies) {
  198. // Figure our the codebase and docbase URLs. We do this
  199. // by locating the URL for a known resource, and then
  200. // massaging the URL.
  201. // First find the "resource name" corresponding to the bean
  202. // itself. So a serialzied bean "a.b.c" would imply a
  203. // resource name of "a/b/c.ser" and a classname of "x.y"
  204. // would imply a resource name of "x/y.class".
  205. final String resourceName;
  206. if (serialized) {
  207. // Serialized bean
  208. resourceName = beanName.replace('.','/').concat(".ser");
  209. } else {
  210. // Regular class
  211. resourceName = beanName.replace('.','/').concat(".class");
  212. }
  213. URL objectUrl = null;
  214. URL codeBase = null;
  215. URL docBase = null;
  216. // Now get the URL correponding to the resource name.
  217. final ClassLoader cloader = cls;
  218. objectUrl = (URL)
  219. java.security.AccessController.doPrivileged
  220. (new java.security.PrivilegedAction() {
  221. public Object run() {
  222. if (cloader == null)
  223. return ClassLoader.getSystemResource
  224. (resourceName);
  225. else
  226. return cloader.getResource(resourceName);
  227. }
  228. });
  229. // If we found a URL, we try to locate the docbase by taking
  230. // of the final path name component, and the code base by taking
  231. // of the complete resourceName.
  232. // So if we had a resourceName of "a/b/c.class" and we got an
  233. // objectURL of "file://bert/classes/a/b/c.class" then we would
  234. // want to set the codebase to "file://bert/classes/" and the
  235. // docbase to "file://bert/classes/a/b/"
  236. if (objectUrl != null) {
  237. String s = objectUrl.toExternalForm();
  238. if (s.endsWith(resourceName)) {
  239. int ix = s.length() - resourceName.length();
  240. codeBase = new URL(s.substring(0,ix));
  241. docBase = codeBase;
  242. ix = s.lastIndexOf('/');
  243. if (ix >= 0) {
  244. docBase = new URL(s.substring(0,ix+1));
  245. }
  246. }
  247. }
  248. // Setup a default context and stub.
  249. BeansAppletContext context = new BeansAppletContext(applet);
  250. stub = (AppletStub)new BeansAppletStub(applet, context, codeBase, docBase);
  251. applet.setStub(stub);
  252. } else {
  253. initializer.initialize(applet, beanContext);
  254. }
  255. // now, if there is a BeanContext, add the bean, if applicable.
  256. if (beanContext != null) {
  257. beanContext.add(result);
  258. }
  259. // If it was deserialized then it was already init-ed.
  260. // Otherwise we need to initialize it.
  261. if (!serialized) {
  262. // We need to set a reasonable initial size, as many
  263. // applets are unhappy if they are started without
  264. // having been explicitly sized.
  265. applet.setSize(100,100);
  266. applet.init();
  267. }
  268. if (needDummies) {
  269. ((BeansAppletStub)stub).active = true;
  270. } else initializer.activate(applet);
  271. } else if (beanContext != null) beanContext.add(result);
  272. }
  273. return result;
  274. }
  275. /**
  276. * From a given bean, obtain an object representing a specified
  277. * type view of that source object.
  278. * <p>
  279. * The result may be the same object or a different object. If
  280. * the requested target view isn't available then the given
  281. * bean is returned.
  282. * <p>
  283. * This method is provided in Beans 1.0 as a hook to allow the
  284. * addition of more flexible bean behaviour in the future.
  285. *
  286. * @param obj Object from which we want to obtain a view.
  287. * @param targetType The type of view we'd like to get.
  288. *
  289. */
  290. public static Object getInstanceOf(Object bean, Class targetType) {
  291. return bean;
  292. }
  293. /**
  294. * Check if a bean can be viewed as a given target type.
  295. * The result will be true if the Beans.getInstanceof method
  296. * can be used on the given bean to obtain an object that
  297. * represents the specified targetType type view.
  298. *
  299. * @param bean Bean from which we want to obtain a view.
  300. * @param targetType The type of view we'd like to get.
  301. * @return "true" if the given bean supports the given targetType.
  302. *
  303. */
  304. public static boolean isInstanceOf(Object bean, Class targetType) {
  305. return Introspector.isSubclass(bean.getClass(), targetType);
  306. }
  307. /**
  308. * Test if we are in design-mode.
  309. *
  310. * @return True if we are running in an application construction
  311. * environment.
  312. *
  313. * @see java.beans.DesignMode
  314. */
  315. public static boolean isDesignTime() {
  316. return designTime;
  317. }
  318. /**
  319. * Determines whether beans can assume a GUI is available.
  320. *
  321. * @return True if we are running in an environment where beans
  322. * can assume that an interactive GUI is available, so they
  323. * can pop up dialog boxes, etc. This will normally return
  324. * true in a windowing environment, and will normally return
  325. * false in a server environment or if an application is
  326. * running as part of a batch job.
  327. *
  328. * @see java.beans.Visibility
  329. *
  330. */
  331. public static boolean isGuiAvailable() {
  332. return guiAvailable;
  333. }
  334. /**
  335. * Used to indicate whether of not we are running in an application
  336. * builder environment.
  337. *
  338. * <p>Note that this method is security checked
  339. * and is not available to (for example) untrusted applets.
  340. * More specifically, if there is a security manager,
  341. * its <code>checkPropertiesAccess</code>
  342. * method is called. This could result in a SecurityException.
  343. *
  344. * @param isDesignTime True if we're in an application builder tool.
  345. * @exception SecurityException if a security manager exists and its
  346. * <code>checkPropertiesAccess</code> method doesn't allow setting
  347. * of system properties.
  348. * @see SecurityManager#checkPropertiesAccess
  349. */
  350. public static void setDesignTime(boolean isDesignTime)
  351. throws SecurityException {
  352. SecurityManager sm = System.getSecurityManager();
  353. if (sm != null) {
  354. sm.checkPropertiesAccess();
  355. }
  356. designTime = isDesignTime;
  357. }
  358. /**
  359. * Used to indicate whether of not we are running in an environment
  360. * where GUI interaction is available.
  361. *
  362. * <p>Note that this method is security checked
  363. * and is not available to (for example) untrusted applets.
  364. * More specifically, if there is a security manager,
  365. * its <code>checkPropertiesAccess</code>
  366. * method is called. This could result in a SecurityException.
  367. *
  368. * @param isGuiAvailable True if GUI interaction is available.
  369. * @exception SecurityException if a security manager exists and its
  370. * <code>checkPropertiesAccess</code> method doesn't allow setting
  371. * of system properties.
  372. * @see SecurityManager#checkPropertiesAccess
  373. */
  374. public static void setGuiAvailable(boolean isGuiAvailable)
  375. throws SecurityException {
  376. SecurityManager sm = System.getSecurityManager();
  377. if (sm != null) {
  378. sm.checkPropertiesAccess();
  379. }
  380. guiAvailable = isGuiAvailable;
  381. }
  382. private static boolean designTime;
  383. private static boolean guiAvailable = true;
  384. }
  385. /**
  386. * This subclass of ObjectInputStream delegates loading of classes to
  387. * an existing ClassLoader.
  388. */
  389. class ObjectInputStreamWithLoader extends ObjectInputStream
  390. {
  391. private ClassLoader loader;
  392. /**
  393. * Loader must be non-null;
  394. */
  395. public ObjectInputStreamWithLoader(InputStream in, ClassLoader loader)
  396. throws IOException, StreamCorruptedException {
  397. super(in);
  398. if (loader == null) {
  399. throw new IllegalArgumentException("Illegal null argument to ObjectInputStreamWithLoader");
  400. }
  401. this.loader = loader;
  402. }
  403. /**
  404. * Make a primitive array class
  405. */
  406. private Class primitiveType(char type) {
  407. switch (type) {
  408. case 'B': return byte.class;
  409. case 'C': return char.class;
  410. case 'D': return double.class;
  411. case 'F': return float.class;
  412. case 'I': return int.class;
  413. case 'J': return long.class;
  414. case 'S': return short.class;
  415. case 'Z': return boolean.class;
  416. default: return null;
  417. }
  418. }
  419. /**
  420. * Use the given ClassLoader rather than using the system class
  421. */
  422. protected Class resolveClass(ObjectStreamClass classDesc)
  423. throws IOException, ClassNotFoundException {
  424. String cname = classDesc.getName();
  425. if (cname.startsWith("[")) {
  426. // An array
  427. Class component; // component class
  428. int dcount; // dimension
  429. for (dcount=1; cname.charAt(dcount)=='['; dcount++) ;
  430. if (cname.charAt(dcount) == 'L') {
  431. component = loader.loadClass(cname.substring(dcount+1,
  432. cname.length()-1));
  433. } else {
  434. if (cname.length() != dcount+1) {
  435. throw new ClassNotFoundException(cname);// malformed
  436. }
  437. component = primitiveType(cname.charAt(dcount));
  438. }
  439. int dim[] = new int[dcount];
  440. for (int i=0; i<dcount; i++) {
  441. dim[i]=0;
  442. }
  443. return Array.newInstance(component, dim).getClass();
  444. } else {
  445. return loader.loadClass(cname);
  446. }
  447. }
  448. }
  449. /**
  450. * Package private support class. This provides a default AppletContext
  451. * for beans which are applets.
  452. */
  453. class BeansAppletContext implements AppletContext {
  454. Applet target;
  455. java.util.Hashtable imageCache = new java.util.Hashtable();
  456. BeansAppletContext(Applet target) {
  457. this.target = target;
  458. }
  459. public AudioClip getAudioClip(URL url) {
  460. // We don't currently support audio clips in the Beans.instantiate
  461. // applet context, unless by some luck there exists a URL content
  462. // class that can generate an AudioClip from the audio URL.
  463. try {
  464. return (AudioClip) url.getContent();
  465. } catch (Exception ex) {
  466. return null;
  467. }
  468. }
  469. public synchronized Image getImage(URL url) {
  470. Object o = imageCache.get(url);
  471. if (o != null) {
  472. return (Image)o;
  473. }
  474. try {
  475. o = url.getContent();
  476. if (o == null) {
  477. return null;
  478. }
  479. if (o instanceof Image) {
  480. imageCache.put(url, o);
  481. return (Image) o;
  482. }
  483. // Otherwise it must be an ImageProducer.
  484. Image img = target.createImage((java.awt.image.ImageProducer)o);
  485. imageCache.put(url, img);
  486. return img;
  487. } catch (Exception ex) {
  488. return null;
  489. }
  490. }
  491. public Applet getApplet(String name) {
  492. return null;
  493. }
  494. public java.util.Enumeration getApplets() {
  495. java.util.Vector applets = new java.util.Vector();
  496. applets.addElement(target);
  497. return applets.elements();
  498. }
  499. public void showDocument(URL url) {
  500. // We do nothing.
  501. }
  502. public void showDocument(URL url, String target) {
  503. // We do nothing.
  504. }
  505. public void showStatus(String status) {
  506. // We do nothing.
  507. }
  508. }
  509. /**
  510. * Package private support class. This provides an AppletStub
  511. * for beans which are applets.
  512. */
  513. class BeansAppletStub implements AppletStub {
  514. transient boolean active;
  515. transient Applet target;
  516. transient AppletContext context;
  517. transient URL codeBase;
  518. transient URL docBase;
  519. BeansAppletStub(Applet target,
  520. AppletContext context, URL codeBase,
  521. URL docBase) {
  522. this.target = target;
  523. this.context = context;
  524. this.codeBase = codeBase;
  525. this.docBase = docBase;
  526. }
  527. public boolean isActive() {
  528. return active;
  529. }
  530. public URL getDocumentBase() {
  531. // use the root directory of the applet's class-loader
  532. return docBase;
  533. }
  534. public URL getCodeBase() {
  535. // use the directory where we found the class or serialized object.
  536. return codeBase;
  537. }
  538. public String getParameter(String name) {
  539. return null;
  540. }
  541. public AppletContext getAppletContext() {
  542. return context;
  543. }
  544. public void appletResize(int width, int height) {
  545. // we do nothing.
  546. }
  547. }