Search in sources :

Example 1 with ClassFile

use of javassist.bytecode.ClassFile in project hibernate-orm by hibernate.

the class ClassFileArchiveEntryHandler method toClassFile.

private ClassFile toClassFile(ArchiveEntry entry) {
    final InputStream inputStream = entry.getStreamAccess().accessInputStream();
    final DataInputStream dataInputStream = new DataInputStream(inputStream);
    try {
        return new ClassFile(dataInputStream);
    } catch (IOException e) {
        throw new ArchiveException("Could not build ClassFile", e);
    } finally {
        try {
            dataInputStream.close();
        } catch (Exception ignore) {
        }
        try {
            inputStream.close();
        } catch (IOException ignore) {
        }
    }
}
Also used : ClassFile(javassist.bytecode.ClassFile) DataInputStream(java.io.DataInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) DataInputStream(java.io.DataInputStream) ArchiveException(org.hibernate.boot.archive.spi.ArchiveException) ArchiveException(org.hibernate.boot.archive.spi.ArchiveException) IOException(java.io.IOException)

Example 2 with ClassFile

use of javassist.bytecode.ClassFile in project hibernate-orm by hibernate.

the class BulkAccessorFactory method create.

BulkAccessor create() {
    final Method[] getters = new Method[getterNames.length];
    final Method[] setters = new Method[setterNames.length];
    findAccessors(targetBean, getterNames, setterNames, types, getters, setters);
    final Class beanClass;
    try {
        final ClassFile classfile = make(getters, setters);
        final ClassLoader loader = this.getClassLoader();
        if (writeDirectory != null) {
            FactoryHelper.writeFile(classfile, writeDirectory);
        }
        beanClass = FactoryHelper.toClass(classfile, loader, getDomain());
        return (BulkAccessor) this.newInstance(beanClass);
    } catch (Exception e) {
        throw new BulkAccessorException(e.getMessage(), e);
    }
}
Also used : ClassFile(javassist.bytecode.ClassFile) Method(java.lang.reflect.Method) CannotCompileException(javassist.CannotCompileException)

Example 3 with ClassFile

use of javassist.bytecode.ClassFile in project ratpack by ratpack.

the class DescribingHandlers method describeTo.

public static void describeTo(Handler handler, StringBuilder stringBuilder) {
    Class<? extends Handler> clazz = handler.getClass();
    if (clazz.isAnonymousClass()) {
        ClassPool pool = ClassPool.getDefault();
        CtClass ctClass;
        try {
            ctClass = pool.get(clazz.getName());
            CtBehavior[] behaviors = ctClass.getDeclaredBehaviors();
            List<CtBehavior> withLineNumber = Arrays.asList(behaviors).stream().filter(input -> input.getMethodInfo().getLineNumber(0) > 0).sorted((o1, o2) -> Integer.valueOf(o1.getMethodInfo().getLineNumber(0)).compareTo(o2.getMethodInfo().getLineNumber(0))).collect(Collectors.toList());
            if (!withLineNumber.isEmpty()) {
                CtBehavior method = withLineNumber.get(0);
                int lineNumber = method.getMethodInfo().getLineNumber(0);
                ClassFile classFile = ctClass.getClassFile();
                String sourceFile = classFile.getSourceFile();
                if (lineNumber != -1 && sourceFile != null) {
                    stringBuilder.append("anonymous class ").append(clazz.getName()).append(" at approximately line ").append(lineNumber).append(" of ").append(sourceFile);
                    return;
                }
            }
        } catch (NotFoundException ignore) {
        // fall through
        }
    }
    stringBuilder.append(clazz.getName());
}
Also used : CtBehavior(javassist.CtBehavior) Arrays(java.util.Arrays) List(java.util.List) ClassFile(javassist.bytecode.ClassFile) Handler(ratpack.handling.Handler) NotFoundException(javassist.NotFoundException) CtBehavior(javassist.CtBehavior) CtClass(javassist.CtClass) Collectors(java.util.stream.Collectors) ClassPool(javassist.ClassPool) CtClass(javassist.CtClass) ClassFile(javassist.bytecode.ClassFile) ClassPool(javassist.ClassPool) NotFoundException(javassist.NotFoundException)

Example 4 with ClassFile

use of javassist.bytecode.ClassFile in project ProxProx by GoMint.

the class PluginAutoDetector method checkPlugin.

/**
 * Check if the jar given is useable as plugin
 *
 * @param jarFile The jar file which should be checked
 * @return a loaded plugin meta or null when not usable as plugin
 */
public PluginMeta checkPlugin(JarFile jarFile) {
    Enumeration<JarEntry> jarEntries = jarFile.entries();
    if (jarEntries == null) {
        logger.warn("Could not load Plugin. File " + jarFile + " is empty");
        return null;
    }
    try {
        while (jarEntries.hasMoreElements()) {
            JarEntry jarEntry = jarEntries.nextElement();
            if (jarEntry != null && jarEntry.getName().endsWith(".class")) {
                ClassFile classFile = new ClassFile(new DataInputStream(jarFile.getInputStream(jarEntry)));
                if (classFile.getSuperclass().equals("io.gomint.proxprox.api.plugin.Plugin")) {
                    PluginMeta pluginDescription = new PluginMeta();
                    pluginDescription.setName(classFile.getName().substring(classFile.getName().lastIndexOf('.') + 1));
                    AnnotationsAttribute visible = (AnnotationsAttribute) classFile.getAttribute(AnnotationsAttribute.visibleTag);
                    for (Annotation annotation : visible.getAnnotations()) {
                        switch(annotation.getTypeName()) {
                            case "io.gomint.proxprox.api.plugin.annotation.Description":
                                pluginDescription.setDescription(((StringMemberValue) annotation.getMemberValue("value")).getValue());
                                break;
                            case "io.gomint.proxprox.api.plugin.annotation.Version":
                                int major = ((IntegerMemberValue) annotation.getMemberValue("major")).getValue();
                                int minor = ((IntegerMemberValue) annotation.getMemberValue("minor")).getValue();
                                pluginDescription.setVersion(new PluginVersion(major, minor));
                                break;
                            case "io.gomint.proxprox.api.plugin.annotation.Depends":
                                MemberValue[] dependsValues = ((ArrayMemberValue) annotation.getMemberValue("value")).getValue();
                                HashSet<String> dependsStringValues = new HashSet<>();
                                for (MemberValue value : dependsValues) {
                                    dependsStringValues.add(((StringMemberValue) value).getValue());
                                }
                                pluginDescription.setDepends(dependsStringValues);
                                break;
                            case "io.gomint.proxprox.api.plugin.annotation.Name":
                                pluginDescription.setName(((StringMemberValue) annotation.getMemberValue("value")).getValue());
                                break;
                            default:
                                break;
                        }
                    }
                    pluginDescription.setMainClass(classFile.getName());
                    return pluginDescription;
                }
            }
        }
        return null;
    } catch (IOException e) {
        logger.warn("Could not load Plugin. File " + jarFile + " is corrupted", e);
        return null;
    }
}
Also used : ClassFile(javassist.bytecode.ClassFile) PluginMeta(io.gomint.proxprox.api.plugin.PluginMeta) AnnotationsAttribute(javassist.bytecode.AnnotationsAttribute) IOException(java.io.IOException) JarEntry(java.util.jar.JarEntry) DataInputStream(java.io.DataInputStream) PluginVersion(io.gomint.proxprox.api.plugin.PluginVersion) HashSet(java.util.HashSet)

Example 5 with ClassFile

use of javassist.bytecode.ClassFile in project latke by b3log.

the class Discoverer method discover.

/**
 * Scans classpath to discover bean classes.
 *
 * @param scanPath the paths to scan, using ',' as the separator. There are two types of the scanPath:
 * <ul>
 *   <li>package: org.b3log.process</li>
 *   <li>ant-style classpath: org/b3log/** /*process.class</li>
 * </ul>
 * @return discovered classes
 * @throws Exception exception
 */
public static Collection<Class<?>> discover(final String scanPath) throws Exception {
    if (Strings.isEmptyOrNull(scanPath)) {
        throw new IllegalStateException("Please specify the [scanPath]");
    }
    LOGGER.debug("scanPath[" + scanPath + "]");
    // See issue #17 (https://github.com/b3log/latke/issues/17) for more details
    final Collection<Class<?>> ret = new HashSet<Class<?>>();
    final String[] splitPaths = scanPath.split(",");
    // Adds some built-in components
    final String[] paths = ArrayUtils.concatenate(splitPaths, BUILT_IN_COMPONENT_PKGS);
    final Set<URL> urls = new LinkedHashSet<URL>();
    for (String path : paths) {
        /*
             * the being two types of the scanPath.
             *  1 package: org.b3log.process
             *  2 ant-style classpath: org/b3log/** /*process.class
             */
        if (!AntPathMatcher.isPattern(path)) {
            path = path.replaceAll("\\.", "/") + "/**/*.class";
        }
        urls.addAll(ClassPathResolver.getResources(path));
    }
    for (URL url : urls) {
        final DataInputStream classInputStream = new DataInputStream(url.openStream());
        final ClassFile classFile = new ClassFile(classInputStream);
        final String className = classFile.getName();
        final AnnotationsAttribute annotationsAttribute = (AnnotationsAttribute) classFile.getAttribute(AnnotationsAttribute.visibleTag);
        if (null == annotationsAttribute) {
            LOGGER.log(Level.TRACE, "The class[name={0}] is not a bean", className);
            continue;
        }
        final ConstPool constPool = classFile.getConstPool();
        final Annotation[] annotations = annotationsAttribute.getAnnotations();
        boolean maybeBeanClass = false;
        for (final Annotation annotation : annotations) {
            if (annotation.getTypeName().equals(RequestProcessor.class.getName())) {
                // Request Processor is singleton scoped
                final Annotation singletonAnnotation = new Annotation("javax.inject.Singleton", constPool);
                annotationsAttribute.addAnnotation(singletonAnnotation);
                classFile.addAttribute(annotationsAttribute);
                classFile.setVersionToJava5();
                maybeBeanClass = true;
                break;
            }
            if (annotation.getTypeName().equals(Service.class.getName()) || (annotation.getTypeName()).equals(Repository.class.getName())) {
                // Service and Repository is singleton scoped by default
                maybeBeanClass = true;
                break;
            }
            if (annotation.getTypeName().equals(Named.class.getName())) {
                // Annoatated with Named maybe a bean class
                maybeBeanClass = true;
                break;
            }
        // Others will not load
        }
        if (maybeBeanClass) {
            Class<?> clz = null;
            try {
                clz = Thread.currentThread().getContextClassLoader().loadClass(className);
            } catch (final ClassNotFoundException e) {
                LOGGER.log(Level.ERROR, "some error to load the class[" + className + "]", e);
            }
            ret.add(clz);
        }
    }
    return ret;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ConstPool(javassist.bytecode.ConstPool) Named(org.b3log.latke.ioc.inject.Named) ClassFile(javassist.bytecode.ClassFile) AnnotationsAttribute(javassist.bytecode.AnnotationsAttribute) DataInputStream(java.io.DataInputStream) URL(java.net.URL) Annotation(javassist.bytecode.annotation.Annotation) RequestProcessor(org.b3log.latke.servlet.annotation.RequestProcessor) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Aggregations

ClassFile (javassist.bytecode.ClassFile)51 DataInputStream (java.io.DataInputStream)15 ClassPool (javassist.ClassPool)15 DataOutputStream (java.io.DataOutputStream)14 CtClass (javassist.CtClass)14 AnnotationsAttribute (javassist.bytecode.AnnotationsAttribute)14 ConstPool (javassist.bytecode.ConstPool)13 ByteArrayOutputStream (java.io.ByteArrayOutputStream)12 ByteArrayInputStream (java.io.ByteArrayInputStream)11 IOException (java.io.IOException)11 MethodInfo (javassist.bytecode.MethodInfo)11 CtField (javassist.CtField)10 NotFoundException (javassist.NotFoundException)9 Annotation (javassist.bytecode.annotation.Annotation)9 Test (org.junit.Test)9 IllegalClassFormatException (java.lang.instrument.IllegalClassFormatException)8 HashSet (java.util.HashSet)7 CtMethod (javassist.CtMethod)7 FieldInfo (javassist.bytecode.FieldInfo)7 Bytecode (javassist.bytecode.Bytecode)5