protected PsmMethodAction(Class c, String m, Class[] argArray) {
    // This prevents IllegalAccessExceptions when attempting to
    // invoke methods on a class that is in another package and not
    // defined 'public'.
    if (!Modifier.isPublic(c.getModifiers())) {
      throw new IllegalPsmMethodActionException("Action class must be public.");
    }

    try {
      method = c.getMethod(m, argArray);
    } catch (NoSuchMethodException ex) {
      throw new IllegalPsmMethodActionException(ex.toString() + ": method " + m);
    }

    // Check each exception this method declares thrown.  If it declares
    // exceptions, and any of them are not runtime exceptions, abort.
    Class[] exceptionTypes = method.getExceptionTypes();
    for (int i = 0; i < exceptionTypes.length; i++) {
      Class exceptionClass = exceptionTypes[i];
      if (!RuntimeException.class.isAssignableFrom(exceptionClass)) {
        throw new IllegalPsmMethodActionException(
            "Method must not declare non-Runtime " + "exceptions.");
      }
    }

    // Ensure that the method returns PsmEvent
    if (PsmEvent.class != method.getReturnType()) {
      throw new IllegalPsmMethodActionException("Method return type must be PsmEvent");
    }

    // Ensure that both the method is both public and static.
    if (!Modifier.isStatic(method.getModifiers()) || !Modifier.isPublic(method.getModifiers())) {
      throw new IllegalPsmMethodActionException("Method " + m + " must be static and public.");
    }
  }
Beispiel #2
0
 public <T> List<Class<T>> getInterfaceImplementations(Class<T> interfaceClass, File f)
     throws IOException, ClassNotFoundException {
   ArrayList<Class<T>> list = new ArrayList<>();
   List<String> classes = null;
   if (f.isDirectory()) {
     classes = getClassesFromDir(f);
   } else {
     classes = getClassesFromJar(f);
   }
   URL url = f.toURI().toURL();
   ClassLoader cl = new URLClassLoader(new URL[] {url}, this.getClass().getClassLoader());
   for (String klazz : classes) {
     try {
       Class<?> c = cl.loadClass(klazz);
       if (interfaceClass.isAssignableFrom(c) && !Modifier.isAbstract(c.getModifiers())) {
         list.add((Class<T>) c);
       }
     } catch (Throwable t) {
       LOGGER.warn(
           String.format(
               "Error checking if class %s from file %s is implementing %s: %s",
               klazz, f, interfaceClass.getName(), t.getMessage()));
     }
   }
   return list;
 }
  public static void main(String[] args) {
    // read class name from command line args or user input
    String name;
    if (args.length > 0) name = args[0];
    else {
      Scanner in = new Scanner(System.in);
      System.out.println("Enter class name (e.g. java.util.Date): ");
      name = in.next();
    }

    try {
      // print class name and superclass name (if != Object)
      Class cl = Class.forName(name);
      Class supercl = cl.getSuperclass();
      String modifiers = Modifier.toString(cl.getModifiers());
      if (modifiers.length() > 0) System.out.print(modifiers + " ");
      System.out.print("class " + name);
      if (supercl != null && supercl != Object.class)
        System.out.print(" extends " + supercl.getName());

      System.out.print("\n{\n");
      printConstructors(cl);
      System.out.println();
      printMethods(cl);
      System.out.println();
      printFields(cl);
      System.out.println("}");
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
    System.exit(0);
  }
  public static String isLocalType(Class<?> type) {
    /* As per [JACKSON-187], GAE seems to throw SecurityExceptions
     * here and there... and GAE itself has a bug, too
     * (see []). Bah.
     */
    try {
      // one more: method locals, anonymous, are not good:
      if (type.getEnclosingMethod() != null) {
        return "local/anonymous";
      }

      /* But how about non-static inner classes? Can't construct
       * easily (theoretically, we could try to check if parent
       * happens to be enclosing... but that gets convoluted)
       */
      if (type.getEnclosingClass() != null) {
        if (!Modifier.isStatic(type.getModifiers())) {
          return "non-static member class";
        }
      }
    } catch (SecurityException e) {
    } catch (NullPointerException e) {
    }
    return null;
  }
  @NotNull
  public Instantiator<?> findInstantiator(@NotNull Type type, @NotNull NamedTypeList types) {
    // First check if we have an immediate conversion registered. If so, we'll just use that.
    if (types.size() == 1) {
      TypeConversion conversion = findConversionFromDbValue(types.getType(0), type).orElse(null);
      if (conversion != null) return args -> conversion.convert(args.getSingleValue());
    }

    Class<?> cl = rawType(type);

    Instantiator<?> instantiator = findExplicitInstantiatorFor(cl, types).orElse(null);
    if (instantiator != null) return instantiator;

    if (!isPublic(cl.getModifiers()))
      throw new InstantiationFailureException(
          type
              + " can't be instantiated reflectively because it is not public or missing a @DalesbredConstructor-annotation");

    return candidateConstructorsSortedByDescendingParameterCount(cl)
        .map(ctor -> implicitInstantiatorFrom(ctor, types).orElse(null))
        .filter(Objects::nonNull)
        .findFirst()
        .orElseThrow(
            () ->
                new InstantiationFailureException(
                    "could not find a way to instantiate " + type + " with parameters " + types));
  }
 /**
  * Register a custom argument creator factory for an unknown final class
  *
  * @param clazz The class for which this factory should be used
  * @param creator The argument factory
  * @param <T>
  */
 public static <T> void registerFinalClassArgumentCreator(
     Class<T> clazz, FinalClassArgumentCreator<T> creator) {
   if ((clazz.getModifiers() & Modifier.FINAL) == 0)
     throw new RuntimeException(
         "A custom argument creator can be registered only for final classes");
   FINAL_CLASS_ARGUMENT_CREATORS.put(clazz, creator);
 }
  private void validateClass(Class<?> source, ValidationProblemCollector problems) {
    int modifiers = source.getModifiers();

    if (Modifier.isInterface(modifiers)) {
      problems.add("Must be a class, not an interface");
    }

    if (source.getEnclosingClass() != null) {
      if (Modifier.isStatic(modifiers)) {
        if (Modifier.isPrivate(modifiers)) {
          problems.add("Class cannot be private");
        }
      } else {
        problems.add("Enclosed classes must be static and non private");
      }
    }

    Constructor<?>[] constructors = source.getDeclaredConstructors();
    for (Constructor<?> constructor : constructors) {
      if (constructor.getParameterTypes().length > 0) {
        problems.add("Cannot declare a constructor that takes arguments");
        break;
      }
    }

    Field[] fields = source.getDeclaredFields();
    for (Field field : fields) {
      int fieldModifiers = field.getModifiers();
      if (!field.isSynthetic()
          && !(Modifier.isStatic(fieldModifiers) && Modifier.isFinal(fieldModifiers))) {
        problems.add(field, "Fields must be static final.");
      }
    }
  }
Beispiel #8
0
  @Nullable
  public InstanceFactory findInstanceFactory(@Nonnull Type mockedType) {
    InstanceFactory instanceFactory = mockedTypesAndInstances.get(mockedType);

    if (instanceFactory != null) {
      return instanceFactory;
    }

    Class<?> mockedClass = getClassType(mockedType);
    //noinspection ReuseOfLocalVariable
    instanceFactory = mockedTypesAndInstances.get(mockedClass);

    if (instanceFactory != null) {
      return instanceFactory;
    }

    boolean abstractType = mockedClass.isInterface() || isAbstract(mockedClass.getModifiers());

    for (Entry<Type, InstanceFactory> entry : mockedTypesAndInstances.entrySet()) {
      Type registeredMockedType = entry.getKey();
      Class<?> registeredMockedClass = getClassType(registeredMockedType);

      if (abstractType) {
        registeredMockedClass = getMockedClassOrInterfaceType(registeredMockedClass);
      }

      if (mockedClass.isAssignableFrom(registeredMockedClass)) {
        instanceFactory = entry.getValue();
        break;
      }
    }

    return instanceFactory;
  }
Beispiel #9
0
  public JavaType findType(String name) {
    if (_bindings == null) {
      _resolve();
    }
    JavaType t = _bindings.get(name);
    if (t != null) {
      return t;
    }
    if (_placeholders != null && _placeholders.contains(name)) {
      return UNBOUND;
    }
    // New with 1.7: check parent context
    if (_parentBindings != null) {
      return _parentBindings.findType(name);
    }
    // nothing found, so...
    // Should we throw an exception or just return null?

    /* [JACKSON-499] 18-Feb-2011, tatu: There are some tricky type bindings within
     *   java.util, such as HashMap$KeySet; so let's punt the problem
     *   (honestly not sure what to do -- they are unbound for good, I think)
     */
    if (_contextClass != null) {
      Class<?> enclosing = _contextClass.getEnclosingClass();
      if (enclosing != null) {
        // [JACKSON-572]: Actually, let's skip this for all non-static inner classes
        //   (which will also cover 'java.util' type cases...
        if (!Modifier.isStatic(_contextClass.getModifiers())) {
          return UNBOUND;
        }

        // ... so this piece of code should not be needed any more
        /*
        Package pkg = enclosing.getPackage();
        if (pkg != null) {
            // as per [JACKSON-533], also include "java.util.concurrent":
            if (pkg.getName().startsWith("java.util")) {
                return UNBOUND;
            }
        }
        */
      }
    }

    String className;
    if (_contextClass != null) {
      className = _contextClass.getName();
    } else if (_contextType != null) {
      className = _contextType.toString();
    } else {
      className = "UNKNOWN";
    }
    throw new IllegalArgumentException(
        "Type variable '"
            + name
            + "' can not be resolved (with context of class "
            + className
            + ")");
    // t = UNBOUND;
  }
Beispiel #10
0
  /** @return the test suite */
  public static Test suite() {
    TestSuite suite = new TestSuite();
    int count = 0;

    for (Enumeration e = (new LoadingTestCollector()).collectTests(); e.hasMoreElements(); ) {
      Object o = e.nextElement();

      if (!(o instanceof String)) continue;
      String s = (String) o;

      if (s.equals("org.argouml.util.DoAllTests")) continue;

      Class candidate;
      try {
        candidate = Class.forName(s);
      } catch (ClassNotFoundException exception) {
        System.err.println("Cannot load class: " + s);
        continue;
      }
      if (!Modifier.isAbstract(candidate.getModifiers())) {
        suite.addTest(new TestSuite(candidate));
        count++;
      }
    }
    System.out.println("Number of test classes found: " + count);

    return suite;
  }
Beispiel #11
0
 private ITemplate templateInstance_() {
   if (!isValid) return NULL_TEMPLATE;
   if (null == templateInstance) {
     try {
       if (Logger.isTraceEnabled()) logger.trace("About to new template instance");
       Class<?> clz = getJavaClass();
       if (Logger.isTraceEnabled()) logger.trace("template java class loaded");
       templateInstance = (TemplateBase) clz.newInstance();
       if (Logger.isTraceEnabled()) logger.trace("template instance generated");
     } catch (RythmException e) {
       throw e;
     } catch (Exception e) {
       throw new RuntimeException("Error load template instance for " + getKey(), e);
     }
   }
   if (!engine().isProdMode()) {
     // check parent class change
     Class<?> c = templateInstance.getClass();
     Class<?> pc = c.getSuperclass();
     if (null != pc && !Modifier.isAbstract(pc.getModifiers())) {
       engine().classes.getByClassName(pc.getName());
     }
   }
   templateInstance.setTemplateClass(this);
   return templateInstance;
 }
  private Configurable getComponentFromAnnotation(String name, S4Component s4Component) {
    Configurable configurable;
    Class<? extends Configurable> defClass = s4Component.defaultClass();

    if (defClass.equals(Configurable.class) && s4Component.mandatory()) {
      throw new InternalConfigurationException(
          getInstanceName(), name, "mandatory property is not set!");
    }

    if (Modifier.isAbstract(defClass.getModifiers()) && s4Component.mandatory())
      throw new InternalConfigurationException(
          getInstanceName(), name, defClass.getName() + " is abstract!");

    // because we're forced to use the default type, make sure that it
    // is set
    if (defClass.equals(Configurable.class)) {
      if (s4Component.mandatory()) {
        throw new InternalConfigurationException(
            getInstanceName(), name, instanceName + ": no default class defined for " + name);
      } else {
        return null;
      }
    }

    configurable = ConfigurationManager.getInstance(defClass);
    if (configurable == null) {
      throw new InternalConfigurationException(
          getInstanceName(), name, "instantiation of referenenced configurable failed");
    }

    return configurable;
  }
  private List<Class> findClassesImpl(Class requiredInterface) throws Exception {
    logger.debug(
        "ServiceLocator finding classes matching interface " + requiredInterface.getName());

    List<Class> classes = new ArrayList<Class>();

    classResolver.addClassLoader(resourceAccessor.toClassLoader());
    for (Class<?> clazz :
        classResolver.findImplementations(
            requiredInterface, packagesToScan.toArray(new String[packagesToScan.size()]))) {
      if (clazz.getAnnotation(LiquibaseService.class) != null
          && clazz.getAnnotation(LiquibaseService.class).skip()) {
        continue;
      }

      if (!Modifier.isAbstract(clazz.getModifiers())
          && !Modifier.isInterface(clazz.getModifiers())
          && Modifier.isPublic(clazz.getModifiers())) {
        try {
          clazz.getConstructor();
          logger.debug(clazz.getName() + " matches " + requiredInterface.getName());

          classes.add(clazz);
        } catch (NoSuchMethodException e) {
          logger.info(
              "Can not use "
                  + clazz
                  + " as a Liquibase service because it does not have a no-argument constructor");
        } catch (NoClassDefFoundError e) {
          String message =
              "Can not use "
                  + clazz
                  + " as a Liquibase service because "
                  + e.getMessage().replace("/", ".")
                  + " is not in the classpath";
          if (e.getMessage().startsWith("org/yaml/snakeyaml")) {
            logger.info(message);
          } else {
            logger.warning(message);
          }
        }
      }
    }

    return classes;
  }
 /**
  * Creates a ClassNode from a real class. The resulting ClassNode will not be a primary ClassNode.
  */
 public ClassNode(Class c) {
   this(c.getName(), c.getModifiers(), null, null, MixinNode.EMPTY_ARRAY);
   clazz = c;
   lazyInitDone = false;
   CompileUnit cu = getCompileUnit();
   if (cu != null) cu.addClass(this);
   isPrimaryNode = false;
 }
  private <T> CachedRuleSource doExtract(final Class<T> source) {
    final ModelType<T> type = ModelType.of(source);
    DefaultMethodModelRuleExtractionContext context =
        new DefaultMethodModelRuleExtractionContext(type, this);

    // TODO - exceptions thrown here should point to some extensive documentation on the concept of
    // class rule sources

    StructSchema<T> schema = getSchema(source, context);
    if (schema == null) {
      throw new InvalidModelRuleDeclarationException(context.problems.format());
    }

    // sort for determinism
    Set<Method> methods = new TreeSet<Method>(Ordering.usingToString());
    methods.addAll(Arrays.asList(source.getDeclaredMethods()));

    ImmutableList.Builder<ModelProperty<?>> implicitInputs = ImmutableList.builder();
    ModelProperty<?> target = null;
    for (ModelProperty<?> property : schema.getProperties()) {
      if (property.isAnnotationPresent(RuleTarget.class)) {
        target = property;
      } else if (property.isAnnotationPresent(RuleInput.class)
          && !(property.getSchema() instanceof ScalarValueSchema)) {
        implicitInputs.add(property);
      }
      for (WeaklyTypeReferencingMethod<?, ?> method : property.getAccessors()) {
        methods.remove(method.getMethod());
      }
    }

    ImmutableList.Builder<ExtractedRuleDetails> rules = ImmutableList.builder();
    for (Method method : methods) {
      MethodRuleDefinition<?, ?> ruleDefinition =
          DefaultMethodRuleDefinition.create(source, method);
      ExtractedModelRule rule = getMethodHandler(ruleDefinition, method, context);
      if (rule != null) {
        rules.add(new ExtractedRuleDetails(ruleDefinition, rule));
      }
    }

    if (context.hasProblems()) {
      throw new InvalidModelRuleDeclarationException(context.problems.format());
    }

    StructBindings<T> bindings = structBindingsStore.getBindings(schema);

    if (schema.getProperties().isEmpty()) {
      return new StatelessRuleSource(
          rules.build(),
          Modifier.isAbstract(source.getModifiers())
              ? new AbstractRuleSourceFactory<T>(schema, bindings, proxyFactory)
              : new ConcreteRuleSourceFactory<T>(type));
    } else {
      return new ParameterizedRuleSource(
          rules.build(), target, implicitInputs.build(), schema, bindings, proxyFactory);
    }
  }
 static {
   final Reflections reflections = new Reflections("uk.ac.ebi.interpro.scan.model");
   final Set<Class<? extends Match>> allClasses = reflections.getSubTypesOf(Match.class);
   for (Class clazz : allClasses) {
     if (!Modifier.isAbstract(clazz.getModifiers())) { // Concrete only.
       CONCRETE_MATCH_CLASSES.add(clazz.getSimpleName());
     }
   }
 }
Beispiel #17
0
 private Mod loadCustomMod(URLClassLoader loader, String className)
     throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException {
   Class<?> cl = null;
   try {
     cl = loader.loadClass(className);
   } catch (NoClassDefFoundError e) {
     Logger.log(Logger.LOG_MOD, "WARNING: skipping %s: %s", className, e.toString());
   }
   if (cl != null && !cl.isInterface() && Mod.class.isAssignableFrom(cl)) {
     int flags = cl.getModifiers();
     if (!Modifier.isAbstract(flags) && Modifier.isPublic(flags)) {
       return newModInstance(cl.asSubclass(Mod.class));
     }
   }
   return null;
 }
Beispiel #18
0
 /**
  * Checks if a class fulfills the JavaBeans contract.
  *
  * @param cls the class to check
  */
 public static void checkJavaBean(Class<?> cls) {
   try {
     Constructor<?> constructor = cls.getDeclaredConstructor();
     int classModifiers = cls.getModifiers();
     if (Modifier.isInterface(classModifiers))
       throw new RuntimeException(cls.getName() + " is an interface");
     if (Modifier.isAbstract(classModifiers))
       throw new RuntimeException(
           cls.getName() + " cannot be instantiated - it is an abstract class");
     int modifiers = constructor.getModifiers();
     if (!Modifier.isPublic(modifiers))
       throw new RuntimeException("No public default constructor in " + cls);
   } catch (NoSuchMethodException e) {
     throw new RuntimeException("No default constructor in class " + cls);
   } catch (SecurityException e) {
     logger.error(
         "I am not allowed to check the class by using reflection, "
             + "so I just can hope the class is alright and go on: ",
         e);
   }
 }
  /**
   * Finds all classes inside the stated scope that implement TetradSerializable and serializes them
   * out to the getCurrentDirectory() directory. Abstract methods and interfaces are skipped over.
   * For all other classes C, it is assumed that C has a static constructor of the following form:
   *
   * <pre>
   *     public static C serializableInstance() {
   *         // Returns an instance of C. May be a mind-numbingly simple
   *         // instance, no need to get fancy.
   *     }
   * </pre>
   *
   * The instance returned may be mind-numbingly simple; there is no need to get fancy. It may
   * change over time. The point is to make sure that instances serialized out with earlier versions
   * load with the currentDirectory version.
   *
   * @throws RuntimeException if clazz cannot be serialized. This exception has an informative
   *     message and wraps the originally thrown exception as root cause.
   */
  public void serializeCurrentDirectory() throws RuntimeException {
    clearCurrentDirectory();
    @SuppressWarnings("Convert2Diamond")
    Map<String, List<String>> classFields = new TreeMap<>();

    // Get the classes that implement SerializationCanonicalizer.
    List classes = getAssignableClasses(new File(getSerializableScope()), TetradSerializable.class);

    System.out.println(
        "Serializing exemplars of instantiable TetradSerializable "
            + "in "
            + getSerializableScope()
            + ".");
    System.out.println("Writing serialized examplars to " + getCurrentDirectory());

    int index = -1;

    for (Object aClass : classes) {
      Class clazz = (Class) aClass;

      if (TetradSerializableExcluded.class.isAssignableFrom(clazz)) {
        continue;
      }

      if (Modifier.isAbstract(clazz.getModifiers())) {
        continue;
      }

      if (Modifier.isInterface(clazz.getModifiers())) {
        continue;
      }

      int numFields = getNumNonSerialVersionUIDFields(clazz);

      if (numFields > 0 && serializableInstanceMethod(clazz) == null) {
        throw new RuntimeException(
            "Class "
                + clazz
                + " does not "
                + "\nhave a public static serializableInstance constructor.");
      }

      if (++index % 50 == 0) {
        System.out.println(index);
      }

      System.out.print(".");

      serializeClass(clazz, classFields);
    }

    try {
      File file = new File(getCurrentDirectory(), "class_fields.ser");
      FileOutputStream out = new FileOutputStream(file);
      ObjectOutputStream objOut = new ObjectOutputStream(out);
      objOut.writeObject(classFields);
      out.close();
    } catch (IOException e) {
      e.printStackTrace();
    }

    System.out.println("\nFinished serializing exemplars.");
  }
 @Override
 public int getModifiers() {
   return _class.getModifiers();
 }
  /**
   * Process and loop until told to stop. A callback_done will stop the loop and will return a
   * result. Otherwise null is returned.
   */
  public Object run() throws CommandException {
    Object result = null;
    boolean shutdown = false;
    boolean closeWhenDone = true;
    Commands.ValueObject valueObject =
        new Commands.ValueObject(); // Working value object so not continually recreated.
    InvokableValueSender valueSender =
        new InvokableValueSender(); // Working valuesender so not continually recreated.
    try {
      boolean doLoop = true;

      /**
       * Note: In the cases below you will see a lot of finally clauses that null variables out.
       * This is because this is a long running loop, and variables declared within blocks are not
       * garbage collected until the method is terminated, so these variables once set would never
       * be GC'd. The nulling at the end of the case makes sure that any of those objects set are
       * now available for garbage collection when necessary.
       */
      while (doLoop && isConnected()) {
        byte cmd = 0;
        try {
          if (LINUX_1_3) socket.setSoTimeout(1000); // Linux 1.3 bug, see comment on LINUX_1_3
          cmd = in.readByte();
          if (LINUX_1_3 && isConnected())
            socket.setSoTimeout(0); // Linux 1.3 bug, see comment on LINUX_1_3
        } catch (InterruptedIOException e) {
          continue; // Timeout, try again
        }
        switch (cmd) {
          case Commands.QUIT_CONNECTION:
            doLoop = false;
            break; // Close this connection

          case Commands.TERMINATE_SERVER:
            doLoop = false;
            shutdown = true; // Shutdown everything
            break;

          case Commands.GET_CLASS:
            String className = in.readUTF();
            Class aClass = null;
            Class superClass = null;
            String superClassName = null;
            boolean added = false;
            try {
              aClass =
                  Class.forName(
                      className); // Turns out using JNI format for array type will work fine.

              added = server.getIdentityID(aClass, valueObject);
              boolean isInterface = aClass.isInterface();
              boolean isAbstract = java.lang.reflect.Modifier.isAbstract(aClass.getModifiers());
              superClass = aClass.getSuperclass();
              superClassName = (superClass != null) ? superClass.getName() : ""; // $NON-NLS-1$
              out.writeByte(Commands.GET_CLASS_RETURN);
              out.writeInt(valueObject.objectID);
              out.writeBoolean(isInterface);
              out.writeBoolean(isAbstract);
              out.writeUTF(superClassName);
              out.flush();
            } catch (ClassNotFoundException e) {
              valueObject.set();
              Commands.sendErrorCommand(out, Commands.GET_CLASS_NOT_FOUND, valueObject);
            } catch (ExceptionInInitializerError e) {
              sendException(e.getException(), valueObject, out);
            } catch (LinkageError e) {
              sendException(e, valueObject, out);
            } catch (Throwable e) {
              // Something bad, did we add a class? If we did remove it from the table.
              if (added) server.removeObject(server.getObject(valueObject.objectID));
              throw e;
            } finally {
              // clear out for GC to work.
              className = null;
              aClass = null;
              superClass = null;
              superClassName = null;
              valueObject.set();
            }
            break;

          case Commands.GET_CLASS_FROM_ID:
            int classID = in.readInt();
            try {
              aClass = (Class) server.getObject(classID);
              boolean isInterface = aClass.isInterface();
              boolean isAbstract = java.lang.reflect.Modifier.isAbstract(aClass.getModifiers());
              superClass = aClass.getSuperclass();
              superClassName = (superClass != null) ? superClass.getName() : ""; // $NON-NLS-1$
              out.writeByte(Commands.GET_CLASS_ID_RETURN);
              out.writeUTF(aClass.getName());
              out.writeBoolean(isInterface);
              out.writeBoolean(isAbstract);
              out.writeUTF(superClassName);
              out.flush();
            } catch (ClassCastException e) {
              valueObject.set();
              Commands.sendErrorCommand(out, Commands.CLASS_CAST_EXCEPTION, valueObject);
            } finally {
              // clear out for GC to work.
              aClass = null;
              superClass = null;
              superClassName = null;
              valueObject.set();
            }
            break;

          case Commands.GET_OBJECT_DATA:
            int objectID = in.readInt();
            Object anObject = null;
            try {
              anObject = server.getObject(objectID);
              valueObject.setObjectID(objectID, server.getIdentityID(anObject.getClass()));
              Commands.writeValue(out, valueObject, true);
            } catch (ClassCastException e) {
              valueObject.set();
              Commands.sendErrorCommand(out, Commands.CLASS_CAST_EXCEPTION, valueObject);
            } finally {
              anObject = null; // Clear out for GC to work
              valueObject.set();
            }
            break;

          case Commands.RELEASE_OBJECT:
            int id = in.readInt();
            server.removeObject(server.getObject(id));
            break;

          case Commands.NEW_INIT_STRING:
            classID = in.readInt(); // ID Of class to do new upon.
            String initString = in.readUTF(); // The init string.
            Object newValue = null;
            Class theClass = null;
            try {
              theClass = (Class) server.getObject(classID);
              if (theClass == null) {
                // The class wasn't found. So imply ClassNotFound exception.
                throw new ClassNotFoundException();
              }

              InitializationStringParser parser = null;
              try {
                parser = InitializationStringParser.createParser(initString);
                newValue = parser.evaluate();
                boolean primitive = parser.isPrimitive();
                // If expected class is Void.TYPE, that means don't test the type of the result
                // to verify if correct type, just return what it really is.
                if (theClass != Void.TYPE && primitive != theClass.isPrimitive()) {
                  valueObject.set();
                  Commands.sendErrorCommand(out, Commands.CLASS_CAST_EXCEPTION, valueObject);
                  continue; // Goto next command.
                }
                if (primitive) {
                  try {
                    // Need to do special tests for compatibility and assignment.
                    sendObject(
                        newValue,
                        classID != Commands.VOID_TYPE
                            ? classID
                            : server.getIdentityID(parser.getExpectedType()),
                        valueObject,
                        out,
                        true); // This will make sure it goes out as the correct primitive type
                  } catch (ClassCastException e) {
                    // The returned type is not of the correct type for what is expected.
                    valueObject.set();
                    Commands.sendErrorCommand(out, Commands.CLASS_CAST_EXCEPTION, valueObject);
                    continue; // Goto next command
                  }
                } else {
                  if (newValue != null) {
                    // Test to see if they are compatible. (Null can be assigned to any object,
                    // so that is why it was tested out above).
                    // If expected class is Void.TYPE, that means don't test the type of the result
                    // to verify if correct type, just return what it really is.
                    if (theClass != Void.TYPE && !theClass.isInstance(newValue)) {
                      // The returned type is not of the correct type for what is expected.
                      valueObject.set();
                      Commands.sendErrorCommand(out, Commands.CLASS_CAST_EXCEPTION, valueObject);
                      continue; // Goto next command
                    }
                  }
                  sendObject(
                      newValue, NOT_A_PRIMITIVE, valueObject, out, true); // Send out as an object.
                }
              } catch (InitializationStringEvaluationException e) {
                if (e instanceof EvaluationException) {
                  // Want to return the real exception.
                  sendException(e.getOriginalException(), valueObject, out);
                } else {
                  // Couldn't be evaluated, return an error for this.
                  setExceptionIntoValue(e.getOriginalException(), valueObject);
                  Commands.sendErrorCommand(out, Commands.CANNOT_EVALUATE_STRING, valueObject);
                }
              } finally {
                parser = null; // Clear out for GC to work
              }
            } catch (Throwable e) {
              sendException(e, valueObject, out);
            } finally {
              // Clear out for GC to work
              initString = null;
              theClass = null;
              newValue = null;
              valueObject.set();
            }
            break;

          case Commands.INVOKE:
            Object target = null;
            Object[] parms = null;
            Class returnType = null;
            java.lang.reflect.Method aMethod = null;
            try {
              int methodID = in.readInt(); // ID of method to invoke
              aMethod = (java.lang.reflect.Method) server.getObject(methodID); // Method to invoke
              Commands.readValue(in, valueObject);
              target = getInvokableObject(valueObject);
              Commands.readValue(in, valueObject);
              if (valueObject.type == Commands.ARRAY_IDS) {
                // It is an array containing IDs, as it normally would be.
                valueSender.initialize(valueObject);
                Commands.readArray(in, valueObject.anInt, valueSender, valueObject, false);
                parms = (Object[]) valueSender.getArray();
              } else {
                // It is all objects or null, so it should be an Object[] or null. If not, then this
                // is an error.
                parms = (Object[]) valueObject.anObject;
              }

              if (!aMethod.isAccessible())
                aMethod.setAccessible(
                    true); // We will allow all to occur. Let access control be handled by IDE and
                           // compiler.
              newValue = aMethod.invoke(target, parms);
              returnType = aMethod.getReturnType();
              if (returnType.isPrimitive()) {
                int returnTypeID = server.getIdentityID(returnType);
                // Need to tell sendObject the correct primitive type.
                sendObject(newValue, returnTypeID, valueObject, out, true);

              } else {
                sendObject(
                    newValue,
                    NOT_A_PRIMITIVE,
                    valueObject,
                    out,
                    true); // Just send the object back. sendObject knows how to iterpret the type
              }
            } catch (CommandException e) {
              throw e; // Throw it again. These we don't want to come up as an exception proxy.
                       // These should end the thread.
            } catch (java.lang.reflect.InvocationTargetException e) {
              // This is a wrappered exception. Return the wrappered one so it looks like
              // it was the real one. (Sometimes the method being invoked is on a
              // java.lang.reflect.Constructor.newInstance,
              // which in turn is an InvocationTargetException, so we will go until we don't have an
              // InvocationTargetException.
              Throwable t = e;
              do {
                t = ((java.lang.reflect.InvocationTargetException) t).getTargetException();
              } while (t instanceof java.lang.reflect.InvocationTargetException);
              sendException(t, valueObject, out);
            } catch (Throwable e) {
              sendException(e, valueObject, out); // Turn it into a exception proxy on the client.
            } finally {
              // Clear out for GC to work
              valueObject.set();
              parms = null;
              target = null;
              aMethod = null;
              returnType = null;
              newValue = null;
              valueSender.clear();
            }
            break;

          case Commands.INVOKE_WITH_METHOD_PASSED:
            aClass = null;
            String methodName = null;
            Class[] parmTypes = null;
            target = null;
            parms = null;
            returnType = null;
            aMethod = null;

            try {
              Commands.readValue(in, valueObject);
              aClass = (Class) getInvokableObject(valueObject); // The class that has the method.
              methodName = in.readUTF();
              Commands.readValue(in, valueObject);
              if (valueObject.type == Commands.ARRAY_IDS) {
                // It is an array containing IDs, as it normally would be.
                valueSender.initialize(valueObject);
                Commands.readArray(in, valueObject.anInt, valueSender, valueObject, false);
                parmTypes = (Class[]) valueSender.getArray();
              } else {
                // It null, so it should be an null. If not, then this is an error.
                parmTypes = null;
              }
              aMethod = aClass.getMethod(methodName, parmTypes);

              // Now we get the info for the invocation of the method and execute it.
              Commands.readValue(in, valueObject);
              target = getInvokableObject(valueObject);
              Commands.readValue(in, valueObject);
              if (valueObject.type == Commands.ARRAY_IDS) {
                // It is an array containing IDs, as it normally would be.
                valueSender.initialize(valueObject);
                Commands.readArray(in, valueObject.anInt, valueSender, valueObject, false);
                parms = (Object[]) valueSender.getArray();
              } else {
                // It is all objects or null, so it should be an Object[] or null. If not, then this
                // is an error.
                parms = (Object[]) valueObject.anObject;
              }

              if (!aMethod.isAccessible())
                aMethod.setAccessible(
                    true); // We will allow all to occur. Let access control be handled by IDE and
                           // compiler.
              newValue = aMethod.invoke(target, parms);
              returnType = aMethod.getReturnType();
              if (returnType.isPrimitive()) {
                int returnTypeID = server.getIdentityID(returnType);
                // Need to tell sendObject the correct primitive type.
                sendObject(newValue, returnTypeID, valueObject, out, true);

              } else {
                sendObject(
                    newValue,
                    NOT_A_PRIMITIVE,
                    valueObject,
                    out,
                    true); // Just send the object back. sendObject knows how to iterpret the type
              }
            } catch (CommandException e) {
              throw e; // Throw it again. These we don't want to come up as an exception proxy.
                       // These should end the thread.
            } catch (java.lang.reflect.InvocationTargetException e) {
              // This is a wrappered exception. Return the wrappered one so it looks like
              // it was the real one. (Sometimes the method being invoked is on a
              // java.lang.reflect.Constructor.newInstance,
              // which in turn is an InvocationTargetException, so we will go until we don't have an
              // InvocationTargetException.
              Throwable t = e;
              do {
                t = ((java.lang.reflect.InvocationTargetException) t).getTargetException();
              } while (t instanceof java.lang.reflect.InvocationTargetException);
              sendException(t, valueObject, out);

            } catch (Throwable e) {
              sendException(e, valueObject, out); // Turn it into a exception proxy on the client.
            } finally {
              aClass = null;
              methodName = null;
              parmTypes = null;
              // Clear out for GC to work
              valueObject.set();
              parms = null;
              target = null;
              aMethod = null;
              returnType = null;
              newValue = null;
              valueSender.clear();
            }
            break;

          case Commands.GET_ARRAY_CONTENTS:
            try {
              target = server.getObject(in.readInt()); // Array to get the ids for.
              valueObject.setArrayIDS(
                  new ArrayContentsRetriever(target),
                  Array.getLength(target),
                  Commands.OBJECT_CLASS);
              Commands.writeValue(out, valueObject, true); // Write it back as a value command.
            } catch (CommandException e) {
              throw e; // Throw it again. These we don't want to come up as an exception proxy.
                       // These should end the thread.
            } catch (Throwable e) {
              sendException(e, valueObject, out); // Turn it into a exception proxy on the client.
            } finally {
              target = null;
              valueObject.set();
            }
            break;

          case Commands.CALLBACK_DONE:
            try {
              if (connectionThread != null) {
                valueObject.set();
                Commands.sendErrorCommand(out, Commands.UNKNOWN_COMMAND_SENT, valueObject);
              } else {
                try {
                  Commands.readBackValue(in, valueObject, Commands.NO_TYPE_CHECK);
                  if (valueObject.type == Commands.ARRAY_IDS) {
                    // It is an array containing IDs, as it normally would be.
                    valueSender.initialize(valueObject);
                    Commands.readArray(in, valueObject.anInt, valueSender, valueObject, false);
                    result = valueSender.getArray();
                  } else {
                    result = getInvokableObject(valueObject);
                  }
                  doLoop = false; // We need to terminate and return result
                  closeWhenDone = false; // Don't close, we will continue.
                } catch (CommandErrorException e) {
                  // There was an command error on the other side. This means
                  // connection still good, but don't continue the callback processing.
                  doLoop = false; // We need to terminate and return result
                  closeWhenDone = false; // Don't close, we will continue.
                  throw e; // Let it go on out.
                }
              }
            } finally {
              valueObject.set();
              valueSender.clear();
            }
            break;

          case Commands.ERROR:
            try {
              // Got an error command. Don't know what to do but read the
              // value and simply print it out.
              Commands.readValue(in, valueObject);
              result = getInvokableObject(valueObject);
              System.out.println("Error sent to server: Result=" + result); // $NON-NLS-1$
            } finally {
              valueObject.set();
            }
            break;

          case Commands.EXPRESSION_TREE_COMMAND:
            try {
              processExpressionCommand(valueObject, valueSender);
            } finally {
              valueObject.set();
              valueSender.clear();
            }
            break;

          default:
            // Unknown command. We don't know how long it is, so we need to shut the connection
            // down.
            System.err.println("Error: Invalid cmd send to server: Cmd=" + cmd); // $NON-NLS-1$
            doLoop = false;
            closeWhenDone = true;
            break;
        }
      }
    } catch (EOFException e) {
      // This is ok. It means that the connection on the other side was terminated.
      // So just accept this and go down.
    } catch (CommandException e) {
      throw e;
    } catch (SocketException e) {
      if (socket != null)
        throw new UnexpectedExceptionCommandException(
            false, e); // socket null means a valid close request
    } catch (Throwable e) {
      e.printStackTrace();
    } finally {
      if (closeWhenDone) {
        try {
          for (Iterator itr = expressionProcessors.values().iterator(); itr.hasNext(); ) {
            ExpressionProcesserController exp = (ExpressionProcesserController) itr.next();
            exp.close();
          }
        } finally {
          expressionProcessors.clear();
        }

        if (in != null)
          try {
            in.close();
          } catch (Exception e) {
          }
        in = null;
        if (out != null)
          try {
            out.close();
          } catch (Exception e) {
          }
        out = null;
        close();
      }
    }

    if (closeWhenDone && connectionThread != null) server.removeConnectionThread(connectionThread);
    if (shutdown) server.requestShutdown();

    return result;
  }
  /** Calculates a MD5 digest of the class. */
  public String getDigest() {
    try {
      if (_className == null || "".equals(_className)) return "";

      DynamicClassLoader loader =
          (DynamicClassLoader) Thread.currentThread().getContextClassLoader();

      ClassLoader tmpLoader = loader.getNewTempClassLoader();

      Class cl = Class.forName(_className, false, tmpLoader);

      if (cl == null) return "";

      MessageDigest digest = MessageDigest.getInstance("MD5");

      addDigest(digest, cl.getName());

      addDigest(digest, cl.getModifiers());

      Class superClass = cl.getSuperclass();
      if (superClass != null) addDigest(digest, superClass.getName());

      Class[] interfaces = cl.getInterfaces();
      for (int i = 0; i < interfaces.length; i++) addDigest(digest, interfaces[i].getName());

      Field[] fields = cl.getDeclaredFields();

      Arrays.sort(fields, new FieldComparator());

      if (_checkFields) {
        for (Field field : fields) {
          if (Modifier.isPrivate(field.getModifiers()) && !_checkPrivate) continue;
          if (Modifier.isProtected(field.getModifiers()) && !_checkProtected) continue;

          addDigest(digest, field.getName());
          addDigest(digest, field.getModifiers());
          addDigest(digest, field.getType().getName());

          addDigest(digest, field.getAnnotations());
        }
      }

      Method[] methods = cl.getDeclaredMethods();
      Arrays.sort(methods, new MethodComparator());

      for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];

        if (Modifier.isPrivate(method.getModifiers()) && !_checkPrivate) continue;
        if (Modifier.isProtected(method.getModifiers()) && !_checkProtected) continue;
        if (Modifier.isStatic(method.getModifiers()) && !_checkStatic) continue;

        addDigest(digest, method.getName());
        addDigest(digest, method.getModifiers());
        addDigest(digest, method.getName());

        Class[] param = method.getParameterTypes();
        for (int j = 0; j < param.length; j++) addDigest(digest, param[j].getName());

        addDigest(digest, method.getReturnType().getName());

        Class[] exn = method.getExceptionTypes();
        for (int j = 0; j < exn.length; j++) addDigest(digest, exn[j].getName());

        addDigest(digest, method.getAnnotations());
      }

      byte[] digestBytes = new byte[256];

      int len = digest.digest(digestBytes, 0, digestBytes.length);

      return digestToBase64(digestBytes, len);
    } catch (Exception e) {
      log.log(Level.FINER, e.toString(), e);

      return "";
    }
  }
  private void addTestsFromFile(TestSuite suite, File file) {
    Class<?> rawClass = getClassFrom(file);
    if (rawClass == null || !TestCase.class.isAssignableFrom(rawClass)) {
      return;
    }

    @SuppressWarnings("unchecked")
    Class<? extends TestCase> clazz = (Class<? extends TestCase>) rawClass;

    int modifiers = clazz.getModifiers();

    if (Modifier.isAbstract(modifiers) || !Modifier.isPublic(modifiers)) {
      return;
    }

    if (onlyRun.size() > 0 && !onlyRun.contains(rawClass.getSimpleName())) {
      return;
    }

    if (isIgnored(clazz)) {
      System.err.println(
          "Ignoring test class: " + clazz + ": " + clazz.getAnnotation(Ignore.class).reason());
      return;
    }

    if (!withDriver && NeedsDriver.class.isAssignableFrom(clazz)) {
      return;
    }

    boolean include = true;
    if (patterns.size() > 0) {
      include = false;
      for (String pattern : patterns) {
        include |= clazz.getName().matches(pattern);
      }
    }
    if (!include) {
      return;
    }

    for (String excludePattern : excludePatterns) {
      if (clazz.getName().matches(excludePattern)) {
        return;
      }
    }

    Method[] methods = clazz.getMethods();
    for (Method method : methods) {
      if (isTestMethod(method)) {
        Test test = TestSuite.createTest(clazz, method.getName());
        if (test instanceof NeedsDriver) {
          boolean freshDriver = false;
          if (method.isAnnotationPresent(NeedsFreshDriver.class)) {
            freshDriver = true;
          }

          boolean restartDriver = false;
          if (method.isAnnotationPresent(NoDriverAfterTest.class)) {
            restartDriver = true;
          }

          if (withDriver) {
            test =
                new DriverTestDecorator(test, driverClass, keepDriver, freshDriver, restartDriver);
          }
        }
        if (outputTestNames) {
          test = new TestNameDecorator(test);
        }
        suite.addTest(test);
      }
    }
  }
  public static void main(String[] args) throws Exception {
    System.out.println(
        "Checking that all known MBeans that are "
            + "NotificationBroadcasters have sane "
            + "MBeanInfo.getNotifications()");

    System.out.println("Checking platform MBeans...");
    checkPlatformMBeans();

    URL codeBase = ClassLoader.getSystemResource("javax/management/MBeanServer.class");
    if (codeBase == null) {
      throw new Exception("Could not determine codeBase for " + MBeanServer.class);
    }

    System.out.println();
    System.out.println("Looking for standard MBeans...");
    String[] classes = findStandardMBeans(codeBase);

    System.out.println("Testing standard MBeans...");
    for (int i = 0; i < classes.length; i++) {
      String name = classes[i];
      Class<?> c;
      try {
        c = Class.forName(name);
      } catch (Throwable e) {
        System.out.println(name + ": cannot load (not public?): " + e);
        continue;
      }
      if (!NotificationBroadcaster.class.isAssignableFrom(c)) {
        System.out.println(name + ": not a NotificationBroadcaster");
        continue;
      }
      if (Modifier.isAbstract(c.getModifiers())) {
        System.out.println(name + ": abstract class");
        continue;
      }

      NotificationBroadcaster mbean;
      Constructor<?> constr;
      try {
        constr = c.getConstructor();
      } catch (Exception e) {
        System.out.println(name + ": no public no-arg constructor: " + e);
        continue;
      }
      try {
        mbean = (NotificationBroadcaster) constr.newInstance();
      } catch (Exception e) {
        System.out.println(name + ": no-arg constructor failed: " + e);
        continue;
      }

      check(mbean);
    }

    System.out.println();
    System.out.println("Testing some explicit cases...");

    check(new RelationService(false));
    /*
      We can't do this:
        check(new RequiredModelMBean());
      because the Model MBean spec more or less forces us to use the
      names GENERIC and ATTRIBUTE_CHANGE for its standard notifs.
    */
    checkRMIConnectorServer();

    System.out.println();
    if (!suspicious.isEmpty()) System.out.println("SUSPICIOUS CLASSES: " + suspicious);

    if (failed.isEmpty()) System.out.println("TEST PASSED");
    else {
      System.out.println("TEST FAILED: " + failed);
      System.exit(1);
    }
  }
 protected void loadHttpServlet(final AnyValue conf, final ClassFilter<? extends Servlet> filter)
     throws Exception {
   final StringBuilder sb = logger.isLoggable(Level.INFO) ? new StringBuilder() : null;
   final String prefix = conf == null ? "" : conf.getValue("path", "");
   final String threadName = "[" + Thread.currentThread().getName() + "] ";
   List<FilterEntry<? extends Servlet>> list = new ArrayList(filter.getFilterEntrys());
   list.sort(
       (FilterEntry<? extends Servlet> o1,
           FilterEntry<? extends Servlet>
               o2) -> { // 必须保证WebSocketServlet优先加载, 因为要确保其他的HttpServlet可以注入本地模式的WebSocketNode
         boolean ws1 = WebSocketServlet.class.isAssignableFrom(o1.getType());
         boolean ws2 = WebSocketServlet.class.isAssignableFrom(o2.getType());
         if (ws1 == ws2) return o1.getType().getName().compareTo(o2.getType().getName());
         return ws1 ? -1 : 1;
       });
   final List<AbstractMap.SimpleEntry<String, String[]>> ss =
       sb == null ? null : new ArrayList<>();
   for (FilterEntry<? extends Servlet> en : list) {
     Class<HttpServlet> clazz = (Class<HttpServlet>) en.getType();
     if (Modifier.isAbstract(clazz.getModifiers())) continue;
     WebServlet ws = clazz.getAnnotation(WebServlet.class);
     if (ws == null || ws.value().length == 0) continue;
     final HttpServlet servlet = clazz.newInstance();
     resourceFactory.inject(servlet, this);
     final String[] mappings = ws.value();
     String pref = ws.repair() ? prefix : "";
     DefaultAnyValue servletConf = (DefaultAnyValue) en.getProperty();
     WebInitParam[] webparams = ws.initParams();
     if (webparams.length > 0) {
       if (servletConf == null) servletConf = new DefaultAnyValue();
       for (WebInitParam webparam : webparams) {
         servletConf.addValue(webparam.name(), webparam.value());
       }
     }
     this.httpServer.addHttpServlet(servlet, pref, servletConf, mappings);
     if (ss != null) {
       for (int i = 0; i < mappings.length; i++) {
         mappings[i] = pref + mappings[i];
       }
       ss.add(new AbstractMap.SimpleEntry<>(clazz.getName(), mappings));
     }
   }
   if (ss != null) {
     Collections.sort(
         ss,
         (AbstractMap.SimpleEntry<String, String[]> o1,
             AbstractMap.SimpleEntry<String, String[]> o2) -> o1.getKey().compareTo(o2.getKey()));
     int max = 0;
     for (AbstractMap.SimpleEntry<String, String[]> as : ss) {
       if (as.getKey().length() > max) max = as.getKey().length();
     }
     for (AbstractMap.SimpleEntry<String, String[]> as : ss) {
       sb.append(threadName).append(" Loaded ").append(as.getKey());
       for (int i = 0; i < max - as.getKey().length(); i++) {
         sb.append(' ');
       }
       sb.append("  mapping to  ").append(Arrays.toString(as.getValue())).append(LINE_SEPARATOR);
     }
   }
   if (sb != null && sb.length() > 0) logger.log(Level.INFO, sb.toString());
 }
  private <T> Class<? extends T> generateUnderLock(Class<T> type) {
    Map<Class<?>, Class<?>> cache = GENERATED_CLASSES.get(getClass());
    if (cache == null) {
      // WeakHashMap won't work here. It keeps a strong reference to the mapping value, which is the
      // generated class in this case
      // However, the generated class has a strong reference to the source class (by extending it),
      // so the keys will always be
      // strongly reachable while this Class is strongly reachable. Use weak references for both key
      // and value of the mapping instead.
      cache = new ReferenceMap(AbstractReferenceMap.WEAK, AbstractReferenceMap.WEAK);
      GENERATED_CLASSES.put(getClass(), cache);
    }
    Class<?> generatedClass = cache.get(type);
    if (generatedClass != null) {
      return generatedClass.asSubclass(type);
    }

    if (Modifier.isPrivate(type.getModifiers())) {
      throw new GradleException(
          String.format(
              "Cannot create a proxy class for private class '%s'.", type.getSimpleName()));
    }
    if (Modifier.isAbstract(type.getModifiers())) {
      throw new GradleException(
          String.format(
              "Cannot create a proxy class for abstract class '%s'.", type.getSimpleName()));
    }

    Class<? extends T> subclass;
    try {
      ClassMetaData classMetaData = inspectType(type);

      ClassBuilder<T> builder = start(type, classMetaData);

      builder.startClass();

      if (!DynamicObjectAware.class.isAssignableFrom(type)) {
        if (ExtensionAware.class.isAssignableFrom(type)) {
          throw new UnsupportedOperationException(
              "A type that implements ExtensionAware must currently also implement DynamicObjectAware.");
        }
        builder.mixInDynamicAware();
      }
      if (!GroovyObject.class.isAssignableFrom(type)) {
        builder.mixInGroovyObject();
      }
      builder.addDynamicMethods();
      if (classMetaData.conventionAware && !IConventionAware.class.isAssignableFrom(type)) {
        builder.mixInConventionAware();
      }

      Class noMappingClass = Object.class;
      for (Class<?> c = type; c != null && noMappingClass == Object.class; c = c.getSuperclass()) {
        if (c.getAnnotation(NoConventionMapping.class) != null) {
          noMappingClass = c;
        }
      }

      Set<PropertyMetaData> conventionProperties = new HashSet<PropertyMetaData>();

      for (PropertyMetaData property : classMetaData.properties.values()) {
        if (SKIP_PROPERTIES.contains(property.name)) {
          continue;
        }

        if (property.injector) {
          builder.addInjectorProperty(property);
          for (Method getter : property.getters) {
            builder.applyServiceInjectionToGetter(property, getter);
          }
          for (Method setter : property.setters) {
            builder.applyServiceInjectionToSetter(property, setter);
          }
          continue;
        }

        boolean needsConventionMapping = false;
        if (classMetaData.isExtensible()) {
          for (Method getter : property.getters) {
            if (!Modifier.isFinal(getter.getModifiers())
                && !getter.getDeclaringClass().isAssignableFrom(noMappingClass)) {
              needsConventionMapping = true;
              break;
            }
          }
        }

        if (needsConventionMapping) {
          conventionProperties.add(property);
          builder.addConventionProperty(property);
          for (Method getter : property.getters) {
            builder.applyConventionMappingToGetter(property, getter);
          }
        }

        if (needsConventionMapping) {
          for (Method setter : property.setters) {
            if (!Modifier.isFinal(setter.getModifiers())) {
              builder.applyConventionMappingToSetter(property, setter);
            }
          }
        }
      }

      Set<Method> actionMethods = classMetaData.missingOverloads;
      for (Method method : actionMethods) {
        builder.addActionMethod(method);
      }

      // Adds a set method for each mutable property
      for (PropertyMetaData property : classMetaData.properties.values()) {
        if (property.setters.isEmpty()) {
          continue;
        }
        if (Iterable.class.isAssignableFrom(property.getType())) {
          // Currently not supported
          continue;
        }

        if (property.setMethods.isEmpty()) {
          for (Method setter : property.setters) {
            builder.addSetMethod(property, setter);
          }
        } else if (conventionProperties.contains(property)) {
          for (Method setMethod : property.setMethods) {
            builder.applyConventionMappingToSetMethod(property, setMethod);
          }
        }
      }

      for (Constructor<?> constructor : type.getConstructors()) {
        if (Modifier.isPublic(constructor.getModifiers())) {
          builder.addConstructor(constructor);
        }
      }

      subclass = builder.generate();
    } catch (Throwable e) {
      throw new GradleException(
          String.format("Could not generate a proxy class for class %s.", type.getName()), e);
    }

    cache.put(type, subclass);
    cache.put(subclass, subclass);
    return subclass;
  }
 @Test
 public void testModifiers() throws Exception {
   for (Class<?> type : standardTypes) {
     assertThat(describe(type).getModifiers(), is(type.getModifiers()));
   }
 }
Beispiel #28
0
  /**
   * Instantiate a new {@link ADDFFunctionalGroupHandler} given its class name
   *
   * @param theInterface
   * @return
   * @throws ClassNotFoundException
   * @throws NoSuchMethodException
   * @throws SecurityException
   * @throws InvocationTargetException
   * @throws IllegalArgumentException
   * @throws IllegalAccessException
   * @throws InstantiationException
   */
  @SuppressWarnings("unchecked")
  protected <I> I newHandler(Class<I> theInterface) {
    if (theInterface == null) return null;

    String className = null;

    try {
      className = Config.getValueWithGlobalDefault(this.getEngine(), theInterface.getSimpleName());
      mLog.info(">>> className = " + className);
      if (Strings.isNullOrEmpty(className)) {
        mLog.error(
            String.format(
                "Cannot determine classname for %s from configuration source [%s] %s",
                theInterface.getSimpleName(),
                Config.getConfigHandler().getSource(),
                this.getEngine()));
        return null;
      }

      Class<?> clazz = Class.forName(className);

      if (Modifier.isAbstract(clazz.getModifiers())) {
        throw new InstantiationError(
            String.format("Class %s is abstract and cannot be instantiated", className));
      }

      Constructor<ADDFFunctionalGroupHandler> cons =
          (Constructor<ADDFFunctionalGroupHandler>)
              clazz.getDeclaredConstructor(new Class<?>[] {DDF.class});

      if (cons != null) cons.setAccessible(true);

      return cons != null ? (I) cons.newInstance(this) : null;

    } catch (ClassNotFoundException cnfe) {
      mLog.error(
          String.format(
              "Cannot instantiate handler for [%s] %s/%s",
              this.getEngine(), theInterface.getSimpleName(), className),
          cnfe);
    } catch (NoSuchMethodException nsme) {
      mLog.error(
          String.format(
              "Cannot instantiate handler for [%s] %s/%s",
              this.getEngine(), theInterface.getSimpleName(), className),
          nsme);
    } catch (IllegalAccessException iae) {
      mLog.error(
          String.format(
              "Cannot instantiate handler for [%s] %s/%s",
              this.getEngine(), theInterface.getSimpleName(), className),
          iae);
    } catch (InstantiationException ie) {
      mLog.error(
          String.format(
              "Cannot instantiate handler for [%s] %s/%s",
              this.getEngine(), theInterface.getSimpleName(), className),
          ie);
    } catch (InvocationTargetException ite) {
      mLog.error(
          String.format(
              "Cannot instantiate handler for [%s] %s/%s",
              this.getEngine(), theInterface.getSimpleName(), className),
          ite);
    }
    return null;
  }
 private static Object createPlaceholder(Class<?> clazz, InvocationSequence invocationSequence) {
   return !Modifier.isFinal(clazz.getModifiers())
       ? createProxy(new ProxyArgument(clazz, invocationSequence), clazz, false)
       : createArgumentPlaceholder(clazz);
 }
Beispiel #30
0
  private static void discoverAccessibleMethods(
      Class<?> clazz,
      Map<MethodSignature, Method> map,
      boolean includeProtected,
      boolean includePrivate) {
    if (Modifier.isPublic(clazz.getModifiers()) || includePrivate) {
      try {
        if (includeProtected || includePrivate) {
          while (clazz != null) {
            try {
              Method[] methods = clazz.getDeclaredMethods();
              for (int i = 0; i < methods.length; i++) {
                Method method = methods[i];
                int mods = method.getModifiers();

                if (Modifier.isPublic(mods) || Modifier.isProtected(mods) || includePrivate) {
                  if (includePrivate) method.setAccessible(true);
                  map.put(new MethodSignature(method), method);
                }
              }
              clazz = clazz.getSuperclass();
            } catch (SecurityException e) {
              // Some security settings (i.e., applets) disallow
              // access to Class.getDeclaredMethods. Fall back to
              // Class.getMethods.
              Method[] methods = clazz.getMethods();
              for (int i = 0; i < methods.length; i++) {
                Method method = methods[i];
                MethodSignature sig = new MethodSignature(method);
                if (map.get(sig) == null) map.put(sig, method);
              }
              break; // getMethods gets superclass methods, no
              // need to loop any more
            }
          }
        } else {
          Method[] methods = clazz.getMethods();
          for (int i = 0; i < methods.length; i++) {
            Method method = methods[i];
            MethodSignature sig = new MethodSignature(method);
            map.put(sig, method);
          }
        }
        return;
      } catch (SecurityException e) {
        Context.reportWarning(
            "Could not discover accessible methods of class "
                + clazz.getName()
                + " due to lack of privileges, "
                + "attemping superclasses/interfaces.");
        // Fall through and attempt to discover superclass/interface
        // methods
      }
    }

    Class<?>[] interfaces = clazz.getInterfaces();
    for (int i = 0; i < interfaces.length; i++) {
      discoverAccessibleMethods(interfaces[i], map, includeProtected, includePrivate);
    }
    Class<?> superclass = clazz.getSuperclass();
    if (superclass != null) {
      discoverAccessibleMethods(superclass, map, includeProtected, includePrivate);
    }
  }