private static Class<?>[] getObjectInterfaces(Class<?> objectClass, List<Class<?>> interfaces) {
   // Rq: object.getClass().getInterfaces() ne suffit pas pour Connection dans Tomcat
   // car la connection est une instance de PoolGuardConnectionWrapper
   // et connection.getClass().getInterfaces() est vide dans ce cas
   final List<Class<?>> myInterfaces;
   if (interfaces == null) {
     myInterfaces = new ArrayList<Class<?>>(Arrays.asList(objectClass.getInterfaces()));
     Class<?> classe = objectClass.getSuperclass();
     while (classe != null) {
       final Class<?>[] classInterfaces = classe.getInterfaces();
       if (classInterfaces.length > 0) {
         final List<Class<?>> superInterfaces = Arrays.asList(classInterfaces);
         // removeAll d'abord car il ne faut pas de doublon dans la liste
         myInterfaces.removeAll(superInterfaces);
         myInterfaces.addAll(superInterfaces);
       }
       classe = classe.getSuperclass();
     }
     // on ignore l'interface javax.naming.Referenceable car sinon le rebind sous jetty appelle
     // referenceable.getReference() et devient inutile
     myInterfaces.remove(Referenceable.class);
   } else {
     myInterfaces = interfaces;
   }
   return myInterfaces.toArray(new Class<?>[myInterfaces.size()]);
 }
Example #2
1
  private void extractClassIntoMaps(Class type, boolean foundName, Supplier supplier) {

    if (type == null) {
      return;
    }
    String named = null;

    Class superClass = type.getSuperclass();

    Class[] superTypes = type.getInterfaces();

    for (Class superType : superTypes) {
      this.supplierTypeMap.put(superType, supplier);
    }

    while (superClass != Object.class) {
      this.supplierTypeMap.put(superClass, supplier);

      if (!foundName) {
        named = NamedUtils.namedValueForClass(superClass);
        if (named != null) {
          supplierNameMap.put(named, new ProviderInfo(named, type, supplier, null));
          foundName = true;
        }
      }

      superTypes = type.getInterfaces();
      for (Class superType : superTypes) {
        this.supplierTypeMap.put(superType, supplier);
      }
      superClass = superClass.getSuperclass();
    }
  }
Example #3
1
 private static ArrayList<Class<?>> getAllInterfaces(Class<?> c) {
   ArrayList<Class<?>> allInterfaces = new ArrayList<Class<?>>();
   if (!c.isInterface() && c.getInterfaces().length == 0) {
     allInterfaces.addAll(getAllInterfaces(c.getSuperclass()));
   } else {
     allInterfaces.addAll(Arrays.asList(c.getInterfaces()));
   }
   return allInterfaces;
 }
Example #4
1
 public ModuleManager createModuleManagerProxy(
     PluginVersionReference pluginVersionReference, InvocationHandler invocationHandler)
     throws CantCreateProxyException {
   ModuleManager moduleManager = null;
   if (!openModules.containsKey(pluginVersionReference)) {
     try {
       ModuleManager moduleManagerBase =
           FermatSystem.getInstance().getModuleManager2(pluginVersionReference);
       if (moduleManagerBase == null)
         throw new RuntimeException(
             "Module manager null in platform, please check if your plugin is connected, pluginVersionReference: "
                 + pluginVersionReference.toString3());
       Class clazz = moduleManagerBase.getClass();
       moduleManager =
           (ModuleManager)
               Proxy.newProxyInstance(
                   clazz.getClassLoader(), clazz.getInterfaces(), invocationHandler);
       openModules.put(clazz, moduleManager);
     } catch (CantGetModuleManagerException e) {
       try {
         Class clazz = FermatSystem.getInstance().getModuleManager3(pluginVersionReference);
         if (clazz == null)
           throw new RuntimeException(
               "Module manager null in platform, please check if your plugin is connected, pluginVersionReference: "
                   + pluginVersionReference.toString3());
         moduleManager =
             (ModuleManager)
                 Proxy.newProxyInstance(
                     clazz.getClassLoader(), clazz.getInterfaces(), invocationHandler);
         openModules.put(clazz, moduleManager);
       } catch (Exception e2) {
         Log.e(
             TAG,
             "Cant get module manager in platform, please check if your plugin is connected, pluginVersionReference: "
                 + pluginVersionReference.toString3());
         throw new CantCreateProxyException(
             "Cant get module manager from system", e, "factory", "");
       }
     } catch (ModuleManagerNotFoundException e) {
       Log.e(
           TAG,
           "Cant get module manager in platform, please check if your plugin is connected, pluginVersionReference: "
               + pluginVersionReference.toString3());
       throw new CantCreateProxyException(
           "Cant fount module manager from system", e, "factory", "");
     }
   } else {
     moduleManager = openModules.get(pluginVersionReference);
   }
   //        Log.i(TAG,"interfaces: ");
   //        for (Class<?> aClass : moduleManager.getClass().getInterfaces()) {
   //            Log.i(TAG,aClass.getName());
   //        }
   return moduleManager;
 }
Example #5
1
 public ClassDefinition(Class<?> cls) {
   this.definedClass = cls;
   this.setClassName(cls.getCanonicalName());
   this.setSuperClass(cls.getSuperclass() != null ? cls.getSuperclass().getCanonicalName() : null);
   String[] interfaces = new String[cls.getInterfaces().length];
   int i = 0;
   for (Class<?> interfaze : cls.getInterfaces()) {
     interfaces[i++] = interfaze.getCanonicalName();
   }
   this.setInterfaces(interfaces);
 }
Example #6
1
 private boolean checkAnonymous(Class<?> target) {
   if (!target.isAnonymousClass()) {
     return false;
   }
   if (target.getSuperclass() != Object.class && target.getSuperclass() == javaClass) {
     return true;
   }
   if (target.getInterfaces().length == 1 && target.getInterfaces()[0] == javaClass) {
     return true;
   }
   return false;
 }
Example #7
1
  /**
   * Returns the generic supertype for {@code supertype}. For example, given a class {@code
   * IntegerSet}, the result for when supertype is {@code Set.class} is {@code Set<Integer>} and the
   * result when the supertype is {@code Collection.class} is {@code Collection<Integer>}.
   */
  static Type getGenericSupertype(Type context, Class<?> rawType, Class<?> toResolve) {
    if (toResolve == rawType) {
      return context;
    }

    // we skip searching through interfaces if unknown is an interface
    if (toResolve.isInterface()) {
      Class<?>[] interfaces = rawType.getInterfaces();
      for (int i = 0, length = interfaces.length; i < length; i++) {
        if (interfaces[i] == toResolve) {
          return rawType.getGenericInterfaces()[i];
        } else if (toResolve.isAssignableFrom(interfaces[i])) {
          return getGenericSupertype(rawType.getGenericInterfaces()[i], interfaces[i], toResolve);
        }
      }
    }

    // check our supertypes
    if (!rawType.isInterface()) {
      while (rawType != Object.class) {
        Class<?> rawSupertype = rawType.getSuperclass();
        if (rawSupertype == toResolve) {
          return rawType.getGenericSuperclass();
        } else if (toResolve.isAssignableFrom(rawSupertype)) {
          return getGenericSupertype(rawType.getGenericSuperclass(), rawSupertype, toResolve);
        }
        rawType = rawSupertype;
      }
    }

    // we can't resolve this further
    return toResolve;
  }
Example #8
1
  @SuppressWarnings("unchecked")
  static void annotatedWith(Set<Class<?>> contracts, Object obj, Class annotation) {
    if (null != obj) {
      Class<?> clazz = obj.getClass();

      while (Object.class != clazz) {
        if (!clazz.isAnonymousClass()) {
          Object t = clazz.getAnnotation(annotation);
          if (null != t) {
            contracts.add(clazz);
          } else {
            annotatedWith(contracts, annotation, clazz);
          }

          for (Class<?> iface : clazz.getInterfaces()) {
            t = iface.getAnnotation(annotation);
            if (null != t) {
              contracts.add(iface);
            } else {
              annotatedWith(contracts, annotation, iface);
            }
          }
        }

        clazz = clazz.getSuperclass();
      }
    }
  }
Example #9
0
 private Class<?> getInterface(Object obj) {
   Class<?> newInterface = obj.getClass();
   Class<?> parent = newInterface;
   while (parent != null) {
     parent = null;
     if (newInterface.getInterfaces().length > 0) {
       Class<?> newParent = newInterface.getInterfaces()[0];
       if (newParent.getPackage().getName().startsWith("org.")) {
         parent = newInterface = newParent;
       }
     }
   }
   return newInterface;
 }
Example #10
0
  /**
   * Format a string buffer containing the Class, Interfaces, CodeSource, and ClassLoader
   * information for the given object clazz.
   *
   * @param clazz the Class
   * @param results, the buffer to write the info to
   */
  public static void displayClassInfo(Class clazz, StringBuffer results) {
    // Print out some codebase info for the ProbeHome
    ClassLoader cl = clazz.getClassLoader();
    results.append("\n" + clazz.getName() + ".ClassLoader=" + cl);
    ClassLoader parent = cl;
    while (parent != null) {
      results.append("\n.." + parent);
      URL[] urls = getClassLoaderURLs(parent);
      int length = urls != null ? urls.length : 0;
      for (int u = 0; u < length; u++) {
        results.append("\n...." + urls[u]);
      }
      if (parent != null) parent = parent.getParent();
    }
    CodeSource clazzCS = clazz.getProtectionDomain().getCodeSource();
    if (clazzCS != null) results.append("\n++++CodeSource: " + clazzCS);
    else results.append("\n++++Null CodeSource");

    results.append("\nImplemented Interfaces:");
    Class[] ifaces = clazz.getInterfaces();
    for (int i = 0; i < ifaces.length; i++) {
      results.append("\n++" + ifaces[i]);
      ClassLoader loader = ifaces[i].getClassLoader();
      results.append("\n++++ClassLoader: " + loader);
      ProtectionDomain pd = ifaces[i].getProtectionDomain();
      CodeSource cs = pd.getCodeSource();
      if (cs != null) results.append("\n++++CodeSource: " + cs);
      else results.append("\n++++Null CodeSource");
    }
  }
Example #11
0
  public static External getExternalFor(final Method method, final Class<?> clazz) {
    requireNonNull(method);
    requireNonNull(clazz);
    if (method == null || clazz == null) {
      return null;
    }

    final External e = method.getAnnotation(External.class);
    if (e != null) {
      return e;
    }
    // Also try the superClass and all the interfaces it implements
    final List<Class<?>> classCandidates = new ArrayList<>(Arrays.asList(clazz.getInterfaces()));
    final Class<?> superClass = clazz.getSuperclass();

    if (superClass != null) {
      classCandidates.add(superClass);
    }

    for (final Class<?> classCandidate : classCandidates) {
      try {
        return getExternalFor(
            classCandidate.getMethod(method.getName(), method.getParameterTypes()), classCandidate);
      } catch (NoSuchMethodException | SecurityException ex) {
      }
    }

    return null;
  }
Example #12
0
 private static Map<String, Method> addMethods(
     Map<String, Method> methods, Class<?> clazz, Predicate<Method> filter) {
   requireNonNull(methods);
   requireNonNull(filter);
   // clazz nullable (why?)
   if (clazz == Object.class) {
     return methods;
   }
   if (clazz == null) {
     return methods;
   }
   Stream.of(clazz.getDeclaredMethods())
       .filter(filter)
       .forEach(
           m -> {
             methods.putIfAbsent(m.getName(), m); // Put only the most recent
             // concrete version of the
             // method
           });
   addMethods(methods, clazz.getSuperclass(), filter); // Recursively add
   // the superclass
   // methods
   Stream.of(clazz.getInterfaces())
       .forEach(
           i -> {
             addMethods(methods, i, filter); // Recursively add the extended
             // interfaces (because they can
             // contain default methods)
           });
   return methods;
 }
 private void inspect() {
   managerModCount = manager.getModCount();
   // first global, then type level, then method level
   // but later one can override pre (for same annotation)
   List<Annotation> typeLevel = new ArrayList<Annotation>();
   Class<?> serviceType = serviceClass;
   while (serviceType != null) {
     for (Annotation ann : serviceType.getAnnotations()) {
       if (ann.annotationType().isAnnotationPresent(AcServiceIntercepted.class)) {
         putOrAppendAnnotation(typeLevel, ann);
       }
     }
     Class<?> theType = serviceType;
     serviceType = null;
     for (Class<?> superInf : theType.getInterfaces()) {
       if (AcService.class.isAssignableFrom(superInf)) {
         serviceType = superInf;
         break;
       }
     }
   }
   for (Method method : serviceClass.getMethods()) {
     List<Annotation> annList = new ArrayList<Annotation>(typeLevel);
     for (Annotation ann : method.getAnnotations()) {
       if (ann.annotationType().isAnnotationPresent(AcServiceIntercepted.class)) {
         putOrAppendAnnotation(annList, ann);
       }
     }
     methodAnnotationList.put(method, annList);
     setupRuntimeInterceptorList(method);
   }
 }
  /**
   * Find an element in the list.
   *
   * <p>This is a little more complex than the simple lookup since it might be that we are indexing
   * with a class and the list contains interfaces.
   *
   * <p>Since the hashtable lookup is a lot faster than the linear search we add the result of the
   * linear search to the hashtable so that the next time we need not do it.
   *
   * @return Checklist or null if noone exist.
   * @param cls the class to lookup.
   */
  private static Checklist lookupChecklist(Class cls) {
    if (lists.contains(cls)) {
      return (Checklist) lists.get(cls);
    }

    // Now lets search
    Enumeration enumeration = lists.keys();

    while (enumeration.hasMoreElements()) {
      Object clazz = enumeration.nextElement();

      Class[] intfs = cls.getInterfaces();
      for (int i = 0; i < intfs.length; i++) {
        if (intfs[i].equals(clazz)) {
          // We found it!
          Checklist chlist = (Checklist) lists.get(clazz);

          // Enter the class to speed up the next search.
          lists.put(cls, chlist);
          return chlist;
        }
      }
    }

    return null;
  }
Example #15
0
  @Override
  public synchronized T get(Object key) {
    Class<?> clazz = (Class<?>) key;
    if (_cache.containsKey(clazz)) {
      // Could be null
      return _cache.get(key);
    }

    if (clazz.getSuperclass() != null) {
      T value = get(clazz.getSuperclass());
      if (value != null) {
        addValueToCache(clazz, value);
        return value;
      }
    }

    for (Class<?> intface : clazz.getInterfaces()) {
      T value = get(intface);
      if (value != null) {
        addValueToCache(clazz, value);
        return value;
      }
    }

    addValueToCache(clazz, null);
    return null;
  }
 private Callback createReverseEngineeredCallbackOfProperType(
     Callback callback, int index, Map callbackIndexMap) {
   Class iface = null;
   Class[] interfaces = callback.getClass().getInterfaces();
   for (int i = 0; i < interfaces.length; i++) {
     if (Callback.class.isAssignableFrom(interfaces[i])) {
       iface = interfaces[i];
       if (iface == Callback.class) {
         ConversionException exception = new ConversionException("Cannot handle CGLIB callback");
         exception.add("CGLIB callback type", callback.getClass().getName());
         throw exception;
       }
       interfaces = iface.getInterfaces();
       if (Arrays.asList(interfaces).contains(Callback.class)) {
         break;
       }
       i = -1;
     }
   }
   return (Callback)
       Proxy.newProxyInstance(
           iface.getClassLoader(),
           new Class[] {iface},
           new ReverseEngineeringInvocationHandler(index, callbackIndexMap));
 }
Example #17
0
  private Properties _getProperties(String fileName) {
    if (Validator.isNull(fileName)) {
      fileName = PATCHER_PROPERTIES;
    }

    Properties properties = new Properties();

    Class<?> clazz = getClass();

    if (Objects.equals(fileName, PATCHER_SERVICE_PROPERTIES)) {
      clazz = clazz.getInterfaces()[0];
    }

    ClassLoader classLoader = clazz.getClassLoader();

    InputStream inputStream = classLoader.getResourceAsStream(fileName);

    if (inputStream == null) {
      if (_log.isDebugEnabled()) {
        _log.debug("Unable to load " + fileName);
      }
    } else {
      try {
        properties.load(inputStream);
      } catch (IOException ioe) {
        _log.error(ioe, ioe);
      } finally {
        StreamUtil.cleanUp(inputStream);
      }
    }

    return properties;
  }
 /**
  * Verifies if the element is an instance of a class with a given class name. If direct match
  * fails, implementing interfaces will be tested, then recursively all superclasses and their
  * interfaces.
  */
 private boolean verifyClass(Object element, String className) {
   Class eclass = element.getClass();
   Class clazz = eclass;
   boolean match = false;
   while (clazz != null) {
     // test the class itself
     if (clazz.getName().equals(className)) {
       match = true;
       break;
     }
     // test all the interfaces it implements
     Class[] interfaces = clazz.getInterfaces();
     for (int i = 0; i < interfaces.length; i++) {
       if (interfaces[i].getName().equals(className)) {
         match = true;
         break;
       }
     }
     if (match == true) {
       break;
     }
     // get the superclass
     clazz = clazz.getSuperclass();
   }
   return match;
 }
Example #19
0
  /** Filters out hidden elements. */
  private static Object filterHidden(Object o, Class<?> expected) {
    if (o == null) {
      return null;
    }

    Class<?> type = o.getClass();
    if (type.getName().startsWith("com.sun.")) {
      // TODO: Implement interfaces from superclasses, too.
      return Proxy.newProxyInstance(
          type.getClassLoader(), type.getInterfaces(), new HideHandler(o));
    } else if (o instanceof Object[]) {
      Class<?> componentType = expected.getComponentType();
      Object[] array = (Object[]) o;
      List<Object> list = new ArrayList<Object>(array.length);
      for (Object entry : array) {
        if ((entry instanceof Doc) && isHidden((Doc) entry)) {
          continue;
        }
        list.add(filterHidden(entry, componentType));
      }
      return list.toArray((Object[]) Array.newInstance(componentType, list.size()));
    } else {
      return o;
    }
  }
Example #20
0
  /**
   * Checks whether the given class implements the given interface.
   *
   * @param intf the interface to look for in the given class
   * @param cls the class to check for the interface
   * @return TRUE if the class contains the interface
   */
  public static boolean hasInterface(Class intf, Class cls) {
    Class[] intfs;
    int i;
    boolean result;
    Class currentclass;

    result = false;
    currentclass = cls;
    do {
      // check all the interfaces, this class implements
      intfs = currentclass.getInterfaces();
      for (i = 0; i < intfs.length; i++) {
        if (intfs[i].equals(intf)) {
          result = true;
          break;
        }
      }

      // get parent class
      if (!result) {
        currentclass = currentclass.getSuperclass();

        // topmost class reached or no superclass?
        if ((currentclass == null) || (currentclass.equals(Object.class))) break;
      }
    } while (!result);

    return result;
  }
Example #21
0
 @Override
 public Object __tojava__(Class<?> c) {
   // Automatically coerce to single method interfaces
   if (c.isInstance(this) && c != InvocationHandler.class) {
     // for base types, conversion is simple - so don't wrap!
     // InvocationHandler is special, since it's a single method interface
     // that we implement, but if we coerce to it we want the arguments
     return c.cast(this);
   } else if (c.isInterface()) {
     if (c.getDeclaredMethods().length == 1 && c.getInterfaces().length == 0) {
       // Proper single method interface
       return proxy(c);
     } else {
       // Try coerce to interface with multiple overloaded versions of
       // the same method (name)
       String name = null;
       for (Method method : c.getMethods()) {
         if (method.getDeclaringClass() != Object.class) {
           if (name == null || name.equals(method.getName())) {
             name = method.getName();
           } else {
             name = null;
             break;
           }
         }
       }
       if (name != null) { // single unique method name
         return proxy(c);
       }
     }
   }
   return super.__tojava__(c);
 }
Example #22
0
  private void getInterfacePropertyDescriptors(
      Class<?> clazz, List<PropertyDescriptor> pds, Set<Class<?>> classes) {
    if (classes.contains(clazz)) {
      return;
    }

    classes.add(clazz);

    try {
      Class[] interfaces = clazz.getInterfaces();

      /** add base interface information */
      BeanInfo info = Introspector.getBeanInfo(clazz);
      for (int j = 0; j < info.getPropertyDescriptors().length; j++) {
        PropertyDescriptor pd = info.getPropertyDescriptors()[j];
        if (!containsPropertyName(pds, pd.getName())) {
          pds.add(pd);
        }
      }

      /** add extended interface information */
      for (int i = 0; i < interfaces.length; i++) {
        getInterfacePropertyDescriptors(interfaces[i], pds, classes);
      }
    } catch (IntrospectionException e) {
      // do nothing
    }
  }
Example #23
0
 public static void main(String[] args) {
   Class c = null;
   try {
     c = Class.forName("typeinfo.toys.FancyToy");
   } catch (ClassNotFoundException e) {
     print("Can't find FancyToy");
     System.exit(1);
   }
   printInfo(c);
   for (Class face : c.getInterfaces()) printInfo(face);
   Class up = c.getSuperclass();
   Object obj = null;
   try {
     // Requires default constructor in order to
     // create a super or Toy object:
     obj = up.newInstance();
   } catch (InstantiationException e) {
     print("Cannot instantiate");
     System.exit(1);
   } catch (IllegalAccessException i) {
     print("Cannot access");
     System.exit(1);
   }
   printInfo(obj.getClass());
 }
Example #24
0
  public static LinkedHashSet<String> findJars(LogicalPlan dag, Class<?>[] defaultClasses) {
    List<Class<?>> jarClasses = new ArrayList<Class<?>>();

    for (String className : dag.getClassNames()) {
      try {
        Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(className);
        jarClasses.add(clazz);
      } catch (ClassNotFoundException e) {
        throw new IllegalArgumentException("Failed to load class " + className, e);
      }
    }

    for (Class<?> clazz : Lists.newArrayList(jarClasses)) {
      // process class and super classes (super does not require deploy annotation)
      for (Class<?> c = clazz; c != Object.class && c != null; c = c.getSuperclass()) {
        // LOG.debug("checking " + c);
        jarClasses.add(c);
        jarClasses.addAll(Arrays.asList(c.getInterfaces()));
      }
    }

    jarClasses.addAll(Arrays.asList(defaultClasses));

    if (dag.isDebug()) {
      LOG.debug("Deploy dependencies: {}", jarClasses);
    }

    LinkedHashSet<String> localJarFiles = new LinkedHashSet<String>(); // avoid duplicates
    HashMap<String, String> sourceToJar = new HashMap<String, String>();

    for (Class<?> jarClass : jarClasses) {
      if (jarClass.getProtectionDomain().getCodeSource() == null) {
        // system class
        continue;
      }
      String sourceLocation =
          jarClass.getProtectionDomain().getCodeSource().getLocation().toString();
      String jar = sourceToJar.get(sourceLocation);
      if (jar == null) {
        // don't create jar file from folders multiple times
        jar = JarFinder.getJar(jarClass);
        sourceToJar.put(sourceLocation, jar);
        LOG.debug("added sourceLocation {} as {}", sourceLocation, jar);
      }
      if (jar == null) {
        throw new AssertionError("Cannot resolve jar file for " + jarClass);
      }
      localJarFiles.add(jar);
    }

    String libJarsPath = dag.getValue(LogicalPlan.LIBRARY_JARS);
    if (!StringUtils.isEmpty(libJarsPath)) {
      String[] libJars = StringUtils.splitByWholeSeparator(libJarsPath, LIB_JARS_SEP);
      localJarFiles.addAll(Arrays.asList(libJars));
    }

    LOG.info("Local jar file dependencies: " + localJarFiles);

    return localJarFiles;
  }
  @EventHandler
  public void openInventory(InventoryOpenEvent ioe) {
    if (!(ioe.getPlayer() instanceof Player)) {
      return;
    }

    Player player = (Player) ioe.getPlayer();
    Game game = Main.getInstance().getGameManager().getGameOfPlayer(player);

    if (game == null) {
      return;
    }

    if (game.getState() != GameState.RUNNING) {
      return;
    }

    if (ioe.getInventory().getType() == InventoryType.ENCHANTING
        || ioe.getInventory().getType() == InventoryType.BREWING
        || (ioe.getInventory().getType() == InventoryType.CRAFTING
            && !Main.getInstance().getBooleanConfig("allow-crafting", false))) {
      ioe.setCancelled(true);
      return;
    } else if (ioe.getInventory().getType() == InventoryType.CRAFTING
        && Main.getInstance().getBooleanConfig("allow-crafting", false)) {
      return;
    }

    if (game.isSpectator(player)) {
      if (ioe.getInventory().getName().equals(Main._l("ingame.spectator"))) {
        return;
      }

      ioe.setCancelled(true);
    }

    if (ioe.getInventory().getHolder() == null) {
      return;
    }

    if (game.getRegion().getInventories().contains(ioe.getInventory())) {
      return;
    }

    InventoryHolder holder = ioe.getInventory().getHolder();
    for (Class<?> interfaze : holder.getClass().getInterfaces()) {

      if (interfaze.equals(BlockState.class)) {
        game.getRegion().addInventory(ioe.getInventory());
        return;
      }

      for (Class<?> interfaze2 : interfaze.getInterfaces()) {
        if (interfaze2.equals(BlockState.class)) {
          game.getRegion().addInventory(ioe.getInventory());
          return;
        }
      }
    }
  }
    private static Optional<Method> lookup(
        Class<?> sourceClass, String methodName, Class<?>[] parameterTypes) {
      Method match;
      try {
        match = sourceClass.getMethod(methodName, parameterTypes);
      } catch (NoSuchMethodException e) {
        return Optional.absent();
      }

      LinkedList<Class<?>> queue = new LinkedList<Class<?>>();
      queue.add(sourceClass);
      while (!queue.isEmpty()) {
        Class<?> c = queue.removeFirst();
        try {
          match = c.getMethod(methodName, parameterTypes);
        } catch (NoSuchMethodException e) {
          // ignore
        }
        for (Class<?> interfaceType : c.getInterfaces()) {
          queue.addFirst(interfaceType);
        }
        if (c.getSuperclass() != null) {
          queue.addFirst(c.getSuperclass());
        }
      }
      match.setAccessible(true);
      return Optional.of(match);
    }
Example #27
0
 /**
  * Looks for classpath contexts matching the class name or any super class or interface.
  *
  * @param clazz the class leaf to look for contexts
  * @return all files matching the class name but ending in .xml for all impls and interfaces
  */
 public static List<String> getClasspathContexts(Class<?> clazz) {
   List<String> names = new ArrayList<String>();
   for (Class<?> current = clazz; current != null; current = current.getSuperclass())
     checkClass(names, current);
   for (Class<?> current : clazz.getInterfaces()) checkClass(names, current);
   return names;
 }
  @SuppressWarnings("unchecked")
  static Class<? extends Event<?>> getEventClass(Class<?> handlerClass) {

    for (Class<?> i : handlerClass.getInterfaces()) {
      if (EventHandler.class.equals(i)) {
        for (Type t : handlerClass.getGenericInterfaces()) {
          if (t instanceof ParameterizedType) {
            ParameterizedType pt = (ParameterizedType) t;
            if (EventHandler.class.equals(pt.getRawType())) {

              return (Class<? extends Event<?>>) pt.getActualTypeArguments()[0];
            }
          }
        }
      } else if (EventHandler.class.isAssignableFrom(i)) {
        return getEventClass((Class<? extends EventHandler<?>>) i);
      }
    }

    if (EventHandler.class.isAssignableFrom(handlerClass.getSuperclass())) {
      return getEventClass((Class<?>) handlerClass.getSuperclass());
    }

    return null;
  }
Example #29
0
 public static Method findPreDestroyMethod(Class<?> c, String name) {
   if (Object.class == c || null == c) {
     return null;
   }
   for (Method m : c.getDeclaredMethods()) {
     if (name != null) {
       if (m.getName().equals(name)) {
         return m;
       }
     } else if (m.getAnnotation(PreDestroy.class) != null) {
       return m;
     }
   }
   Method m = findPreDestroyMethod(c.getSuperclass(), name);
   if (m != null) {
     return m;
   }
   for (Class<?> i : c.getInterfaces()) {
     m = findPreDestroyMethod(i, name);
     if (m != null) {
       return m;
     }
   }
   return null;
 }
Example #30
0
 private void addAllInterfaces(List<Class<?>> list, Class<?> clazz) {
   Class<?>[] interfaces = clazz.getInterfaces();
   for (Class<?> it : interfaces) {
     list.add(it);
     addAllInterfaces(list, it);
   }
 }