Esempio n. 1
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));
  }
  boolean applyArgoController(Class<?> clazz, Pattern controllerPattern) {

    return ArgoController.class.isAssignableFrom(clazz)
        && controllerPattern.matcher(clazz.getName()).matches()
        && !Modifier.isInterface(clazz.getModifiers())
        && !Modifier.isAbstract(clazz.getModifiers())
        && Modifier.isPublic(clazz.getModifiers());
  }
Esempio n. 3
1
 public static TypeImpl getIterableImpl(Class<?> iterClass) {
   if (iterClass == List.class || iterClass == Collection.class || iterClass == Iterable.class) {
     return new TypeImpl(iterClass, ArrayList.class);
   } else if (Modifier.isAbstract(iterClass.getModifiers())
       || Modifier.isInterface(iterClass.getModifiers())) {
     throw new RuntimeException(
         "Cannot find appropriate implementation of collection type: " + iterClass.getName());
   }
   return new TypeImpl(iterClass, iterClass);
 }
Esempio n. 4
1
 public static TypeImpl getMapImpl(Class<?> mapClass) {
   if (mapClass == Map.class || mapClass == AbstractMap.class) {
     return new TypeImpl(mapClass, HashMap.class);
   } else if (mapClass == ConcurrentMap.class) {
     return new TypeImpl(mapClass, ConcurrentHashMap.class);
   } else if (SortedMap.class.isAssignableFrom(mapClass)) {
     return new TypeImpl(mapClass, TreeMap.class);
   } else if (Modifier.isAbstract(mapClass.getModifiers())
       || Modifier.isInterface(mapClass.getModifiers())) {
     throw new RuntimeException(
         "Cannot find appropriate implementation of collection type: " + mapClass.getName());
   }
   return new TypeImpl(mapClass, mapClass);
 }
Esempio n. 5
0
 @Test
 public void isAnInterface() {
   exists();
   assertTrue(
       "Class " + AIRCRAFT_REPOSITORY_CLASSNAME + " should be an interface.",
       Modifier.isInterface(Reflex.reflect(AIRCRAFT_REPOSITORY_CLASSNAME).cls().getModifiers()));
   assertTrue(
       "Class " + AIRPORT_REPOSITORY_CLASSNAME + " should be an interface.",
       Modifier.isInterface(Reflex.reflect(AIRPORT_REPOSITORY_CLASSNAME).cls().getModifiers()));
 }
Esempio n. 6
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;
  }
  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.");
      }
    }
  }
Esempio n. 8
0
  private Class<?> loadBeanClass() {
    if (beanClass == null) {
      String className = beanInfo.getClassName();
      Class<?> clazz = loadClass(className);
      ApplicationAssociate associate = ApplicationAssociate.getCurrentInstance();

      if (!associate.isDevModeEnabled()) {
        beanClass = clazz;
      }

      // validate the bean class is public and has a public
      // no-arg ctor
      int classModifiers = clazz.getModifiers();
      if (!Modifier.isPublic(classModifiers)) {
        String message =
            MessageUtils.getExceptionMessageString(
                MessageUtils.MANAGED_BEAN_CLASS_IS_NOT_PUBLIC_ERROR_ID,
                className,
                beanInfo.getName());
        queueMessage(message);
      }
      if (Modifier.isInterface(classModifiers) || Modifier.isAbstract(classModifiers)) {
        String message =
            MessageUtils.getExceptionMessageString(
                MessageUtils.MANAGED_BEAN_CLASS_IS_ABSTRACT_ERROR_ID,
                className,
                beanInfo.getName());
        queueMessage(message);
      }

      try {
        Constructor ctor = clazz.getConstructor(RIConstants.EMPTY_CLASS_ARGS);
        if (!Modifier.isPublic(ctor.getModifiers())) {
          String message =
              MessageUtils.getExceptionMessageString(
                  MessageUtils.MANAGED_BEAN_CLASS_NO_PUBLIC_NOARG_CTOR_ERROR_ID,
                  className,
                  beanInfo.getName());
          queueMessage(message);
        }
      } catch (NoSuchMethodException nsme) {
        String message =
            MessageUtils.getExceptionMessageString(
                MessageUtils.MANAGED_BEAN_CLASS_NO_PUBLIC_NOARG_CTOR_ERROR_ID,
                className,
                beanInfo.getName());
        queueMessage(message);
      }

      if (!hasMessages()) {
        // class is ok, scan for annotations
        this.isInjectible = scanForAnnotations(clazz);
      }
      return clazz;
    }
    return beanClass;
  }
  public boolean isValidClass(Class<?> clazz) {
    final int modifiers = clazz.getModifiers();

    if (Modifier.isAbstract(modifiers) || Modifier.isInterface(modifiers)) return false;

    if (!Modifier.isPublic(modifiers)) return false;

    return true;
  }
Esempio n. 10
0
  /** Map Java class modifiers to Fantom flags. */
  public static int classModifiersToFanFlags(int m) {
    int flags = 0;

    if (Modifier.isAbstract(m)) flags |= FConst.Abstract;
    if (Modifier.isFinal(m)) flags |= FConst.Final;
    if (Modifier.isInterface(m)) flags |= FConst.Mixin;

    if (Modifier.isPublic(m)) flags |= FConst.Public;
    else flags |= FConst.Internal;

    return flags;
  }
 public void registerExpression(final ExpressionMetaData metaData) {
   if (metaData == null) {
     throw new NullPointerException();
   }
   final Class type = metaData.getExpressionType();
   final int modifiers = type.getModifiers();
   if (Modifier.isAbstract(modifiers) || Modifier.isInterface(modifiers)) {
     throw new IllegalArgumentException(
         "Expression-Implementation cannot be abstract or an interface.");
   }
   this.backend.put(type.getName(), metaData);
 }
Esempio n. 12
0
 private void removeAllAbstractMethods(List<MethodInfo> methods) {
   Iterator<MethodInfo> it = methods.iterator();
   while (it.hasNext()) {
     MethodInfo info = it.next();
     // if the class is an interface then keep the method
     boolean isFromInterface =
         Modifier.isInterface(info.getMethod().getDeclaringClass().getModifiers());
     if (!isFromInterface && Modifier.isAbstract(info.getMethod().getModifiers())) {
       // we cannot invoke an abstract method
       it.remove();
     }
   }
 }
Esempio n. 13
0
    @SuppressWarnings({"rawtypes", "unchecked", "synthetic-access"})
    @Override
    public boolean processClass(final Class candidate) throws Exception {
      if (FilteredPipeline.class.isAssignableFrom(candidate)
          && !Modifier.isAbstract(candidate.getModifiers())
          && !Modifier.isInterface(candidate.getModifiers())
          && Ats.from(candidate).has(ComponentPart.class)) {
        try {
          final ComponentId compId =
              Ats.from(candidate).get(ComponentPart.class).value().newInstance();
          final Class<? extends FilteredPipeline> pipelineClass = candidate;
          final FilteredPipeline pipeline = Classes.newInstance(pipelineClass);
          Pipelines.pipelines.add(pipeline);
          return true;
        } catch (final Exception ex) {
          LOG.trace(ex, ex);
          return false;
        }
      } else if (ChannelPipelineFactory.class.isAssignableFrom(candidate)
          && !Modifier.isAbstract(candidate.getModifiers())
          && !Modifier.isInterface(candidate.getModifiers())
          && Ats.from(candidate).has(ComponentPart.class)) {
        try {
          final ComponentId compId =
              Ats.from(candidate).get(ComponentPart.class).value().newInstance();
          final Class<? extends ChannelPipelineFactory> pipelineClass = candidate;
          final ChannelPipelineFactory pipeline = Classes.newInstance(pipelineClass);
          Pipelines.clientPipelines.put(compId.getClass(), pipeline);
          return true;
        } catch (final Exception ex) {
          LOG.trace(ex, ex);
          return false;
        }

      } else {
        return false;
      }
    }
Esempio n. 14
0
 /** 找到所有的子类,不包括接口 */
 @SuppressWarnings("unchecked")
 public <T> List<Class<? extends T>> findSubClass(final Class<T> classInterface) {
   Set<Class<? extends T>> classSet = reflections.getSubTypesOf(classInterface);
   List<Class<? extends T>> classList = Lists.newArrayList();
   for (Class<? extends T> clazz : classSet) {
     int modifier = clazz.getModifiers();
     if (classInterface.isAssignableFrom(clazz)
         && !Modifier.isInterface(modifier)
         && !Modifier.isAbstract(modifier)
         && Modifier.isPublic(modifier)) {
       classList.add(clazz);
     }
   }
   return classList;
 }
 /**
  * Returns true if the passed <code>mdbClass</code> meets the requirements set by the EJB3 spec
  * about bean implementation classes. The passed <code>mdbClass</code> must not be an interface
  * and must be public and not final and not abstract. If it passes these requirements then this
  * method returns true. Else it returns false.
  *
  * @param mdbClass The MDB class
  * @return
  */
 private boolean assertMDBClassValidity(final ClassInfo mdbClass) {
   final short flags = mdbClass.flags();
   final String className = mdbClass.name().toString();
   // must *not* be a interface
   if (Modifier.isInterface(flags)) {
     EjbLogger.EJB3_LOGGER.mdbClassCannotBeAnInterface(className);
     return false;
   }
   // bean class must be public, must *not* be abstract or final
   if (!Modifier.isPublic(flags) || Modifier.isAbstract(flags) || Modifier.isFinal(flags)) {
     EjbLogger.EJB3_LOGGER.mdbClassMustBePublicNonAbstractNonFinal(className);
     return false;
   }
   // valid class
   return true;
 }
 @Override
 public boolean processClass(Class candidate) throws Exception {
   if (Ats.from(candidate).has(ObjectStorageProviderClientProperty.class)
       && !Modifier.isAbstract(candidate.getModifiers())
       && !Modifier.isInterface(candidate.getModifiers())) {
     ObjectStorageProviderClientProperty candidateType =
         Ats.from(candidate).get(ObjectStorageProviderClientProperty.class);
     String propName = candidateType.value();
     if (ObjectStorageProviderClient.class.isAssignableFrom(candidate)) {
       clients.put(propName, candidate);
     }
     return true;
   } else {
     return false;
   }
 }
Esempio n. 17
0
  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;
  }
Esempio n. 18
0
 public static final void register(Class<? extends Function> cls) {
   int mods = cls.getModifiers();
   if (Modifier.isAbstract(mods) || Modifier.isInterface(mods) || !Modifier.isPublic(mods)) {
     return;
   }
   String name = getFunctionName(cls);
   FunctionInfo fn = functions.get(name);
   if (fn != null) {
     if (fn.functionClass == cls) {
       // ok, same class is already registered
       return;
     }
     throw new GreqlException("Duplicate function name '" + name + "'");
   }
   logger.fine("Registering " + cls.getName() + " as '" + name + "'");
   functions.put(name, new FunctionInfo(name, cls));
   functionNames.add(name);
 }
Esempio n. 19
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);
   }
 }
 /**
  * Returns true if the passed <code>sessionBeanClass</code> meets the requirements set by the EJB3
  * spec about bean implementation classes. The passed <code>sessionBeanClass</code> must not be an
  * interface and must be public and not final and not abstract. If it passes these requirements
  * then this method returns true. Else it returns false.
  *
  * @param sessionBeanClass The session bean class
  * @return
  */
 private static boolean assertSessionBeanClassValidity(final ClassInfo sessionBeanClass) {
   final short flags = sessionBeanClass.flags();
   final String className = sessionBeanClass.name().toString();
   // must *not* be a interface
   if (Modifier.isInterface(flags)) {
     logger.warn(
         "[EJB3.1 spec, section 4.9.2] Session bean implementation class MUST NOT be a interface - "
             + className
             + " is an interface, hence won't be considered as a session bean");
     return false;
   }
   // bean class must be public, must *not* be abstract or final
   if (!Modifier.isPublic(flags) || Modifier.isAbstract(flags) || Modifier.isFinal(flags)) {
     logger.warn(
         "[EJB3.1 spec, section 4.9.2] Session bean implementation class MUST be public, not abstract and not final - "
             + className
             + " won't be considered as a session bean, since it doesn't meet that requirement");
     return false;
   }
   // valid class
   return true;
 }
Esempio n. 21
0
  public Object newInstance(
      ComponentDescriptor componentDescriptor, ClassRealm classRealm, PlexusContainer container)
      throws ComponentInstantiationException {
    Class implementationClass = null;

    try {
      String implementation = componentDescriptor.getImplementation();

      implementationClass = classRealm.loadClass(implementation);

      int modifiers = implementationClass.getModifiers();

      if (Modifier.isInterface(modifiers)) {
        throw new ComponentInstantiationException(
            "Cannot instanciate implementation '"
                + implementation
                + "' because the class is a interface.");
      }

      if (Modifier.isAbstract(modifiers)) {
        throw new ComponentInstantiationException(
            "Cannot instanciate implementation '"
                + implementation
                + "' because the class is abstract.");
      }

      Object instance = implementationClass.newInstance();

      return instance;
    } catch (InstantiationException e) {
      throw makeException(classRealm, componentDescriptor, implementationClass, e);
    } catch (ClassNotFoundException e) {
      throw makeException(classRealm, componentDescriptor, implementationClass, e);
    } catch (IllegalAccessException e) {
      throw makeException(classRealm, componentDescriptor, implementationClass, e);
    } catch (LinkageError e) {
      throw makeException(classRealm, componentDescriptor, implementationClass, e);
    }
  }
Esempio n. 22
0
  /**
   * get all classes within an Java package as action
   *
   * @param p_package full-qualified package name or empty for default package
   * @return action stream
   */
  @SuppressWarnings("unchecked")
  public static Stream<IAction> actionsFromPackage(final String... p_package) {
    return ((p_package == null) || (p_package.length == 0)
            ? Stream.of(MessageFormat.format("{0}.{1}", PACKAGEROOT, "action.buildin"))
            : Arrays.stream(p_package))
        .flatMap(
            j -> {
              try {
                return ClassPath.from(Thread.currentThread().getContextClassLoader())
                    .getTopLevelClassesRecursive(j)
                    .parallelStream()
                    .map(ClassPath.ClassInfo::load)
                    .filter(i -> !Modifier.isAbstract(i.getModifiers()))
                    .filter(i -> !Modifier.isInterface(i.getModifiers()))
                    .filter(i -> Modifier.isPublic(i.getModifiers()))
                    .filter(IAction.class::isAssignableFrom)
                    .map(
                        i -> {
                          try {
                            return (IAction) i.newInstance();
                          } catch (final IllegalAccessException
                              | InstantiationException l_exception) {
                            LOGGER.warning(
                                CCommon.languagestring(
                                    CCommon.class, "actioninstantiate", i, l_exception));
                            return null;
                          }
                        })

                    // action can be instantiate
                    .filter(Objects::nonNull)

                    // check usable action name
                    .filter(CCommon::actionusable);
              } catch (final IOException l_exception) {
                throw new UncheckedIOException(l_exception);
              }
            });
  }
Esempio n. 23
0
 public static boolean isJaxwsEndpoint(final ClassInfo clazz, final CompositeIndex index) {
   // assert JAXWS endpoint class flags
   final short flags = clazz.flags();
   if (Modifier.isInterface(flags)) return false;
   if (Modifier.isAbstract(flags)) return false;
   if (!Modifier.isPublic(flags)) return false;
   if (isJaxwsService(clazz, index)) return false;
   final boolean hasWebServiceAnnotation = clazz.annotations().containsKey(WEB_SERVICE_ANNOTATION);
   final boolean hasWebServiceProviderAnnotation =
       clazz.annotations().containsKey(WEB_SERVICE_PROVIDER_ANNOTATION);
   if (!hasWebServiceAnnotation && !hasWebServiceProviderAnnotation) {
     return false;
   }
   if (hasWebServiceAnnotation && hasWebServiceProviderAnnotation) {
     ROOT_LOGGER.mutuallyExclusiveAnnotations(clazz.name().toString());
     return false;
   }
   if (Modifier.isFinal(flags)) {
     ROOT_LOGGER.finalEndpointClassDetected(clazz.name().toString());
     return false;
   }
   return true;
 }
Esempio n. 24
0
 private boolean isInterface() {
   return Modifier.isInterface(this.code);
 }
Esempio n. 25
0
 /**
  * {@link Modifier} NOT ABSTRACT,INTERFACE OR PRIVATE.
  *
  * @param clazz
  * @return
  */
 public static boolean isNewInstanceable(Class<?> clazz) {
   int modify = clazz.getModifiers();
   return !Modifier.isAbstract(modify)
       && !Modifier.isInterface(modify)
       && !Modifier.isPrivate(modify);
 }
Esempio n. 26
0
  protected void scan(
      final DeploymentUnit du,
      final ClassLoader classLoader,
      final ResteasyDeploymentData resteasyDeploymentData)
      throws DeploymentUnitProcessingException, ModuleLoadException {

    final CompositeIndex index = du.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX);

    if (!resteasyDeploymentData.shouldScan()) {
      return;
    }

    final Set<ClassInfo> applicationClass = index.getAllKnownSubclasses(APPLICATION);
    try {
      if (applicationClass.size() > 1) {
        StringBuilder builder = new StringBuilder();
        Set<ClassInfo> aClasses = new HashSet<ClassInfo>();
        for (ClassInfo c : applicationClass) {
          if (!Modifier.isAbstract(c.flags())) {
            aClasses.add(c);
          }
          builder.append(" ").append(c.name().toString());
        }
        if (aClasses.size() > 1) {
          throw new DeploymentUnitProcessingException(
              MESSAGES.onlyOneApplicationClassAllowed(builder));
        } else if (aClasses.size() == 1) {
          ClassInfo aClass = applicationClass.iterator().next();
          resteasyDeploymentData.setScannedApplicationClass(
              (Class<? extends Application>) classLoader.loadClass(aClass.name().toString()));
        }
      } else if (applicationClass.size() == 1) {
        ClassInfo aClass = applicationClass.iterator().next();
        resteasyDeploymentData.setScannedApplicationClass(
            (Class<? extends Application>) classLoader.loadClass(aClass.name().toString()));
      }
    } catch (ClassNotFoundException e) {
      throw MESSAGES.cannotLoadApplicationClass(e);
    }

    List<AnnotationInstance> resources = null;
    List<AnnotationInstance> providers = null;
    if (resteasyDeploymentData.isScanResources()) {
      resources = index.getAnnotations(JaxrsAnnotations.PATH.getDotName());
    }
    if (resteasyDeploymentData.isScanProviders()) {
      providers = index.getAnnotations(JaxrsAnnotations.PROVIDER.getDotName());
    }

    if ((resources == null || resources.isEmpty()) && (providers == null || providers.isEmpty()))
      return;
    final Set<ClassInfo> pathInterfaces = new HashSet<ClassInfo>();
    if (resources != null) {
      for (AnnotationInstance e : resources) {
        final ClassInfo info;
        if (e.target() instanceof ClassInfo) {
          info = (ClassInfo) e.target();
        } else if (e.target() instanceof MethodInfo) {
          // ignore
          continue;
        } else {
          JAXRS_LOGGER.classOrMethodAnnotationNotFound("@Path", e.target());
          continue;
        }
        if (!Modifier.isInterface(info.flags())) {
          resteasyDeploymentData.getScannedResourceClasses().add(info.name().toString());
        } else {
          pathInterfaces.add(info);
        }
      }
    }
    if (providers != null) {
      for (AnnotationInstance e : providers) {
        if (e.target() instanceof ClassInfo) {
          ClassInfo info = (ClassInfo) e.target();
          if (!Modifier.isInterface(info.flags())) {
            resteasyDeploymentData.getScannedProviderClasses().add(info.name().toString());
          }
        } else {
          JAXRS_LOGGER.classAnnotationNotFound("@Provider", e.target());
        }
      }
    }

    // look for all implementations of interfaces annotated @Path
    for (final ClassInfo iface : pathInterfaces) {
      final Set<ClassInfo> implementors = index.getAllKnownImplementors(iface.name());
      for (final ClassInfo implementor : implementors) {
        resteasyDeploymentData.getScannedResourceClasses().add(implementor.name().toString());
      }
    }
  }
Esempio n. 27
0
 private boolean isInterface(int modifiers) {
   return Modifier.isInterface(modifiers);
 }
  /**
   * 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.");
  }
 /** Return whether the class is an interface. */
 public boolean isInterface() {
   return Modifier.isInterface(this.accessFlags);
 }
Esempio n. 30
0
    public static void invokeTests(
        @NotNull InMemoryJavaGenerationHandler generationHandler,
        List<SModel> outputModels,
        junit.framework.TestResult testResult,
        ClassLoader baseClassLoader) {
      Condition<SNode> cond =
          new Condition<SNode>() {
            public boolean met(SNode node) {
              return node.isInstanceOfConcept(BootstrapLanguages.concept_baseLanguage_ClassConcept);
            }
          };
      for (final SModel model : outputModels) {
        Iterable<SNode> iterable = new ConditionalIterable<SNode>(model.roots(), cond);
        for (final SNode outputRoot : iterable) {
          if (baseClassLoader == null) {
            baseClassLoader = model.getClass().getClassLoader();
          }
          ClassLoader classLoader = generationHandler.getCompiler().getClassLoader(baseClassLoader);
          try {
            String className =
                ModelAccess.instance()
                    .runReadAction(
                        new Computable<String>() {
                          public String compute() {
                            return model.getLongName() + "." + outputRoot.getName();
                          }
                        });
            final Class testClass = Class.forName(className, true, classLoader);
            if (Modifier.isAbstract(testClass.getModifiers())
                || Modifier.isInterface(testClass.getModifiers())) continue;
            if (Modifier.isPrivate(testClass.getModifiers())) continue;
            if (testClass.getAnnotation(
                    classLoader.loadClass("jetbrains.mps.baseLanguage.util.plugin.run.MPSLaunch"))
                != null) continue;

            List<Method> testMethods = new ArrayList<Method>();
            Class<TestCase> testCaseClass =
                (Class<TestCase>) classLoader.loadClass(TestCase.class.getName());
            boolean isTestCase = testCaseClass.isAssignableFrom(testClass);

            for (Method method : testClass.getMethods()) {
              if (method.getAnnotation(
                          (Class<Annotation>) classLoader.loadClass(org.junit.Test.class.getName()))
                      != null
                  || (method.getName().startsWith("test") && isTestCase)) {
                testMethods.add(method);
              }
            }

            for (Method testMethod : testMethods) {
              try {
                final Object instance = testClass.newInstance();
                Method setName = testCaseClass.getMethod("setName", String.class);
                setName.invoke(instance, testMethod.getName());
                Method runMethod =
                    testCaseClass.getMethod(
                        "run", classLoader.loadClass(junit.framework.TestResult.class.getName()));
                runMethod.invoke(instance, testResult);
              } catch (Throwable ignored) {
                // if one test fails, we still want to try to run the others
                System.err.println(testClass.getCanonicalName() + ":");
                ignored.printStackTrace();
              }
            }
          } catch (Throwable ignored) {
            ignored.printStackTrace(); // exceptions happen for a reason
          }
        }
      }
    }