Search in sources :

Example 6 with ClassGraph

use of io.github.classgraph.ClassGraph in project hazelcast by hazelcast.

the class ReflectionUtils method resourcesOf.

@Nonnull
@SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE", justification = "False positive on try-with-resources as of JDK11")
public static Resources resourcesOf(String... packages) {
    String[] paths = stream(packages).map(ReflectionUtils::toPath).toArray(String[]::new);
    ClassGraph classGraph = new ClassGraph().whitelistPackages(packages).whitelistPaths(paths).ignoreClassVisibility();
    try (ScanResult scanResult = classGraph.scan()) {
        Collection<ClassResource> classes = scanResult.getAllClasses().stream().map(ClassResource::new).collect(toList());
        Collection<URL> nonClasses = scanResult.getAllResources().nonClassFilesOnly().getURLs();
        return new Resources(classes, nonClasses);
    }
}
Also used : ScanResult(io.github.classgraph.ScanResult) ClassGraph(io.github.classgraph.ClassGraph) URL(java.net.URL) Nonnull(javax.annotation.Nonnull) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 7 with ClassGraph

use of io.github.classgraph.ClassGraph in project Orchid by JavaEden.

the class OrchidFlags method getInstance.

public static OrchidFlags getInstance() {
    if (instance == null) {
        List<OrchidFlag> orchidFlags = new ArrayList<>();
        new ClassGraph().enableClassInfo().scan().getSubclasses(OrchidFlag.class.getName()).loadClasses(OrchidFlag.class).forEach(matchingClass -> {
            try {
                OrchidFlag option = matchingClass.newInstance();
                if (option != null) {
                    orchidFlags.add(option);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        instance = new OrchidFlags(orchidFlags);
    }
    return instance;
}
Also used : ClassGraph(io.github.classgraph.ClassGraph) ArrayList(java.util.ArrayList)

Example 8 with ClassGraph

use of io.github.classgraph.ClassGraph in project Orchid by JavaEden.

the class ClasspathModuleInstaller method configure.

@Override
protected void configure() {
    final StringBuilder moduleLog = new StringBuilder();
    moduleLog.append("\n--------------------");
    new ClassGraph().enableClassInfo().scan().getSubclasses(OrchidModule.class.getName()).loadClasses(OrchidModule.class).forEach((matchingClass) -> {
        if (isInstantiable(matchingClass)) {
            try {
                OrchidModule provider = matchingClass.newInstance();
                if (provider != null) {
                    install(provider);
                    Manifest manifest = provider.getModuleManifest();
                    boolean isModuleNameProvided = false;
                    if (manifest != null) {
                        String pluginName = manifest.getMainAttributes().getValue("Name");
                        String pluginVersion = manifest.getMainAttributes().getValue("Plugin-Version");
                        if (!EdenUtils.isEmpty(pluginName) && !EdenUtils.isEmpty(pluginVersion)) {
                            // Display plugin info if it is provided in the jar's manifest
                            isModuleNameProvided = true;
                            moduleLog.append("\n * " + pluginName + " " + pluginVersion);
                        }
                    }
                    if (!isModuleNameProvided) {
                        // otherwise print the module's classname, but don't log anonymous-class modules
                        if (!provider.getClass().getName().startsWith("com.eden.orchid.OrchidModule")) {
                            moduleLog.append("\n * " + provider.getClass().getName());
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    moduleLog.append("\n");
    Clog.tag("Auto-loaded modules").log(moduleLog.toString());
}
Also used : ClassGraph(io.github.classgraph.ClassGraph) Manifest(java.util.jar.Manifest)

Example 9 with ClassGraph

use of io.github.classgraph.ClassGraph in project checker-framework by typetools.

the class SourceChecker method logBugInCF.

/**
 * Log (that is, print) an internal error in the framework or a checker.
 *
 * @param ce the internal error to output
 */
private void logBugInCF(BugInCF ce) {
    StringJoiner msg = new StringJoiner(LINE_SEPARATOR);
    if (ce.getCause() != null && ce.getCause() instanceof OutOfMemoryError) {
        msg.add(String.format("OutOfMemoryError (max memory = %d, total memory = %d, free memory = %d)", Runtime.getRuntime().maxMemory(), Runtime.getRuntime().totalMemory(), Runtime.getRuntime().freeMemory()));
    } else {
        msg.add(ce.getMessage());
        boolean noPrintErrorStack = (processingEnv != null && processingEnv.getOptions() != null && processingEnv.getOptions().containsKey("noPrintErrorStack"));
        msg.add("; The Checker Framework crashed.  Please report the crash.");
        if (noPrintErrorStack) {
            msg.add(" To see the full stack trace, don't invoke the compiler with -AnoPrintErrorStack");
        } else {
            if (this.currentRoot != null && this.currentRoot.getSourceFile() != null) {
                msg.add("Compilation unit: " + this.currentRoot.getSourceFile().getName());
            }
            if (this.visitor != null) {
                DiagnosticPosition pos = (DiagnosticPosition) this.visitor.lastVisited;
                if (pos != null) {
                    DiagnosticSource source = new DiagnosticSource(this.currentRoot.getSourceFile(), null);
                    int linenr = source.getLineNumber(pos.getStartPosition());
                    int col = source.getColumnNumber(pos.getStartPosition(), true);
                    String line = source.getLine(pos.getStartPosition());
                    msg.add("Last visited tree at line " + linenr + " column " + col + ":");
                    msg.add(line);
                }
            }
        }
    }
    msg.add("Exception: " + ce.getCause() + "; " + UtilPlume.stackTraceToString(ce.getCause()));
    boolean printClasspath = ce.getCause() instanceof NoClassDefFoundError;
    Throwable cause = ce.getCause().getCause();
    while (cause != null) {
        msg.add("Underlying Exception: " + cause + "; " + UtilPlume.stackTraceToString(cause));
        printClasspath |= cause instanceof NoClassDefFoundError;
        cause = cause.getCause();
    }
    if (printClasspath) {
        msg.add("Classpath:");
        for (URI uri : new ClassGraph().getClasspathURIs()) {
            msg.add(uri.toString());
        }
    }
    printMessage(msg.toString());
}
Also used : DiagnosticSource(com.sun.tools.javac.util.DiagnosticSource) DiagnosticPosition(com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition) ClassGraph(io.github.classgraph.ClassGraph) URI(java.net.URI) StringJoiner(java.util.StringJoiner)

Example 10 with ClassGraph

use of io.github.classgraph.ClassGraph in project checker-framework by typetools.

the class AnnotationFileElementTypes method parseAnnotationFiles.

/**
 * Parses the files in {@code annotationFiles} of the given file type. This includes files listed
 * directly in {@code annotationFiles} and for each listed directory, also includes all files
 * located in that directory (recursively).
 *
 * @param annotationFiles list of files and directories to parse
 * @param fileType the file type of files to parse
 */
private void parseAnnotationFiles(List<String> annotationFiles, AnnotationFileType fileType) {
    SourceChecker checker = factory.getChecker();
    ProcessingEnvironment processingEnv = factory.getProcessingEnv();
    for (String path : annotationFiles) {
        // Special case when running in jtreg.
        String base = System.getProperty("test.src");
        String fullPath = (base == null) ? path : base + "/" + path;
        List<AnnotationFileResource> allFiles = AnnotationFileUtil.allAnnotationFiles(fullPath, fileType);
        if (allFiles != null) {
            for (AnnotationFileResource resource : allFiles) {
                InputStream annotationFileStream;
                try {
                    annotationFileStream = resource.getInputStream();
                } catch (IOException e) {
                    checker.message(Kind.NOTE, "Could not read annotation resource: " + resource.getDescription());
                    continue;
                }
                // We use parseStubFile here even for ajava files because at this stage ajava
                // files are parsed as stub files. The extra annotation data in an ajava file is
                // parsed when type-checking the ajava file's corresponding Java file.
                AnnotationFileParser.parseStubFile(resource.getDescription(), annotationFileStream, factory, processingEnv, annotationFileAnnos, fileType == AnnotationFileType.AJAVA ? AnnotationFileType.AJAVA_AS_STUB : fileType);
            }
        } else {
            // level directory of the jar that contains the checker.
            if (path.startsWith("checker.jar/")) {
                path = path.substring("checker.jar/".length());
            }
            InputStream in = checker.getClass().getResourceAsStream(path);
            if (in != null) {
                AnnotationFileParser.parseStubFile(path, in, factory, processingEnv, annotationFileAnnos, fileType);
            } else {
                // Didn't find the file.  Issue a warning.
                // When using a compound checker, the target file may be found by the
                // current checker's parent checkers. Also check this to avoid a false
                // warning. Currently, only the original checker will try to parse the target
                // file, the parent checkers are only used to reduce false warnings.
                SourceChecker currentChecker = checker;
                boolean findByParentCheckers = false;
                while (currentChecker != null) {
                    URL topLevelResource = currentChecker.getClass().getResource("/" + path);
                    if (topLevelResource != null) {
                        currentChecker.message(Kind.WARNING, path + " should be in the same directory as " + currentChecker.getClass().getSimpleName() + ".class, but is at the top level of a jar file: " + topLevelResource);
                        findByParentCheckers = true;
                        break;
                    } else {
                        currentChecker = currentChecker.getParentChecker();
                    }
                }
                // If there exists one parent checker that can find this file, don't report a warning.
                if (!findByParentCheckers) {
                    File parentPath = new File(path).getParentFile();
                    String parentPathDescription = (parentPath == null ? "current directory" : "directory " + parentPath.getAbsolutePath());
                    String msg = checker.getClass().getSimpleName() + " did not find annotation file or directory " + path + " on classpath or within " + parentPathDescription + (fullPath.equals(path) ? "" : (" or at " + fullPath));
                    StringJoiner sj = new StringJoiner(System.lineSeparator() + "  ");
                    sj.add(msg);
                    sj.add("Classpath:");
                    for (URI uri : new ClassGraph().getClasspathURIs()) {
                        sj.add(uri.toString());
                    }
                    checker.message(Kind.WARNING, sj.toString());
                }
            }
        }
    }
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ClassGraph(io.github.classgraph.ClassGraph) IOException(java.io.IOException) ProcessingEnvironment(javax.annotation.processing.ProcessingEnvironment) URI(java.net.URI) URL(java.net.URL) SourceChecker(org.checkerframework.framework.source.SourceChecker) JarFile(java.util.jar.JarFile) File(java.io.File) StringJoiner(java.util.StringJoiner)

Aggregations

ClassGraph (io.github.classgraph.ClassGraph)21 ScanResult (io.github.classgraph.ScanResult)8 Test (org.junit.Test)8 URLClassLoader (java.net.URLClassLoader)7 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)7 File (java.io.File)5 URL (java.net.URL)5 ArrayList (java.util.ArrayList)4 ClassInfo (io.github.classgraph.ClassInfo)3 HashSet (java.util.HashSet)3 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)2 URI (java.net.URI)2 StringJoiner (java.util.StringJoiner)2 Nonnull (javax.annotation.Nonnull)2 ClassLoaderUtil (com.hazelcast.internal.nio.ClassLoaderUtil)1 ExceptionUtil.sneakyThrow (com.hazelcast.internal.util.ExceptionUtil.sneakyThrow)1 DefaultQueryMetadata (com.querydsl.core.DefaultQueryMetadata)1 GroupExpression (com.querydsl.core.group.GroupExpression)1 DiagnosticSource (com.sun.tools.javac.util.DiagnosticSource)1 DiagnosticPosition (com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition)1