Search in sources :

Example 1 with ClassPath

use of com.google.common.reflect.ClassPath in project checkstyle by checkstyle.

the class CheckUtil method getCheckstyleModules.

/**
     * Gets all checkstyle's modules.
     * @return the set of checkstyle's module classes.
     * @throws IOException if the attempt to read class path resources failed.
     * @see #isCheckstyleModule(Class)
     */
public static Set<Class<?>> getCheckstyleModules() throws IOException {
    final Set<Class<?>> checkstyleModules = new HashSet<>();
    final ClassLoader loader = Thread.currentThread().getContextClassLoader();
    final ClassPath classpath = ClassPath.from(loader);
    final String packageName = "com.puppycrawl.tools.checkstyle";
    final ImmutableSet<ClassPath.ClassInfo> checkstyleClasses = classpath.getTopLevelClassesRecursive(packageName);
    for (ClassPath.ClassInfo clazz : checkstyleClasses) {
        final Class<?> loadedClass = clazz.load();
        if (isCheckstyleModule(loadedClass)) {
            checkstyleModules.add(loadedClass);
        }
    }
    return checkstyleModules;
}
Also used : ClassPath(com.google.common.reflect.ClassPath) HashSet(java.util.HashSet)

Example 2 with ClassPath

use of com.google.common.reflect.ClassPath in project alluxio by Alluxio.

the class EvictorContractTest method data.

/**
   * @return a list of all evictors
   */
@Parameterized.Parameters
public static Collection<Object[]> data() {
    // Run this test against all types of Evictors
    List<Object[]> list = new ArrayList<>();
    try {
        String packageName = Reflection.getPackageName(Evictor.class);
        ClassPath path = ClassPath.from(Thread.currentThread().getContextClassLoader());
        List<ClassPath.ClassInfo> clazzInPackage = new ArrayList<>(path.getTopLevelClassesRecursive(packageName));
        for (ClassPath.ClassInfo clazz : clazzInPackage) {
            Set<Class<?>> interfaces = new HashSet<>(Arrays.asList(clazz.load().getInterfaces()));
            if (!Modifier.isAbstract(clazz.load().getModifiers()) && interfaces.size() > 0 && interfaces.contains(Evictor.class)) {
                list.add(new Object[] { clazz.getName() });
            }
        }
    } catch (Exception e) {
        Assert.fail("Failed to find implementation of allocate strategy");
    }
    return list;
}
Also used : ClassPath(com.google.common.reflect.ClassPath) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet)

Example 3 with ClassPath

use of com.google.common.reflect.ClassPath in project pyramid by cheng-li.

the class AppLauncher method matchClass.

private static String matchClass(String className) throws Exception {
    // deal with normal names
    String lower = className.toLowerCase();
    String realName = null;
    ClassPath classPath = ClassPath.from(Thread.currentThread().getContextClassLoader());
    ImmutableSet<ClassPath.ClassInfo> classes = classPath.getTopLevelClasses("edu.neu.ccs.pyramid.application");
    for (ClassPath.ClassInfo classInfo : classes) {
        if (classInfo.getSimpleName().toLowerCase().equals(lower)) {
            realName = classInfo.getName();
            break;
        }
    }
    return realName;
}
Also used : ClassPath(com.google.common.reflect.ClassPath)

Example 4 with ClassPath

use of com.google.common.reflect.ClassPath in project java by kubernetes-client.

the class Yaml method initModelMap.

private static void initModelMap() throws IOException {
    ClassPath cp = ClassPath.from(ClassLoader.getSystemClassLoader());
    Set<ClassPath.ClassInfo> allClasses = cp.getTopLevelClasses("io.kubernetes.client.models");
    for (ClassPath.ClassInfo clazz : allClasses) {
        String groupVersion = getApiGroupVersion(clazz.getSimpleName());
        int len = groupVersion.replace("/", "").length();
        String name = clazz.getSimpleName().substring(len);
        classes.put(groupVersion + "/" + name, clazz.load());
    }
}
Also used : ClassPath(com.google.common.reflect.ClassPath)

Example 5 with ClassPath

use of com.google.common.reflect.ClassPath in project raml-module-builder by folio-org.

the class AnnotationGrabber method generateMappings.

// ^http.*?//.*?/apis/patrons/.*?/fines/.*
// ^http.*?\/\/.*?\/apis\/patrons\/?(.+?)*
// ^http.*?\/\/.*?\/apis\/([^\/]+)\/([^\/]+)(\?.*)
public static JsonObject generateMappings() throws Exception {
    /* this class is one of the drivers for the client generation
     * check if the plugin set the system property in the pom and only if
     * so generate */
    String clientGen = System.getProperty("client.generate");
    String modDescr = System.getProperty("modDescrptor.generate");
    if (clientGen != null) {
        generateClient = true;
    }
    if ("true".equals(modDescr)) {
        generateModDescrptor = true;
    }
    JsonObject globalClassMapping = new JsonObject();
    // get classes in generated package
    ClassPath classPath = ClassPath.from(Thread.currentThread().getContextClassLoader());
    ImmutableSet<ClassPath.ClassInfo> classes = classPath.getTopLevelClasses(RTFConsts.INTERFACE_PACKAGE);
    Collection<Object> classNames = Collections2.transform(classes, new Function<ClassPath.ClassInfo, Object>() {

        @Override
        public Object apply(ClassPath.ClassInfo input) {
            log.info("Mapping functions in " + input.getName() + " class to appropriate urls");
            // not needed - dont need transform function,
            return input.getName();
        // remove
        }
    });
    // loop over all the classes from the package
    classNames.forEach(val -> {
        try {
            ClientGenerator cGen = new ClientGenerator();
            // ----------------- class level annotations -----------------------//
            // -----------------------------------------------------------------//
            // will contain all mappings for a specific class in the package
            JsonObject classSpecificMapping = new JsonObject();
            // get annotations via reflection for a class
            Annotation[] annotations = Class.forName(val.toString()).getAnnotations();
            // create an entry for the class name = ex. "class":"com.sling.rest.jaxrs.resource.BibResource"
            classSpecificMapping.put(CLASS_NAME, val.toString());
            classSpecificMapping.put(INTERFACE_NAME, val.toString());
            // needed info - these are class level annotation - not method level
            for (int i = 0; i < annotations.length; i++) {
                // get the annotation type - example in jersey would we javax.ws.rs.Path
                Class<? extends Annotation> type = annotations[i].annotationType();
                // function
                for (Method method : type.getDeclaredMethods()) {
                    Object value = method.invoke(annotations[i], (Object[]) null);
                    if (type.isAssignableFrom(Path.class)) {
                        classSpecificMapping.put(CLASS_URL, "^/" + value);
                        if (generateClient) {
                            cGen.generateClassMeta(val.toString(), value);
                        }
                        if (generateModDescrptor && classSpecificMapping.getString(CLASS_URL) != null) {
                            String url = classSpecificMapping.getString(CLASS_URL).substring(2);
                            if (!url.contains("rmbtests")) {
                                MDGenerator.ProvidesEntry pe = MDGenerator.INSTANCE.new ProvidesEntry();
                                if (url.contains("_/tenant")) {
                                    url = "_tenant";
                                }
                                pe.setId(url);
                                MDGenerator.INSTANCE.addProvidesEntry(pe);
                            }
                        }
                    }
                }
            }
            // ----------------- method level annotations ------------ //
            // ------------------------------------------------------- //
            /**
             * will be used only if ModuleDescriptor generation is turned on
             * maps all http verbs to a single url
             */
            mdUrl2Verbs = new HashMap<>();
            JsonArray methodsInAPath;
            // iterate over all functions in the class
            Method[] methods = Class.forName(val.toString()).getMethods();
            for (int i = 0; i < methods.length; i++) {
                JsonObject methodObj = new JsonObject();
                JsonObject params = getParameterNames(methods[i]);
                // get annotations on the method and add all info per method to its
                // own methodObj
                Annotation[] methodAn = methods[i].getAnnotations();
                // System.out.println(methods[i].getName());
                // put the name of the function
                methodObj.put(FUNCTION_NAME, methods[i].getName());
                methodObj.put(METHOD_PARAMS, params);
                for (int j = 0; j < methodAn.length; j++) {
                    Class<? extends Annotation> type = methodAn[j].annotationType();
                    // System.out.println("Values of " + type.getName());
                    if (RTFConsts.POSSIBLE_HTTP_METHOD.contains(type.getName())) {
                        // put the method - get or post, etc..
                        methodObj.put(HTTP_METHOD, type.getName());
                    }
                    boolean replaceAccept = false;
                    if (type.isAssignableFrom(Produces.class)) {
                        // this is the accept header, right now can not send */*
                        // so if accept header equals any/ - change this to */*
                        replaceAccept = true;
                    }
                    for (Method method : type.getDeclaredMethods()) {
                        Object value = method.invoke(methodAn[j], (Object[]) null);
                        if (value.getClass().isArray()) {
                            List<Object> retList = new ArrayList<>();
                            for (int k = 0; k < Array.getLength(value); k++) {
                                if (replaceAccept) {
                                    // replace any/any with */* to allow declaring accpet */* which causes compilation issues
                                    // when declared in raml. so declare any/any in raml instead and replaced here
                                    retList.add(((String) Array.get(value, k)).replaceAll("any/any", ""));
                                } else {
                                    retList.add(Array.get(value, k));
                                }
                            }
                            // put generically things like consumes, produces as arrays
                            // since they can have multi values
                            methodObj.put(type.getName(), retList);
                        } else {
                            if (type.isAssignableFrom(Path.class)) {
                                String path = classSpecificMapping.getString(CLASS_URL) + URL_PATH_DELIMITER + value;
                                String regexPath = getRegexForPath(path);
                                // put path to function
                                methodObj.put(METHOD_URL, path);
                                // put regex path to function
                                methodObj.put(REGEX_URL, regexPath);
                            }
                        // System.out.println(" " + method.getName() + ": " + value.toString());
                        }
                    }
                }
                if (generateClient) {
                    cGen.generateMethodMeta(methodObj.getString(FUNCTION_NAME), methodObj.getJsonObject(METHOD_PARAMS), methodObj.getString(METHOD_URL), methodObj.getString(HTTP_METHOD), methodObj.getJsonArray(CONSUMES), methodObj.getJsonArray(PRODUCES));
                }
                // class
                if (methodObj.getString(METHOD_URL) == null) {
                    methodObj.put(METHOD_URL, classSpecificMapping.getString(CLASS_URL));
                    methodObj.put(REGEX_URL, getRegexForPath(classSpecificMapping.getString(CLASS_URL)));
                }
                if (generateModDescrptor) {
                    String verb = methodObj.getString(HTTP_METHOD);
                    verb = verb.substring(verb.lastIndexOf(".") + 1);
                    String rootURL4Service = classSpecificMapping.getString(CLASS_URL).substring(1);
                    /*if(mdUrl2Verbs.get(path.substring(1)) != null){
              mdUrl2Verbs.get(path.substring(1)).add(verb);
            } else {
              mdUrl2Verbs.put(path.substring(1), new JsonArray());
              mdUrl2Verbs.get(path.substring(1)).add(verb);
            }*/
                    if (mdUrl2Verbs.get(rootURL4Service) != null) {
                        mdUrl2Verbs.get(rootURL4Service).add(verb);
                    } else {
                        mdUrl2Verbs.put(rootURL4Service, new HashSet<String>());
                        mdUrl2Verbs.get(rootURL4Service).add(verb);
                    }
                }
                // this is the key - the regex path is the key to the functions
                // represented by this url
                // an array of functions which answer to this url (with get, delete,
                // post, etc... methods)
                methodsInAPath = classSpecificMapping.getJsonArray(methodObj.getString(REGEX_URL));
                if (methodsInAPath == null) {
                    methodsInAPath = new JsonArray();
                    classSpecificMapping.put(methodObj.getString(REGEX_URL), methodsInAPath);
                }
                methodsInAPath.add(methodObj);
            }
            // System.out.println( val.toString() );
            globalClassMapping.put(classSpecificMapping.getString(CLASS_URL), classSpecificMapping);
            if (generateClient) {
                cGen.generateClass(classSpecificMapping);
            }
            if (generateModDescrptor) {
                BiConsumer<String, Set<String>> biConsumer = (key, value) -> {
                    if (!key.contains("_/tenant") && !key.contains("rmbtests")) {
                        MDGenerator.RoutingEntry re = MDGenerator.INSTANCE.new RoutingEntry();
                        JsonArray ja = new JsonArray();
                        value.forEach(verb -> {
                            ja.add(verb);
                        });
                        re.setMethods(ja);
                        re.setEntryPath(key);
                        re.setLevel("30");
                        re.setType("request-response");
                        MDGenerator.INSTANCE.addRoutingEntry(re);
                    }
                };
                mdUrl2Verbs.forEach(biConsumer);
                MDGenerator.INSTANCE.generateMD();
                // this is needed when the MDGenerator is used to generate
                // partial MDs in submodules. the system variable is maintained
                // across the sub module builds and if not reset will generate a
                // partial MD for all sub modules
                System.setProperty("modDescrptor.generate", "false");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    });
    // writeMappings(globalClassMapping);
    return globalClassMapping;
}
Also used : PathParam(javax.ws.rs.PathParam) Array(java.lang.reflect.Array) Produces(javax.ws.rs.Produces) Path(javax.ws.rs.Path) HashMap(java.util.HashMap) Collections2(com.google.common.collect.Collections2) LoggerFactory(io.vertx.core.logging.LoggerFactory) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) QueryParam(javax.ws.rs.QueryParam) Parameter(java.lang.reflect.Parameter) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) DefaultValue(javax.ws.rs.DefaultValue) HeaderParam(javax.ws.rs.HeaderParam) JsonObject(io.vertx.core.json.JsonObject) ClassPath(com.google.common.reflect.ClassPath) Logger(io.vertx.core.logging.Logger) Method(java.lang.reflect.Method) Function(com.google.common.base.Function) ImmutableSet(com.google.common.collect.ImmutableSet) Collection(java.util.Collection) Set(java.util.Set) JsonArray(io.vertx.core.json.JsonArray) List(java.util.List) Annotation(java.lang.annotation.Annotation) ClassPath(com.google.common.reflect.ClassPath) HashSet(java.util.HashSet) ImmutableSet(com.google.common.collect.ImmutableSet) Set(java.util.Set) ArrayList(java.util.ArrayList) JsonObject(io.vertx.core.json.JsonObject) Method(java.lang.reflect.Method) Annotation(java.lang.annotation.Annotation) JsonArray(io.vertx.core.json.JsonArray) JsonObject(io.vertx.core.json.JsonObject)

Aggregations

ClassPath (com.google.common.reflect.ClassPath)26 IOException (java.io.IOException)10 ArrayList (java.util.ArrayList)10 HashSet (java.util.HashSet)8 ClassInfo (com.google.common.reflect.ClassPath.ClassInfo)5 URL (java.net.URL)3 List (java.util.List)3 ReflectionException (io.openems.api.exception.ReflectionException)2 URLClassLoader (java.net.URLClassLoader)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 Set (java.util.Set)2 Predicate (java.util.function.Predicate)2 Logger (org.slf4j.Logger)2 LoggerFactory (org.slf4j.LoggerFactory)2 BuckEventListener (com.facebook.buck.event.BuckEventListener)1 HumanReadableException (com.facebook.buck.util.HumanReadableException)1 VisibleForTesting (com.google.common.annotations.VisibleForTesting)1 Function (com.google.common.base.Function)1 Collections2 (com.google.common.collect.Collections2)1