/**
   * Returns the bytecode for the specified class.
   *
   * @param className the class for which bytecode is to be fetched/generated.
   * @return the bytecode for the specified class.
   * @throws ClassNotFoundException
   */
  private byte[] getBytecodeForClassInternal(final String className) throws ClassNotFoundException {

    final byte[] data;
    if (shouldLookupClassData()) {

      // Lookup the class data.
      if (PERFORM_TIMING) {
        final long before = System.currentTimeMillis();
        data = lookupClassData(className);
        final long after = System.currentTimeMillis();
        lookupClassDataTimeMS += (after - before);

      } else {
        data = lookupClassData(className);
      }

    } else {

      // Generate the class data.
      final int lastPeriodIndex = className.lastIndexOf('.');
      if (lastPeriodIndex < 0) {
        throw new ClassNotFoundException("Unable to find class: " + className);
      }
      final String unqualifiedClassName = className.substring(lastPeriodIndex + 1);
      try {

        if (PERFORM_TIMING) {
          final long before = System.currentTimeMillis();
          data = LECCJavaBytecodeGenerator.generateClassData(module, unqualifiedClassName);
          final long after = System.currentTimeMillis();
          generateClassDataTimeMS += (after - before);

        } else {
          data = LECCJavaBytecodeGenerator.generateClassData(module, unqualifiedClassName);
        }

      } catch (final CodeGenerationException e) {
        // Badness occurred.  This is a runtime exception.
        // -- OR --
        // The code generation failed because a foreign type or a foreign function's corresponding
        // Java entity
        // could not be resolved. (In this case the CodeGenerationException would be wrapping an
        // UnableToResolveForeignEntityException)

        // By throwing a NoClassDefFoundError instead of a ClassNotFoundException,
        //  we ensure that classes in the namespace for cal module packages are not found by other
        // classloaders.
        // A ClassNotFoundException will be caught by the calling loadClass() method, which will try
        // again with the parent classloader.

        // Imitate behaviour where NoClassDefFoundErrors thrown by the VM have the slashified class
        // name as the message.
        final Error error = new NoClassDefFoundError(className.replace('.', '/'));
        error.initCause(e);
        throw error;
      }
    }

    return data;
  }
Exemple #2
0
 /** Initialize ResourceBundle. */
 private static void initResource() {
   try {
     messageRBapt = ResourceBundle.getBundle(aptRB);
     messageRBjavac = ResourceBundle.getBundle(javacRB);
   } catch (MissingResourceException e) {
     Error x = new FatalError("Fatal Error: Resource for apt or javac is missing");
     x.initCause(e);
     throw x;
   }
 }
 SolrUpdateAction(String label, String description) {
   this.label = label;
   this.description = description;
   try {
     this.uri = new URI(JDOMNamespaceUtil.CDR_MESSAGE_NS.getURI() + "/solr/" + name());
   } catch (URISyntaxException e) {
     Error x =
         new ExceptionInInitializerError("Error creating URI for SolrUpdateAction " + name());
     x.initCause(e);
     throw x;
   }
 }
Exemple #4
0
  /**
   * Looks for all "META-INF/services/[className]" files and create one instance for each class name
   * found inside this file.
   */
  private static <T> T[] findServices(Class<T> clazz, ClassLoader classLoader) {
    // if true, print debug output
    final boolean debug =
        com.sun.tools.xjc.util.Util.getSystemProperty(Options.class, "findServices") != null;

    // if we are running on Mustang or Dolphin, use ServiceLoader
    // so that we can take advantage of JSR-277 module system.
    try {
      Class<?> serviceLoader = Class.forName("java.util.ServiceLoader");
      if (debug) System.out.println("Using java.util.ServiceLoader");
      Iterable<T> itr =
          (Iterable<T>)
              serviceLoader
                  .getMethod("load", Class.class, ClassLoader.class)
                  .invoke(null, clazz, classLoader);
      List<T> r = new ArrayList<T>();
      for (T t : itr) r.add(t);
      return r.toArray((T[]) Array.newInstance(clazz, r.size()));
    } catch (ClassNotFoundException e) {
      // fall through
    } catch (IllegalAccessException e) {
      Error x = new IllegalAccessError();
      x.initCause(e);
      throw x;
    } catch (InvocationTargetException e) {
      Throwable x = e.getTargetException();
      if (x instanceof RuntimeException) throw (RuntimeException) x;
      if (x instanceof Error) throw (Error) x;
      throw new Error(x);
    } catch (NoSuchMethodException e) {
      Error x = new NoSuchMethodError();
      x.initCause(e);
      throw x;
    }

    String serviceId = "META-INF/services/" + clazz.getName();

    // used to avoid creating the same instance twice
    Set<String> classNames = new HashSet<String>();

    if (debug) {
      System.out.println("Looking for " + serviceId + " for add-ons");
    }

    // try to find services in CLASSPATH
    try {
      Enumeration<URL> e = classLoader.getResources(serviceId);
      if (e == null) return (T[]) Array.newInstance(clazz, 0);

      ArrayList<T> a = new ArrayList<T>();
      while (e.hasMoreElements()) {
        URL url = e.nextElement();
        BufferedReader reader = null;

        if (debug) {
          System.out.println("Checking " + url + " for an add-on");
        }

        try {
          reader = new BufferedReader(new InputStreamReader(url.openStream()));
          String impl;
          while ((impl = reader.readLine()) != null) {
            // try to instanciate the object
            impl = impl.trim();
            if (classNames.add(impl)) {
              Class implClass = classLoader.loadClass(impl);
              if (!clazz.isAssignableFrom(implClass)) {
                pluginLoadFailure = impl + " is not a subclass of " + clazz + ". Skipping";
                if (debug) System.out.println(pluginLoadFailure);
                continue;
              }
              if (debug) {
                System.out.println("Attempting to instanciate " + impl);
              }
              a.add(clazz.cast(implClass.newInstance()));
            }
          }
          reader.close();
        } catch (Exception ex) {
          // let it go.
          StringWriter w = new StringWriter();
          ex.printStackTrace(new PrintWriter(w));
          pluginLoadFailure = w.toString();
          if (debug) {
            System.out.println(pluginLoadFailure);
          }
          if (reader != null) {
            try {
              reader.close();
            } catch (IOException ex2) {
              // ignore
            }
          }
        }
      }

      return a.toArray((T[]) Array.newInstance(clazz, a.size()));
    } catch (Throwable e) {
      // ignore any error
      StringWriter w = new StringWriter();
      e.printStackTrace(new PrintWriter(w));
      pluginLoadFailure = w.toString();
      if (debug) {
        System.out.println(pluginLoadFailure);
      }
      return (T[]) Array.newInstance(clazz, 0);
    }
  }