/** Use the given ClassLoader rather than using the system class */
 protected Class resolveClass(ObjectStreamClass classDesc)
     throws IOException, ClassNotFoundException {
   String cname = classDesc.getName();
   if (cname.startsWith("[")) {
     // An array
     Class component; // component class
     int dcount; // dimension
     for (dcount = 1; cname.charAt(dcount) == '['; dcount++) ;
     if (cname.charAt(dcount) == 'L') {
       component = loader.loadClass(cname.substring(dcount + 1, cname.length() - 1));
     } else {
       if (cname.length() != dcount + 1) {
         throw new ClassNotFoundException(cname); // malformed
       }
       component = primitiveType(cname.charAt(dcount));
     }
     int dim[] = new int[dcount];
     for (int i = 0; i < dcount; i++) {
       dim[i] = 1;
     }
     return Array.newInstance(component, dim).getClass();
   } else {
     return loader.loadClass(cname);
   }
 }
Example #2
0
 boolean tryDir(String d) {
   ClassLoader L = getClass().getClassLoader();
   File p = new File(d, PACKAGE);
   // System.out.println("Try "+p);
   if (!p.exists() || !p.isDirectory()) return false;
   for (File f : p.listFiles()) {
     String s = f.getName();
     if (!s.endsWith(".class")) continue;
     String name = s.substring(0, s.length() - 6);
     try {
       Class<?> c = L.loadClass(PACKAGE + "." + name);
       if (!Quotation.class.isAssignableFrom(c)) continue;
       Q.put(name, (Quotation) c.newInstance());
       System.out.println("  " + name);
       // ClassNotFoundException InstantiationException IllegalAccessException
     } catch (Exception e) {
       continue;
     }
   }
   return Q.size() > 0;
 }
  /** Look on disk for an editor with the class name 'ocName'. */
  PluggableEditor loadEditorFromDisk(String ocName) {
    // if here, we need to look on disk for a pluggable editor class...
    log.finer("looking for ocName: " + ocName);
    try {
      Class c = myLoader.loadClass(ocName);
      Constructor constructor = c.getConstructor(new Class[0]);

      // XXX If the pluggable editor has an error in the constructor, under some
      // XXX circumstances it can fail so badly that this call never returns, and
      // XXX the thread hangs!  It doesn't even get to the exception handler below...
      // XXX but sometimes if the constructor fails everything works as expected.  Wierd.
      PluggableEditor editor = (PluggableEditor) constructor.newInstance(new Object[0]);

      editors.put(ocName, editor); // add the new editor to our list
      return editor;
    } catch (Exception e) // expected condition - just means no pluggable editor available
    {
      if (e
          instanceof
          InvocationTargetException) // rare exception - an error was encountered in the plugin's
                                     // constructor.
      {
        log.warning("unable to load special editor for: '" + ocName + "' " + e);
        if (JXConfig.debugLevel >= 1) {
          log.warning("Error loading plugin class: ");
          ((InvocationTargetException) e).getTargetException().printStackTrace();
        }
      }

      log.log(Level.FINEST, "'Expected' Error loading " + ocName, e);
      editors.put(ocName, NONE); // add a blank place holder - we can't load
      // an editor for this, and there's no point looking again. (change if want dynamic loading,
      // i.e. look *every* time)
    }
    return null; // only here if an error has occured.
  }
  /**
   * Instantiate a JavaBean.
   *
   * @param classLoader the class-loader from which we should create the bean. If this is null, then
   *     the system class-loader is used.
   * @param beanName the name of the bean within the class-loader. For example "sun.beanbox.foobah"
   * @exception java.lang.ClassNotFoundException if the class of a serialized object could not be
   *     found.
   * @exception java.io.IOException if an I/O error occurs.
   */
  public static Object instantiate(ClassLoader cls, String beanName)
      throws java.io.IOException, ClassNotFoundException {
    java.io.InputStream ins;
    java.io.ObjectInputStream oins = null;
    Object result = null;
    boolean serialized = false;
    java.io.IOException serex = null;
    // If the given classloader is null, we check if an
    // system classloader is available and (if so)
    // use that instead.
    // Note that calls on the system class loader will
    // look in the bootstrap class loader first.
    if (cls == null) {
      try {
        cls = ClassLoader.getSystemClassLoader();
      } catch (SecurityException ex) { // We're not allowed to access the system class loader.
        // Drop through.
      }
    }
    // Try to find a serialized object with this name
    final String serName = beanName.replace('.', '/').concat(".ser");
    final ClassLoader loader = cls;
    ins =
        (InputStream)
            java.security.AccessController.doPrivileged(
                new java.security.PrivilegedAction() {
                  public Object run() {
                    if (loader == null) return ClassLoader.getSystemResourceAsStream(serName);
                    else return loader.getResourceAsStream(serName);
                  }
                });
    if (ins != null) {
      try {
        if (cls == null) {
          oins = new ObjectInputStream(ins);
        } else {
          oins = new ObjectInputStreamWithLoader(ins, cls);
        }
        result = oins.readObject();
        serialized = true;
        oins.close();
      } catch (java.io.IOException ex) {
        ins.close();
        // Drop through and try opening the class.  But remember
        // the exception in case we can't find the class either.
        serex = ex;
      } catch (ClassNotFoundException ex) {
        ins.close();
        throw ex;
      }
    }
    if (result == null) {
      // No serialized object, try just instantiating the class
      Class cl;
      try {
        if (cls == null) {
          cl = Class.forName(beanName);
        } else {
          cl = cls.loadClass(beanName);
        }
      } catch (ClassNotFoundException ex) {
        // There is no appropriate class.  If we earlier tried to
        // deserialize an object and got an IO exception, throw that,
        // otherwise rethrow the ClassNotFoundException.
        if (serex != null) {
          throw serex;
        }
        throw ex;
      }
      /*
       * Try to instantiate the class.
       */

      try {
        result = cl.newInstance();
      } catch (Exception ex) {
        // We have to remap the exception to one in our signature.
        // But we pass extra information in the detail message.
        throw new ClassNotFoundException("" + cl + " : " + ex);
      }
    }
    if (result != null) { // Ok, if the result is an applet initialize it.
      AppletStub stub = null;

      if (result instanceof Applet) {
        Applet applet = (Applet) result;

        // Figure our the codebase and docbase URLs.  We do this
        // by locating the URL for a known resource, and then
        // massaging the URL.

        // First find the "resource name" corresponding to the bean
        // itself.  So a serialzied bean "a.b.c" would imply a
        // resource name of "a/b/c.ser" and a classname of "x.y"
        // would imply a resource name of "x/y.class".

        final String resourceName;

        if (serialized) {
          // Serialized bean
          resourceName = beanName.replace('.', '/').concat(".ser");
        } else {
          // Regular class
          resourceName = beanName.replace('.', '/').concat(".class");
        }

        URL objectUrl = null;
        URL codeBase = null;
        URL docBase = null;

        // Now get the URL correponding to the resource name.

        final ClassLoader cloader = cls;
        objectUrl =
            (URL)
                java.security.AccessController.doPrivileged(
                    new java.security.PrivilegedAction() {
                      public Object run() {
                        if (cloader == null) return ClassLoader.getSystemResource(resourceName);
                        else return cloader.getResource(resourceName);
                      }
                    });

        // If we found a URL, we try to locate the docbase by taking
        // of the final path name component, and the code base by taking
        // of the complete resourceName.
        // So if we had a resourceName of "a/b/c.class" and we got an
        // objectURL of "file://bert/classes/a/b/c.class" then we would
        // want to set the codebase to "file://bert/classes/" and the
        // docbase to "file://bert/classes/a/b/"

        if (objectUrl != null) {
          String s = objectUrl.toExternalForm();

          if (s.endsWith(resourceName)) {
            int ix = s.length() - resourceName.length();
            codeBase = new URL(s.substring(0, ix));
            docBase = codeBase;

            ix = s.lastIndexOf('/');

            if (ix >= 0) {
              docBase = new URL(s.substring(0, ix + 1));
            }
          }
        }

        // Setup a default context and stub.
        BeansAppletContext context = new BeansAppletContext(applet);

        stub = (AppletStub) new BeansAppletStub(applet, context, codeBase, docBase);
        applet.setStub(stub);

        // If it was deserialized then it was already init-ed.
        // Otherwise we need to initialize it.

        if (!serialized) {
          // We need to set a reasonable initial size, as many
          // applets are unhappy if they are started without
          // having been explicitly sized.
          applet.setSize(100, 100);
          applet.init();
        }
        ((BeansAppletStub) stub).active = true;
      }
    }
    return result;
  }
Example #5
0
  public QSAdminGUI(QSAdminMain qsadminMain, JFrame parentFrame) {
    this.parentFrame = parentFrame;
    Container cp = this;
    qsadminMain.setGUI(this);
    cp.setLayout(new BorderLayout(5, 5));
    headerPanel = new HeaderPanel(qsadminMain, parentFrame);
    mainCommandPanel = new MainCommandPanel(qsadminMain);
    cmdConsole = new CmdConsole(qsadminMain);
    propertiePanel = new PropertiePanel(qsadminMain);

    if (headerPanel == null
        || mainCommandPanel == null
        || cmdConsole == null
        || propertiePanel == null) {
      throw new RuntimeException("Loading of one of gui component failed.");
    }

    headerPanel.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
    cp.add(headerPanel, BorderLayout.NORTH);
    JScrollPane propertieScrollPane = new JScrollPane(propertiePanel);
    // JScrollPane commandScrollPane = new JScrollPane(mainCommandPanel);
    JSplitPane splitPane =
        new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, mainCommandPanel, cmdConsole);
    splitPane.setOneTouchExpandable(false);
    splitPane.setDividerLocation(250);
    // splitPane.setDividerLocation(0.70);

    tabbedPane = new JTabbedPane(JTabbedPane.TOP);
    tabbedPane.addTab("Main", ball, splitPane, "Main Commands");
    tabbedPane.addTab("Get/Set", ball, propertieScrollPane, "Properties Panel");

    QSAdminPluginConfig qsAdminPluginConfig = null;
    PluginPanel pluginPanel = null;
    // -- start of loadPlugins
    try {
      File xmlFile = null;
      ClassLoader classLoader = null;
      Class mainClass = null;

      File file = new File(pluginDir);
      File dirs[] = null;

      if (file.canRead()) dirs = file.listFiles(new DirFileList());

      for (int i = 0; dirs != null && i < dirs.length; i++) {
        xmlFile = new File(dirs[i].getAbsolutePath() + File.separator + "plugin.xml");
        if (xmlFile.canRead()) {
          qsAdminPluginConfig = PluginConfigReader.read(xmlFile);
          if (qsAdminPluginConfig.getActive().equals("yes")
              && qsAdminPluginConfig.getType().equals("javax.swing.JPanel")) {
            classLoader = ClassUtil.getClassLoaderFromJars(dirs[i].getAbsolutePath());
            mainClass = classLoader.loadClass(qsAdminPluginConfig.getMainClass());
            logger.fine("Got PluginMainClass " + mainClass);
            pluginPanel = (PluginPanel) mainClass.newInstance();
            if (JPanel.class.isInstance(pluginPanel) == true) {
              logger.info("Loading plugin : " + qsAdminPluginConfig.getName());
              pluginPanelMap.put("" + (2 + i), pluginPanel);
              plugins.add(pluginPanel);
              tabbedPane.addTab(
                  qsAdminPluginConfig.getName(),
                  ball,
                  (JPanel) pluginPanel,
                  qsAdminPluginConfig.getDesc());
              pluginPanel.setQSAdminMain(qsadminMain);
              pluginPanel.init();
            }
          } else {
            logger.info(
                "Plugin "
                    + dirs[i]
                    + " is disabled so skipping "
                    + qsAdminPluginConfig.getActive()
                    + ":"
                    + qsAdminPluginConfig.getType());
          }
        } else {
          logger.info("No plugin configuration found in " + xmlFile + " so skipping");
        }
      }
    } catch (Exception e) {
      logger.warning("Error loading plugin : " + e);
      logger.fine("StackTrace:\n" + MyString.getStackTrace(e));
    }
    // -- end of loadPlugins

    tabbedPane.addChangeListener(
        new ChangeListener() {
          int selected = -1;
          int oldSelected = -1;

          public void stateChanged(ChangeEvent e) {
            // if plugin
            selected = tabbedPane.getSelectedIndex();
            if (selected >= 2) {
              ((PluginPanel) pluginPanelMap.get("" + selected)).activated();
            }
            if (oldSelected >= 2) {
              ((PluginPanel) pluginPanelMap.get("" + oldSelected)).deactivated();
            }
            oldSelected = selected;
          }
        });

    // tabbedPane.setBorder(BorderFactory.createEmptyBorder(0,5,5,5));
    cp.add(tabbedPane, BorderLayout.CENTER);

    buildMenu();
  }