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