Search in sources :

Example 1 with Annotation

use of javassist.bytecode.annotation.Annotation 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)

Example 2 with Annotation

use of javassist.bytecode.annotation.Annotation in project libSBOLj by SynBioDex.

the class OBOTermCreator method createTerm.

// /**
// * Dynamically generates a Class file, for an interface that represents an OBO term with the given fields.
// *
// * The OBO term is uniquely identified by the id, and if a term with this id has been converted into a Class
// * file already, then that Class file (cached within the OBOTermCreator object) will be returned immediately.
// *
// * @param id
// * @param name
// * @param def
// * @param comments
// * @param is_a
// * @param relTypes
// * @param relTypedefs
// * @return term
// * @throws CannotCompileException
// */
public Class createTerm(String id, String name, String def, String[] comments, Class[] is_a, Class[] relTypes, String[] relTypedefs) throws CannotCompileException {
    String ccClassName = unmangleName(name);
    if (created.containsKey(id)) {
        return created.get(id);
    }
    if (created.containsKey(ccClassName)) {
        return created.get(ccClassName);
    }
    OBOAnnotationParser obo = new OBOAnnotationParser();
    ClassPool cp = ClassPool.getDefault();
    CtClass stringClass = null, stringArrayClass = null;
    try {
        stringClass = cp.get("java.lang.String");
        stringArrayClass = cp.get("java.lang.String[]");
    } catch (NotFoundException e) {
        throw new IllegalStateException(e);
    }
    CtClass cc = cp.makeInterface(ccClassName);
    cc.setModifiers(javassist.Modifier.INTERFACE | javassist.Modifier.PUBLIC);
    ClassFile ccFile = cc.getClassFile();
    ConstPool constpool = ccFile.getConstPool();
    Annotation termAnnotation = new Annotation("org.sc.obo.annotations.Term", constpool);
    CtField idField = new CtField(stringClass, "id", cc);
    idField.setModifiers(javassist.Modifier.PUBLIC | javassist.Modifier.STATIC | javassist.Modifier.FINAL);
    CtField nameField = new CtField(stringClass, "name", cc);
    nameField.setModifiers(javassist.Modifier.PUBLIC | javassist.Modifier.STATIC | javassist.Modifier.FINAL);
    CtField defField = new CtField(stringClass, "def", cc);
    defField.setModifiers(javassist.Modifier.PUBLIC | javassist.Modifier.STATIC | javassist.Modifier.FINAL);
    cc.addField(idField, CtField.Initializer.constant(removeSlashes(id)));
    cc.addField(nameField, CtField.Initializer.constant(removeSlashes(name)));
    cc.addField(defField, CtField.Initializer.constant(removeSlashes(def)));
    if (is_a != null) {
        for (Class superClass : is_a) {
            if (!obo.isTerm(superClass)) {
                throw new IllegalArgumentException(superClass.getCanonicalName());
            }
            try {
                CtClass superCtClass = cp.get(superClass.getCanonicalName());
                cc.addInterface(superCtClass);
            } catch (NotFoundException e) {
                throw new IllegalArgumentException(e);
            }
        }
    }
    /*
		 * Finally, we convert all the relTypes/relTypedefs into methods.
		 *
		 * The main trick here is to do this in a way that the method names don't clash!
		 *
		 * We want to rename each method to a form that's unique to this class as well -- the reason is that
		 * Class A and Class B can have incompatible methods with the same name, which is fine since neither of
		 * them is a superclass (super-interface, whatevs) of the other.
		 *
		 * However, as soon as we define a Class C that extends both interfaces A & B, we have a problem -- suddenly
		 * we inherit both methods, but with incompatible types.
		 *
		 * So we need to mangle the names of A and B's classes, so that they are (a) descriptive, but (b) don't
		 * clash with other class's method names.  This leads to ugly code generation, but ... it works.
		 */
    if (relTypes != null && relTypedefs != null) {
        if (relTypes.length != relTypedefs.length) {
            throw new IllegalArgumentException();
        }
        String[] nonDups = renameDuplicates(relTypedefs);
        for (int i = 0; i < relTypes.length; i++) {
            try {
                if (relTypes[i] == null) {
                    throw new IllegalArgumentException(id + " " + Arrays.asList(relTypes));
                }
                Class arrayType = relTypes[i].isArray() ? relTypes[i] : getArrayType(relTypes[i]);
                String typeName = arrayType.getCanonicalName();
                String methodName = findNonConflictingName(ccClassName, arrayType, nonDups[i], null, is_a);
                CtClass relTypeClass = cp.get(typeName);
                CtMethod relMethod = new CtMethod(relTypeClass, methodName, new CtClass[] {}, cc);
                relMethod.setModifiers(Modifier.PUBLIC | Modifier.ABSTRACT);
                // We need to create this with the *original* typedef name,
                // not the new (non-clashing) method name.  That way, we can recover the original
                // name of the property from the (mangled) method name.
                Annotation relAnnotation = new Annotation("org.sc.obo.annotations.Relates", constpool);
                relAnnotation.addMemberValue("value", new StringMemberValue(relTypedefs[i], ccFile.getConstPool()));
                AnnotationsAttribute annotations = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag);
                annotations.addAnnotation(relAnnotation);
                relMethod.getMethodInfo().addAttribute(annotations);
                cc.addMethod(relMethod);
            } catch (NotFoundException e) {
                throw new IllegalArgumentException(e);
            }
        }
    }
    AnnotationsAttribute attr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag);
    attr.addAnnotation(termAnnotation);
    ccFile.addAttribute(attr);
    Class c = cc.toClass();
    created.put(id, c);
    created.put(ccClassName, c);
    return c;
}
Also used : ConstPool(javassist.bytecode.ConstPool) ClassFile(javassist.bytecode.ClassFile) StringMemberValue(javassist.bytecode.annotation.StringMemberValue) AnnotationsAttribute(javassist.bytecode.AnnotationsAttribute) ClassPool(javassist.ClassPool) NotFoundException(javassist.NotFoundException) Annotation(javassist.bytecode.annotation.Annotation) CtClass(javassist.CtClass) CtField(javassist.CtField) CtClass(javassist.CtClass) CtMethod(javassist.CtMethod)

Example 3 with Annotation

use of javassist.bytecode.annotation.Annotation in project fakereplace by fakereplace.

the class AnnotationBuilder method createJavassistAnnotation.

public static javassist.bytecode.annotation.Annotation createJavassistAnnotation(java.lang.annotation.Annotation annotation, ConstPool cp) {
    try {
        javassist.bytecode.annotation.Annotation a = new Annotation(annotation.annotationType().getName(), cp);
        for (Method m : annotation.annotationType().getDeclaredMethods()) {
            Object val = m.invoke(annotation);
            a.addMemberValue(m.getName(), createMemberValue(m.getReturnType(), val, cp));
        }
        return a;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : Annotation(javassist.bytecode.annotation.Annotation) Method(java.lang.reflect.Method) Annotation(javassist.bytecode.annotation.Annotation)

Example 4 with Annotation

use of javassist.bytecode.annotation.Annotation in project fakereplace by fakereplace.

the class FinalMethodManipulator method transformClass.

public boolean transformClass(ClassFile file, ClassLoader loader, boolean modifiableClass, final Set<MethodInfo> modifiedMethods) {
    if (!modifiableClass) {
        return false;
    }
    boolean modified = false;
    for (Object i : file.getMethods()) {
        MethodInfo m = (MethodInfo) i;
        if ((m.getAccessFlags() & AccessFlag.FINAL) != 0) {
            m.setAccessFlags(m.getAccessFlags() & ~AccessFlag.FINAL);
            // ClassDataStore.addFinalMethod(file.getName(), m.getName(),
            // m.getDescriptor());
            AnnotationsAttribute at = (AnnotationsAttribute) m.getAttribute(AnnotationsAttribute.visibleTag);
            if (at == null) {
                at = new AnnotationsAttribute(file.getConstPool(), AnnotationsAttribute.visibleTag);
                m.addAttribute(at);
            }
            at.addAnnotation(new Annotation(ModifiedMethod.class.getName(), file.getConstPool()));
            m.addAttribute(new AttributeInfo(file.getConstPool(), Constants.FINAL_METHOD_ATTRIBUTE, new byte[0]));
            modified = true;
        }
    }
    return modified;
}
Also used : AttributeInfo(javassist.bytecode.AttributeInfo) AnnotationsAttribute(javassist.bytecode.AnnotationsAttribute) MethodInfo(javassist.bytecode.MethodInfo) Annotation(javassist.bytecode.annotation.Annotation)

Example 5 with Annotation

use of javassist.bytecode.annotation.Annotation in project compss by bsc-wdc.

the class AddOrchestration method main.

public static void main(String[] args) throws NotFoundException, NameNotFoundException, CannotCompileException, IOException {
    if (args.length < 2) {
        ErrorManager.fatal("Error: missing arguments for loader");
    }
    String className = args[0];
    String classPackage = getPackage(className);
    // Pool creation
    ClassPool pool = ClassPool.getDefault();
    if (classPackage != null && classPackage.trim().length() > 0) {
        pool.importPackage(classPackage);
    }
    // Extracting the class
    CtClass cc = pool.getCtClass(className);
    ClassFile ccFile = cc.getClassFile();
    ConstPool constpool = ccFile.getConstPool();
    for (int i = 1; i < args.length; i++) {
        String methodLabel = args[i];
        String methodName = getMethodName(methodLabel);
        CtClass[] params = getParamClasses(methodLabel, pool);
        CtMethod methodDescriptor = cc.getDeclaredMethod(methodName, params);
        AnnotationsAttribute attr = (AnnotationsAttribute) methodDescriptor.getMethodInfo().getAttribute(AnnotationsAttribute.visibleTag);
        if (attr == null) {
            // Create the annotation
            attr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag);
        }
        Annotation annot = new Annotation(LoaderConstants.CLASS_ANNOTATIONS_ORCHESTRATION, constpool);
        attr.addAnnotation(annot);
        methodDescriptor.getMethodInfo().addAttribute(attr);
    }
    cc.writeFile();
// transform the ctClass to java class
/*
         * Class<?> dynamiqueBeanClass = cc.toClass();
         * 
         * //instanciating the updated class AddOrchestration ao = (AddOrchestration) dynamiqueBeanClass.newInstance();
         * 
         * try{ Method fooMethod = ao.getClass().getDeclaredMethod(methodName, new Class<?>[] { int.class }); //getting
         * the annotation Orchestration o = (Orchestration) fooMethod.getAnnotation(Orchestration.class);
         * System.out.println("METHOD: " + fooMethod); System.out.println("ANNOTATION: " + o); } catch(Exception e){
         * e.printStackTrace(); }
         */
}
Also used : CtClass(javassist.CtClass) ConstPool(javassist.bytecode.ConstPool) ClassFile(javassist.bytecode.ClassFile) AnnotationsAttribute(javassist.bytecode.AnnotationsAttribute) ClassPool(javassist.ClassPool) CtMethod(javassist.CtMethod) Annotation(javassist.bytecode.annotation.Annotation)

Aggregations

Annotation (javassist.bytecode.annotation.Annotation)26 AnnotationsAttribute (javassist.bytecode.AnnotationsAttribute)19 StringMemberValue (javassist.bytecode.annotation.StringMemberValue)12 ConstPool (javassist.bytecode.ConstPool)11 ClassFile (javassist.bytecode.ClassFile)9 ArrayList (java.util.ArrayList)7 CtClass (javassist.CtClass)7 ClassPool (javassist.ClassPool)6 CtMethod (javassist.CtMethod)5 AnnotationMemberValue (javassist.bytecode.annotation.AnnotationMemberValue)5 ArrayMemberValue (javassist.bytecode.annotation.ArrayMemberValue)5 ByteArrayInputStream (java.io.ByteArrayInputStream)4 IllegalClassFormatException (java.lang.instrument.IllegalClassFormatException)4 MethodInfo (javassist.bytecode.MethodInfo)4 EnumMemberValue (javassist.bytecode.annotation.EnumMemberValue)4 MemberValue (javassist.bytecode.annotation.MemberValue)4 DataInputStream (java.io.DataInputStream)3 HashSet (java.util.HashSet)3 CtField (javassist.CtField)3 ClassMemberValue (javassist.bytecode.annotation.ClassMemberValue)3