Search in sources :

Example 56 with ClassPool

use of javassist.ClassPool in project aem-core-wcm-components by Adobe-Marketing-Cloud.

the class FormsHelperStubber method createStub.

public static void createStub() {
    ClassPool classPool = ClassPool.getDefault();
    CtClass ctClass;
    try {
        ctClass = classPool.get(CLASS_NAME);
        // indicates the class has already been stubbed and loaded
        if (ctClass.isFrozen()) {
            return;
        }
        // to remove any dependencies on impl classes.
        for (CtMethod ctMethod : ctClass.getDeclaredMethods()) {
            if (!ctMethod.getName().equals("getContentRequestParameterNames") && !ctMethod.getName().equals("getFormId")) {
                ctMethod.setBody(null);
            }
        }
        // remove the error causing static field declaration
        ctClass.removeField(ctClass.getDeclaredField(ERROR_FIELD));
        // remove the static initializer block calling new on impl class.
        ctClass.removeConstructor(ctClass.getClassInitializer());
        // defer getValues(..) to another method call so that we can manipulate/mock return values
        ctClass.getDeclaredMethod("getValues").setBody("return com.adobe.cq.wcm.core.components.internal.models.v1.form.FormsHelperGetValuesStubMethod.get();");
        // load the stubbed class
        ctClass.toClass();
    } catch (NotFoundException e) {
        e.printStackTrace();
    } catch (CannotCompileException e) {
        e.printStackTrace();
    }
}
Also used : CtClass(javassist.CtClass) ClassPool(javassist.ClassPool) NotFoundException(javassist.NotFoundException) CannotCompileException(javassist.CannotCompileException) CtMethod(javassist.CtMethod)

Example 57 with ClassPool

use of javassist.ClassPool in project wildfly by wildfly.

the class TimeoutTestXAResource method createXATestExceptionClass.

/**
 * Creates new public class named org.jboss.as.test.XATestException.
 */
private static Class<?> createXATestExceptionClass() throws Exception {
    ClassPool pool = ClassPool.getDefault();
    CtClass evalClass = pool.makeClass("org.jboss.as.test.XATestException", pool.get("javax.transaction.xa.XAException"));
    return evalClass.toClass();
}
Also used : CtClass(javassist.CtClass) ClassPool(javassist.ClassPool)

Example 58 with ClassPool

use of javassist.ClassPool in project dubbo by alibaba.

the class Wrapper method makeWrapper.

private static Wrapper makeWrapper(Class<?> c) {
    if (c.isPrimitive()) {
        throw new IllegalArgumentException("Can not create wrapper for primitive type: " + c);
    }
    String name = c.getName();
    ClassLoader cl = ClassUtils.getClassLoader(c);
    StringBuilder c1 = new StringBuilder("public void setPropertyValue(Object o, String n, Object v){ ");
    StringBuilder c2 = new StringBuilder("public Object getPropertyValue(Object o, String n){ ");
    StringBuilder c3 = new StringBuilder("public Object invokeMethod(Object o, String n, Class[] p, Object[] v) throws " + InvocationTargetException.class.getName() + "{ ");
    c1.append(name).append(" w; try{ w = ((").append(name).append(")$1); }catch(Throwable e){ throw new IllegalArgumentException(e); }");
    c2.append(name).append(" w; try{ w = ((").append(name).append(")$1); }catch(Throwable e){ throw new IllegalArgumentException(e); }");
    c3.append(name).append(" w; try{ w = ((").append(name).append(")$1); }catch(Throwable e){ throw new IllegalArgumentException(e); }");
    // <property name, property types>
    Map<String, Class<?>> pts = new HashMap<>();
    // <method desc, Method instance>
    Map<String, Method> ms = new LinkedHashMap<>();
    // method names.
    List<String> mns = new ArrayList<>();
    // declaring method names.
    List<String> dmns = new ArrayList<>();
    // get all public field.
    for (Field f : c.getFields()) {
        String fn = f.getName();
        Class<?> ft = f.getType();
        if (Modifier.isStatic(f.getModifiers()) || Modifier.isTransient(f.getModifiers())) {
            continue;
        }
        c1.append(" if( $2.equals(\"").append(fn).append("\") ){ w.").append(fn).append("=").append(arg(ft, "$3")).append("; return; }");
        c2.append(" if( $2.equals(\"").append(fn).append("\") ){ return ($w)w.").append(fn).append("; }");
        pts.put(fn, ft);
    }
    final ClassPool classPool = new ClassPool(ClassPool.getDefault());
    classPool.appendClassPath(new CustomizedLoaderClassPath(cl));
    List<String> allMethod = new ArrayList<>();
    try {
        final CtMethod[] ctMethods = classPool.get(c.getName()).getMethods();
        for (CtMethod method : ctMethods) {
            allMethod.add(ReflectUtils.getDesc(method));
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    Method[] methods = Arrays.stream(c.getMethods()).filter(method -> allMethod.contains(ReflectUtils.getDesc(method))).collect(Collectors.toList()).toArray(new Method[] {});
    // get all public method.
    boolean hasMethod = hasMethods(methods);
    if (hasMethod) {
        Map<String, Integer> sameNameMethodCount = new HashMap<>((int) (methods.length / 0.75f) + 1);
        for (Method m : methods) {
            sameNameMethodCount.compute(m.getName(), (key, oldValue) -> oldValue == null ? 1 : oldValue + 1);
        }
        c3.append(" try{");
        for (Method m : methods) {
            // ignore Object's method.
            if (m.getDeclaringClass() == Object.class) {
                continue;
            }
            String mn = m.getName();
            c3.append(" if( \"").append(mn).append("\".equals( $2 ) ");
            int len = m.getParameterTypes().length;
            c3.append(" && ").append(" $3.length == ").append(len);
            boolean overload = sameNameMethodCount.get(m.getName()) > 1;
            if (overload) {
                if (len > 0) {
                    for (int l = 0; l < len; l++) {
                        c3.append(" && ").append(" $3[").append(l).append("].getName().equals(\"").append(m.getParameterTypes()[l].getName()).append("\")");
                    }
                }
            }
            c3.append(" ) { ");
            if (m.getReturnType() == Void.TYPE) {
                c3.append(" w.").append(mn).append('(').append(args(m.getParameterTypes(), "$4")).append(");").append(" return null;");
            } else {
                c3.append(" return ($w)w.").append(mn).append('(').append(args(m.getParameterTypes(), "$4")).append(");");
            }
            c3.append(" }");
            mns.add(mn);
            if (m.getDeclaringClass() == c) {
                dmns.add(mn);
            }
            ms.put(ReflectUtils.getDesc(m), m);
        }
        c3.append(" } catch(Throwable e) { ");
        c3.append("     throw new java.lang.reflect.InvocationTargetException(e); ");
        c3.append(" }");
    }
    c3.append(" throw new " + NoSuchMethodException.class.getName() + "(\"Not found method \\\"\"+$2+\"\\\" in class " + c.getName() + ".\"); }");
    // deal with get/set method.
    Matcher matcher;
    for (Map.Entry<String, Method> entry : ms.entrySet()) {
        String md = entry.getKey();
        Method method = entry.getValue();
        if ((matcher = ReflectUtils.GETTER_METHOD_DESC_PATTERN.matcher(md)).matches()) {
            String pn = propertyName(matcher.group(1));
            c2.append(" if( $2.equals(\"").append(pn).append("\") ){ return ($w)w.").append(method.getName()).append("(); }");
            pts.put(pn, method.getReturnType());
        } else if ((matcher = ReflectUtils.IS_HAS_CAN_METHOD_DESC_PATTERN.matcher(md)).matches()) {
            String pn = propertyName(matcher.group(1));
            c2.append(" if( $2.equals(\"").append(pn).append("\") ){ return ($w)w.").append(method.getName()).append("(); }");
            pts.put(pn, method.getReturnType());
        } else if ((matcher = ReflectUtils.SETTER_METHOD_DESC_PATTERN.matcher(md)).matches()) {
            Class<?> pt = method.getParameterTypes()[0];
            String pn = propertyName(matcher.group(1));
            c1.append(" if( $2.equals(\"").append(pn).append("\") ){ w.").append(method.getName()).append("(").append(arg(pt, "$3")).append("); return; }");
            pts.put(pn, pt);
        }
    }
    c1.append(" throw new " + NoSuchPropertyException.class.getName() + "(\"Not found property \\\"\"+$2+\"\\\" field or setter method in class " + c.getName() + ".\"); }");
    c2.append(" throw new " + NoSuchPropertyException.class.getName() + "(\"Not found property \\\"\"+$2+\"\\\" field or getter method in class " + c.getName() + ".\"); }");
    // make class
    long id = WRAPPER_CLASS_COUNTER.getAndIncrement();
    ClassGenerator cc = ClassGenerator.newInstance(cl);
    cc.setClassName((Modifier.isPublic(c.getModifiers()) ? Wrapper.class.getName() : c.getName() + "$sw") + id);
    cc.setSuperClass(Wrapper.class);
    cc.addDefaultConstructor();
    // property name array.
    cc.addField("public static String[] pns;");
    // property type map.
    cc.addField("public static " + Map.class.getName() + " pts;");
    // all method name array.
    cc.addField("public static String[] mns;");
    // declared method name array.
    cc.addField("public static String[] dmns;");
    for (int i = 0, len = ms.size(); i < len; i++) {
        cc.addField("public static Class[] mts" + i + ";");
    }
    cc.addMethod("public String[] getPropertyNames(){ return pns; }");
    cc.addMethod("public boolean hasProperty(String n){ return pts.containsKey($1); }");
    cc.addMethod("public Class getPropertyType(String n){ return (Class)pts.get($1); }");
    cc.addMethod("public String[] getMethodNames(){ return mns; }");
    cc.addMethod("public String[] getDeclaredMethodNames(){ return dmns; }");
    cc.addMethod(c1.toString());
    cc.addMethod(c2.toString());
    cc.addMethod(c3.toString());
    try {
        Class<?> wc = cc.toClass();
        // setup static field.
        wc.getField("pts").set(null, pts);
        wc.getField("pns").set(null, pts.keySet().toArray(new String[0]));
        wc.getField("mns").set(null, mns.toArray(new String[0]));
        wc.getField("dmns").set(null, dmns.toArray(new String[0]));
        int ix = 0;
        for (Method m : ms.values()) {
            wc.getField("mts" + ix++).set(null, m.getParameterTypes());
        }
        return (Wrapper) wc.getDeclaredConstructor().newInstance();
    } catch (RuntimeException e) {
        throw e;
    } catch (Throwable e) {
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        cc.release();
        ms.clear();
        mns.clear();
        dmns.clear();
    }
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) ClassPool(javassist.ClassPool) LinkedHashMap(java.util.LinkedHashMap) Field(java.lang.reflect.Field) CtMethod(javassist.CtMethod) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) CtMethod(javassist.CtMethod)

Example 59 with ClassPool

use of javassist.ClassPool in project HikariCP by brettwooldridge.

the class JavassistProxyFactory method main.

public static void main(String... args) {
    classPool = new ClassPool();
    classPool.importPackage("java.sql");
    classPool.appendClassPath(new LoaderClassPath(JavassistProxyFactory.class.getClassLoader()));
    try {
        // Cast is not needed for these
        String methodBody = "{ try { return delegate.method($$); } catch (SQLException e) { throw checkException(e); } }";
        generateProxyClass(Connection.class, ProxyConnection.class.getName(), methodBody);
        generateProxyClass(Statement.class, ProxyStatement.class.getName(), methodBody);
        generateProxyClass(ResultSet.class, ProxyResultSet.class.getName(), methodBody);
        // For these we have to cast the delegate
        methodBody = "{ try { return ((cast) delegate).method($$); } catch (SQLException e) { throw checkException(e); } }";
        generateProxyClass(PreparedStatement.class, ProxyPreparedStatement.class.getName(), methodBody);
        generateProxyClass(CallableStatement.class, ProxyCallableStatement.class.getName(), methodBody);
        modifyProxyFactory();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : ProxyResultSet(com.zaxxer.hikari.pool.ProxyResultSet) ProxyStatement(com.zaxxer.hikari.pool.ProxyStatement) ProxyConnection(com.zaxxer.hikari.pool.ProxyConnection) ClassPool(javassist.ClassPool) LoaderClassPath(javassist.LoaderClassPath) ProxyPreparedStatement(com.zaxxer.hikari.pool.ProxyPreparedStatement) NotFoundException(javassist.NotFoundException) ProxyCallableStatement(com.zaxxer.hikari.pool.ProxyCallableStatement)

Example 60 with ClassPool

use of javassist.ClassPool in project java-crud-api by kolchagov.

the class OrderedTestRunner method computeTestMethods.

/*
     * (non-Javadoc)
     * 
     * @see org.junit.runners.BlockJUnit4ClassRunner#computeTestMethods()
     */
@Override
protected List<FrameworkMethod> computeTestMethods() {
    // get all methods to be tested
    List<FrameworkMethod> toSort = super.computeTestMethods();
    if (toSort.isEmpty())
        return toSort;
    // a map containing <line_number, method>
    final Map<Integer, FrameworkMethod> testMethods = new TreeMap<>();
    // check that all methods here are declared in the same class, we don't
    // deal with test methods from superclasses that haven't been overridden
    Class<?> clazz = getDeclaringClass(toSort);
    if (clazz == null) {
        // fail explicitly
        System.err.println("OrderedTestRunner can only run test classes that" + " don't have test methods inherited from superclasses");
        return Collections.emptyList();
    }
    // use Javassist to figure out line numbers for methods
    ClassPool pool = ClassPool.getDefault();
    try {
        CtClass cc = pool.get(clazz.getName());
        // all methods in toSort are declared in the same class, we checked
        for (FrameworkMethod m : toSort) {
            String methodName = m.getName();
            CtMethod method = cc.getDeclaredMethod(methodName);
            testMethods.put(method.getMethodInfo().getLineNumber(0), m);
        }
    } catch (NotFoundException e) {
        e.printStackTrace();
    }
    return new ArrayList<>(testMethods.values());
}
Also used : CtClass(javassist.CtClass) ClassPool(javassist.ClassPool) NotFoundException(javassist.NotFoundException) FrameworkMethod(org.junit.runners.model.FrameworkMethod) CtMethod(javassist.CtMethod)

Aggregations

ClassPool (javassist.ClassPool)120 CtClass (javassist.CtClass)93 CtMethod (javassist.CtMethod)48 NotFoundException (javassist.NotFoundException)40 CannotCompileException (javassist.CannotCompileException)28 IOException (java.io.IOException)23 LoaderClassPath (javassist.LoaderClassPath)21 CtField (javassist.CtField)20 CtConstructor (javassist.CtConstructor)17 Test (org.junit.Test)17 ClassFile (javassist.bytecode.ClassFile)15 File (java.io.File)13 Method (java.lang.reflect.Method)13 ByteArrayInputStream (java.io.ByteArrayInputStream)12 ConstPool (javassist.bytecode.ConstPool)12 FileNotFoundException (java.io.FileNotFoundException)11 IllegalClassFormatException (java.lang.instrument.IllegalClassFormatException)9 AnnotationsAttribute (javassist.bytecode.AnnotationsAttribute)9 ClassClassPath (javassist.ClassClassPath)7 MethodInfo (javassist.bytecode.MethodInfo)7