@SuppressWarnings("rawtypes")
 private <O extends Operator> O newInstance(Class<O> c) {
   if (c.isInterface()) {
     return null;
   }
   if (Modifier.isAbstract(c.getModifiers())) {
     return null;
   }
   final Class<?>[] paramTypes;
   final Object[] args;
   if (Modifier.isStatic(c.getModifiers())) {
     paramTypes = ArrayUtils.EMPTY_CLASS_ARRAY;
     args = ArrayUtils.EMPTY_OBJECT_ARRAY;
   } else {
     paramTypes = new Class[] {getClass()};
     args = new Object[] {this};
   }
   final Constructor<O> cs = ConstructorUtils.getMatchingAccessibleConstructor(c, paramTypes);
   if (cs == null) {
     return null;
   }
   try {
     return cs.newInstance(args);
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
Example #2
1
  /**
   * reads all methods by the action-annotations for building agent-actions
   *
   * @param p_class class
   * @param p_root root class
   * @return stream of all methods with inheritance
   */
  private static Stream<Method> methods(final Class<?> p_class, final Class<?> p_root) {
    final Pair<Boolean, IAgentAction.EAccess> l_classannotation = CCommon.isActionClass(p_class);
    if (!l_classannotation.getLeft())
      return p_class.getSuperclass() == null
          ? Stream.of()
          : methods(p_class.getSuperclass(), p_root);

    final Predicate<Method> l_filter =
        IAgentAction.EAccess.WHITELIST.equals(l_classannotation.getRight())
            ? i -> !CCommon.isActionFiltered(i, p_root)
            : i -> CCommon.isActionFiltered(i, p_root);

    return Stream.concat(
        Arrays.stream(p_class.getDeclaredMethods())
            .parallel()
            .map(
                i -> {
                  i.setAccessible(true);
                  return i;
                })
            .filter(i -> !Modifier.isAbstract(i.getModifiers()))
            .filter(i -> !Modifier.isInterface(i.getModifiers()))
            .filter(i -> !Modifier.isNative(i.getModifiers()))
            .filter(i -> !Modifier.isStatic(i.getModifiers()))
            .filter(l_filter),
        methods(p_class.getSuperclass(), p_root));
  }
    public boolean apply(Class<?> aClass) {
      // For JUnit3
      if (TestCase.class.isAssignableFrom((Class<?>) aClass)) {
        int modifiers = ((Class<?>) aClass).getModifiers();
        return Modifier.isPublic(modifiers)
            && !Modifier.isAbstract(modifiers)
            && hasValidConstructor((Class<?>) aClass);
      }

      // For JUnit4
      int modifiers = ((Class<?>) aClass).getModifiers();

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

      if (hasAnnotation(aClass, RunWith.class)) {
        return true;
      }

      if (hasSuiteMethod(aClass)) {
        return true;
      }

      if (hasAnnotatedMethod(aClass)) {
        return true;
      }

      return false;
    }
Example #4
0
  private final void bindResourceToLocalContainer(
      final Class<?> resource, final Class<?> container) {
    final Set<Method> nonAbstractMethods =
        Sets.newHashSet(resource.getMethods())
            .stream()
            .filter(method -> !Modifier.isAbstract(method.getModifiers()))
            .collect(Collectors.toSet());
    Preconditions.checkState(
        !nonAbstractMethods.isEmpty(),
        "Found non-abstract methods in " + resource + ": " + nonAbstractMethods);

    final Set<Method> abstractMethods =
        Sets.newHashSet(resource.getMethods())
            .stream()
            .filter(method -> Modifier.isAbstract(method.getModifiers()))
            .collect(Collectors.toSet());

    for (final Method resourceMethod : abstractMethods) {
      final Method containerMethod = findMatchingMethod(container, resourceMethod);
      if (containerMethod != null) {
        this.resourceToContainer.put(resourceMethod, containerMethod);
      }
    }

    bindResourceToContainer(resource, injector.getInstance(container));
  }
Example #5
0
 /*package*/ static boolean isModern(Class<? extends LoadStatistics> clazz) {
   // cannot use Util.isOverridden as these are protected methods.
   boolean hasGetNodes = false;
   boolean hasMatches = false;
   while (clazz != LoadStatistics.class && clazz != null && !(hasGetNodes && hasMatches)) {
     if (!hasGetNodes) {
       try {
         final Method getNodes = clazz.getDeclaredMethod("getNodes");
         hasGetNodes = !Modifier.isAbstract(getNodes.getModifiers());
       } catch (NoSuchMethodException e) {
         // ignore
       }
     }
     if (!hasMatches) {
       try {
         final Method getNodes =
             clazz.getDeclaredMethod("matches", Queue.Item.class, SubTask.class);
         hasMatches = !Modifier.isAbstract(getNodes.getModifiers());
       } catch (NoSuchMethodException e) {
         // ignore
       }
     }
     if (!(hasGetNodes && hasMatches)
         && LoadStatistics.class.isAssignableFrom(clazz.getSuperclass())) {
       clazz = (Class<? extends LoadStatistics>) clazz.getSuperclass();
     }
   }
   return hasGetNodes && hasMatches;
 }
Example #6
0
 @Test
 public void checkEarthIsAbstract() throws NoSuchMethodException {
   assertTrue("Earth class should be abstract", Modifier.isAbstract(Earth.class.getModifiers()));
   assertTrue(
       "Earth class spin() method should be abstract",
       Modifier.isAbstract(Earth.class.getMethod("spin").getModifiers()));
   assertTrue(
       "Earth class warmUp() method should be abstract",
       Modifier.isAbstract(Earth.class.getMethod("warmUp").getModifiers()));
 }
 private static void getAbstractMethods(Class c, List<Method> current) {
   if (c == null || !Modifier.isAbstract(c.getModifiers())) return;
   getAbstractMethods(c.getSuperclass(), current);
   for (Class ci : c.getInterfaces()) {
     getAbstractMethods(ci, current);
   }
   for (Method m : getDeclaredMethods(c)) {
     if (Modifier.isPrivate(m.getModifiers())) continue;
     if (Modifier.isAbstract(m.getModifiers())) current.add(m);
   }
 }
Example #8
0
  private Method findMethodWith(Class<? extends Annotation> type, boolean isOptional) {
    Method[] methods = process.getClass().getMethods();

    for (Method method : methods) {
      if (method.getAnnotation(type) == null) continue;

      int modifiers = method.getModifiers();

      if (Modifier.isAbstract(modifiers))
        throw new IllegalStateException(
            "given process method: " + method.getName() + " must not be abstract");

      if (Modifier.isInterface(modifiers))
        throw new IllegalStateException(
            "given process method: " + method.getName() + " must be implemented");

      if (!Modifier.isPublic(modifiers))
        throw new IllegalStateException(
            "given process method: " + method.getName() + " must be public");

      return method;
    }

    if (!isOptional)
      throw new IllegalStateException("no method found declaring annotation: " + type.getName());

    return null;
  }
Example #9
0
  /**
   * This method gets all classes in the same package as RegisterHandlerByReflection which
   * implements the RegisterHandlerByReflection interface.
   *
   * @return
   * @throws ClassNotFoundException
   * @throws InstantiationException
   * @throws IllegalAccessException
   * @throws UnsupportedEncodingException
   */
  public static Collection<RegisteredHandler> getRegisteredHandlerImplementations()
      throws ClassNotFoundException, InstantiationException, IllegalAccessException,
          UnsupportedEncodingException {

    final String pckgname = RegisteredHandler.class.getPackage().getName();
    final Collection<RegisteredHandler> handlers = new ArrayList<RegisteredHandler>();
    Collection<String> classNames = null;
    try {
      final String path = '/' + pckgname.replace('.', '/');
      final URL resource = HandlerUtil.class.getResource(path);
      if (resource == null) {
        throw new ClassNotFoundException("No resource for " + path);
      }

      classNames = findHandlerClassNames(resource.getPath().toString(), pckgname);
    } catch (Exception e) {
      throw new ClassNotFoundException(
          pckgname + " (" + pckgname + ") does not appear to be a valid package", e);
    }

    for (String className : classNames) {
      final Class<?> clazz = Class.forName(className);
      if (!clazz.isInterface()
          && !Modifier.isAbstract(clazz.getModifiers())
          && RegisteredHandler.class.isAssignableFrom(clazz)) {

        handlers.add((RegisteredHandler) clazz.newInstance());
      }
    }

    return handlers;
  }
Example #10
0
  public static void register(Class<? extends Event> pore) {
    checkNotNull(pore, "pore");

    Class<? extends org.spongepowered.api.event.Event> sponge = null;
    for (Constructor<?> constructor : pore.getConstructors()) {
      Class<?>[] parameters = constructor.getParameterTypes();
      if (parameters.length == 1) {
        Class<?> parameter = parameters[0];
        if (org.spongepowered.api.event.Event.class.isAssignableFrom(parameter)) {
          sponge = parameter.asSubclass(org.spongepowered.api.event.Event.class);
        }
      }
    }

    checkArgument(sponge != null, "No event constructor found in %s", pore);

    Class<?> superClass = pore.getSuperclass();
    checkState(
        !Modifier.isAbstract(superClass.getModifiers())
            && superClass.getName().startsWith("org.bukkit.event"),
        "Not a Bukkit handle event %s",
        superClass);
    Class<? extends Event> handle = superClass.asSubclass(Event.class);

    HandlerList list = SimplePluginManager.getEventListeners(handle);
    list.addAdapter(create(pore, sponge));
  }
 /**
  * @param expectedType expected Type
  * @return a {@link EntityFactory} instance for specified type.
  * @throws NullPointerException if expectedType
  * @throws IllegalArgumentException if no factory can be provided
  */
 @SuppressWarnings("unchecked")
 public <T> EntityFactory<T> newInstance(final Class<T> expectedType)
     throws NullPointerException, IllegalArgumentException {
   // in a registered factory ?
   EntityFactories.EntityFactory<?> factory = factories.get(expectedType);
   if (factory == null) {
     // should we use a proxy ?
     if (expectedType.isInterface() || Modifier.isAbstract(expectedType.getModifiers())) {
       final MetaEntityContext metaEntityContext =
           metaEntityContextProvider.find(Reference.newReferenceOnEntityClass(expectedType));
       factory = EntityFactories.newEntityProxyDynamicFactory(expectedType, metaEntityContext);
     } else // EntityDynamic
     if (EntityDynamic.class.getName().equals(expectedType.getName())) {
       // build factory for class
       factory = EntityFactories.newEntityDynamicFactory(MetaModel.getEntityDynamicContext());
     } else // default Factory ?
     {
       if (!enableDefaultFactory) {
         throw new IllegalArgumentException(
             StringUtils.format("No EntityFactory for %s", expectedType));
       }
       if (!Entity.class.isAssignableFrom(expectedType)) {
         throw new IllegalArgumentException(
             StringUtils.format(
                 "No EntityFactory can be created for %s (Not assignable to Entity interface)",
                 expectedType));
       }
       factory = buildDefaultEntityFactory(expectedType);
     }
     // register for later
     factories.put(expectedType, factory);
   }
   return (EntityFactory<T>) factory;
 }
Example #12
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;
 }
 @Override
 public List<Module> get() {
   List<Module> modules = new ArrayList<>();
   ClassPath classpath;
   for (String pkg : packages) {
     try {
       classpath = ClassPath.from(Thread.currentThread().getContextClassLoader());
       for (ClassPath.ClassInfo classInfo : classpath.getTopLevelClassesRecursive(pkg)) {
         try {
           // Include Modules that have at least on Conditional
           Class<?> cls =
               Class.forName(classInfo.getName(), false, ClassLoader.getSystemClassLoader());
           if (!cls.isInterface()
               && !Modifier.isAbstract(cls.getModifiers())
               && Module.class.isAssignableFrom(cls)) {
             for (Annotation annot : cls.getAnnotations()) {
               if (null != annot.annotationType().getAnnotation(Conditional.class)) {
                 modules.add((Module) cls.newInstance());
                 break;
               }
             }
           }
         } catch (Exception e) {
           throw new RuntimeException("Failed to instantiate module '" + pkg + "'", e);
         }
       }
     } catch (Exception e) {
       throw new RuntimeException("Failed to scan root package '" + pkg + "'", e);
     }
   }
   return modules;
 }
  static <C extends Collection<?>, E> Collection<E> createCollection(
      Class<C> collectionType, Collection<? extends E> elements)
      throws IllegalAccessException, InstantiationException {

    final Collection<E> result;

    // If the collectionType is Abstract (or an Interface) we try to guess a valid
    // implementation...
    if (Modifier.isAbstract(collectionType.getModifiers())) {
      // FIXME: Maybe we should add some more implementations here?
      if (collectionType.isAssignableFrom(HashSet.class)) {
        result = new HashSet<E>();
      } else if (collectionType.isAssignableFrom(LinkedList.class)) {
        result = new LinkedList<E>();
      } else {
        throw new InstantiationException(
            "Could not find an implementation of " + collectionType.getName());
      }
    } else {
      result = createInstance(collectionType);
    }

    if (elements != null) {
      result.addAll(elements);
    }

    return result;
  }
  // this GwtCreateHandler has been introduced to make possible the
  // instanciation of abstract classes
  // that gwt-test-utils doesn't patch right now
  public Object create(Class<?> classLiteral) throws Exception {
    if (classLiteral.isAnnotation()
        || classLiteral.isArray()
        || classLiteral.isEnum()
        || classLiteral.isInterface()
        || !Modifier.isAbstract(classLiteral.getModifiers())) {
      return null;
    }

    Class<?> newClass = cache.get(classLiteral);

    if (newClass != null) {
      return newClass.newInstance();
    }

    CtClass ctClass = GwtClassPool.getCtClass(classLiteral);
    CtClass subClass = GwtClassPool.get().makeClass(classLiteral.getCanonicalName() + "SubClass");

    subClass.setSuperclass(ctClass);

    for (CtMethod m : ctClass.getDeclaredMethods()) {
      if (javassist.Modifier.isAbstract(m.getModifiers())) {
        CtMethod copy = new CtMethod(m, subClass, null);
        subClass.addMethod(copy);
      }
    }

    GwtPatcherUtils.patch(subClass, null);

    newClass = subClass.toClass(GwtClassLoader.get(), null);
    cache.put(classLiteral, newClass);

    return newClass.newInstance();
  }
  @Test
  public void testTwoWayFieldBridgeCanHandleNullInObjectToString() throws Exception {
    List<Class<?>> classes = getClasses("org.hibernate.search.bridge.builtin");
    assertTrue("Guarding against a package refactoring", classes.size() > 0);

    for (Class<?> clazz : classes) {
      // not interested in abstract classes
      if (Modifier.isAbstract(clazz.getModifiers())) {
        continue;
      }
      // neither in non TwoWayFieldBridge
      if (!TwoWayFieldBridge.class.isAssignableFrom(clazz)) {
        continue;
      }

      // the NumericFieldBridge is an emum (go figure) - we need special massaging here
      if (Enum.class.isAssignableFrom(clazz)) {
        assertTrue(
            "Unexpected enum class" + clazz, NumericFieldBridge.class.isAssignableFrom(clazz));
        for (Object o : clazz.getEnclosingClass().getEnumConstants()) {
          TwoWayFieldBridge bridge = (TwoWayFieldBridge) o;
          assertEquals(
              "All TwoWayFieldBridgeTest should return 'null' for 'null' passed to 'objectToString",
              null,
              bridge.objectToString(null));
        }
      } else {
        TwoWayFieldBridge bridge = (TwoWayFieldBridge) clazz.newInstance();
        assertEquals(
            "All TwoWayFieldBridgeTest should return 'null' for 'null' passed to 'objectToString",
            null,
            bridge.objectToString(null));
      }
    }
  }
Example #17
0
 @Override
 public boolean innerSupports(ParamMetaData metaData) {
   return List.class == metaData.getParamType()
       || Collection.class == metaData.getParamType()
       || (!Modifier.isAbstract(metaData.getParamType().getModifiers())
           && List.class.isAssignableFrom(metaData.getParamType()));
 }
  private void generateStage(
      Element[] parents, Class stage, Set<Class<? extends Stage>> generatedStages) {
    if (generatedStages.contains(stage)) return;
    boolean hasParentStage = Stage.class.isAssignableFrom(stage.getSuperclass());
    if (hasParentStage) {
      generateStage(parents, stage.getSuperclass(), generatedStages);
    }
    org.radargun.config.Stage stageAnnotation =
        (org.radargun.config.Stage) stage.getAnnotation(org.radargun.config.Stage.class);
    if (stageAnnotation == null) return; // not a proper stage

    String stageType = generateClass(stage);
    if (!Modifier.isAbstract(stage.getModifiers()) && !stageAnnotation.internal()) {
      for (Element parent : parents) {
        createReference(
            parent, XmlHelper.camelCaseToDash(StageHelper.getStageName(stage)), stageType);
      }
      if (!stageAnnotation.deprecatedName().equals(org.radargun.config.Stage.NO_DEPRECATED_NAME)) {
        for (Element parent : parents) {
          createReference(
              parent, XmlHelper.camelCaseToDash(stageAnnotation.deprecatedName()), stageType);
        }
      }
    }
    generatedStages.add(stage);
  }
Example #19
0
    private void LoadClasses() {
      classes = new ArrayList<FileClass>();

      // Load directory
      File dir = new File(directory);
      File[] files = dir.listFiles(filter);
      // For each file of type .class,
      for (File f : files) {
        // Load file
        try {
          URL url = f.toURI().toURL();
          URL[] urls = new URL[] {url};
          ClassLoader cl = new URLClassLoader(urls);
          Class<?> cls = cl.loadClass("builtin." + f.getName().replace(".class", ""));
          ArrayList<Class<?>> interfaces = getAllInterfaces(cls);
          for (Class<?> c : interfaces) {
            if (c.equals(mytype) && !Modifier.isAbstract(cls.getModifiers())) {
              classes.add(new FileClass(f, cls));
              break;
            }
          }
        } catch (Exception ex) {
          System.err.println("Error loading class file: " + f.getAbsolutePath());
        }
      }
    }
  public void initialize() {
    identity = context.getMappingSyntaxStrategy().getIdentity(javaClass, context);
    owners = context.getMappingSyntaxStrategy().getOwningEntities(javaClass, context);
    persistentProperties =
        context.getMappingSyntaxStrategy().getPersistentProperties(javaClass, context);
    persistentPropertyNames = new ArrayList<String>();
    associations = new ArrayList();
    for (PersistentProperty persistentProperty : persistentProperties) {
      if (!(persistentProperty instanceof OneToMany))
        persistentPropertyNames.add(persistentProperty.getName());
      if (persistentProperty instanceof Association) {
        associations.add((Association) persistentProperty);
      }
    }
    for (PersistentProperty persistentProperty : persistentProperties) {
      propertiesByName.put(persistentProperty.getName(), persistentProperty);
    }

    Class superClass = javaClass.getSuperclass();
    if (superClass != null
        && !superClass.equals(Object.class)
        && !Modifier.isAbstract(superClass.getModifiers())) {
      parentEntity = context.addPersistentEntity(superClass);
    }

    getMapping().getMappedForm(); // initialize mapping
  }
Example #21
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;
  }
Example #22
0
  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;
  }
  /**
   * @return a reference to the public static serializableInstance() method of clazz, if there is
   *     one; otherwise, returns null.
   */
  private Method serializableInstanceMethod(Class clazz) {
    Method[] methods = clazz.getMethods();

    for (Method method : methods) {
      if ("serializableInstance".equals(method.getName())) {
        Class[] parameterTypes = method.getParameterTypes();

        if (!(parameterTypes.length == 0)) {
          continue;
        }

        if (!(Modifier.isStatic(method.getModifiers()))) {
          continue;
        }

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

        return method;
      }
    }

    return null;
  }
Example #24
0
  @SuppressWarnings({"unchecked", "rawtypes"})
  private final Object bindResourceToContainer(
      final Class resource, final Object containerInstance) {
    final ProxyFactory factory = new ProxyFactory();
    factory.setSuperclass(resource);
    factory.setFilter(method -> Modifier.isAbstract(method.getModifiers()));

    final MethodHandler handler =
        (b, thisMethod, proceed, args) -> {
          final Method containerMethod = resourceToContainer.get(thisMethod);
          if (containerMethod != null) {
            return containerMethod.invoke(containerInstance, args);
          } else {
            throw new IllegalAccessException(
                thisMethod
                    + " is not implemented in "
                    + containerInstance.getClass()
                    + " via interface");
          }
        };

    try {
      final Object resourceInstance =
          resource.cast(factory.create(new Class<?>[0], new Object[0], handler));
      bind(resource).toInstance(resource.cast(resourceInstance));
      return resourceInstance;
    } catch (NoSuchMethodException
        | IllegalArgumentException
        | InstantiationException
        | IllegalAccessException
        | InvocationTargetException e) {
      throw new RuntimeException(e);
    }
  }
Example #25
0
  ClassMethod(
      String name, String returnType, String[] parameters, int accessFlags, ClassFile classFile) {
    ConstPool constPool = classFile.getConstPool();
    this.classFile = classFile;
    this.returnType = DescriptorUtils.validateDescriptor(returnType);
    this.parameters = parameters;
    this.name = name;
    this.descriptor = DescriptorUtils.methodDescriptor(parameters, returnType);
    this.accessFlags = accessFlags;
    this.nameIndex = constPool.addUtf8Entry(name);
    this.descriptorIndex = constPool.addUtf8Entry(descriptor);
    this.constructor = name.equals("<init>");
    this.exceptionsAttribute = new ExceptionsAttribute(constPool);
    this.attributes.add(exceptionsAttribute);

    if (Modifier.isAbstract(accessFlags)) {
      codeAttribute = null;
    } else {
      codeAttribute = new CodeAttribute(this, constPool);
      attributes.add(codeAttribute);
    }
    for (String param : this.parameters) {
      DescriptorUtils.validateDescriptor(param);
    }
  }
Example #26
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;
 }
 /**
  * Adds the new {@link StaticWidget} to the registry.
  *
  * @param clazz the class of the {@link StaticWidget}. If it is an abstract class, then it will be
  *     ignored.
  */
 public static void registerStaticWidget(Class<? extends StaticWidget> clazz) {
   if (!Modifier.isAbstract(clazz.getModifiers())) {
     staticWidgets.add(clazz);
   }
   // TODO made this complain if given a normal widget, or make it call
   // registerWidget
 }
  /**
   * @see
   *     org.apache.wicket.core.request.mapper.AbstractBookmarkableMapper#parseRequest(org.apache.wicket.request.Request)
   */
  @Override
  protected UrlInfo parseRequest(Request request) {
    Url url = request.getUrl();
    if (url.getSegments().size() >= 1) {
      // try to extract page and component information from URL
      PageComponentInfo info = getPageComponentInfo(url);

      // load the page class
      String className = url.getSegments().get(0);

      if (isValidClassName(className) == false) {
        return null;
      }

      className = transformFromUrl(className);
      String fullyQualifiedClassName = packageName.getName() + '.' + className;
      Class<? extends IRequestablePage> pageClass = getPageClass(fullyQualifiedClassName);

      if (pageClass != null
          && Modifier.isAbstract(pageClass.getModifiers()) == false
          && IRequestablePage.class.isAssignableFrom(pageClass)) {
        // extract the PageParameters from URL if there are any
        PageParameters pageParameters = extractPageParameters(request, 1, pageParametersEncoder);

        return new UrlInfo(info, pageClass, pageParameters);
      }
    }
    return null;
  }
Example #29
0
 public static boolean isValidResourceClass(Class<?> c) {
   if (c.isInterface() || Modifier.isAbstract(c.getModifiers())) {
     LOG.info("Ignoring invalid resource class " + c.getName());
     return false;
   }
   return true;
 }
 public PropertyAccessorExtractionContext(Iterable<Method> declaringMethods) {
   this.declaringMethods = ImmutableList.copyOf(declaringMethods);
   this.mostSpecificDeclaration = ModelSchemaUtils.findMostSpecificMethod(declaringMethods);
   this.declaredInManagedType = ModelSchemaUtils.isMethodDeclaredInManagedType(declaringMethods);
   this.declaredAsAbstract = Modifier.isAbstract(this.mostSpecificDeclaration.getModifiers());
   this.annotations = collectAnnotations(declaringMethods);
 }