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, ConnectionProxy.class.getName(), methodBody); generateProxyClass(Statement.class, StatementProxy.class.getName(), methodBody); generateProxyClass(ResultSet.class, ResultSetProxy.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, PreparedStatementProxy.class.getName(), methodBody); generateProxyClass( CallableStatement.class, CallableStatementProxy.class.getName(), methodBody); modifyProxyFactory(); } catch (Exception e) { throw new RuntimeException(e); } }
public JavassistInstrumentingClassLoader( ClassLoader classLoader, ClassCache classCache, AndroidTranslator androidTranslator, Setup setup) { super(classLoader, null); this.setup = setup; for (String className : setup.getClassesToDelegateFromRcl()) { delegateLoadingOf(className); } this.classCache = classCache; try { ClassPool classPool = new ClassPool(); classPool.appendClassPath(new LoaderClassPath(classLoader)); if (classLoader != JavassistInstrumentingClassLoader.class.getClassLoader()) { classPool.appendClassPath( new LoaderClassPath(JavassistInstrumentingClassLoader.class.getClassLoader())); } addTranslator(classPool, androidTranslator); } catch (NotFoundException e) { throw new RuntimeException(e); } catch (CannotCompileException e) { throw new RuntimeException(e); } }
public static boolean start(RootDoc rootDoc) throws Exception { List<Class<?>> mbeanIspnClasses = getMBeanClasses(); List<Class<?>> globalClasses = new ArrayList<Class<?>>(); List<Class<?>> namedCacheClasses = new ArrayList<Class<?>>(); for (Class<?> clazz : mbeanIspnClasses) { Scope scope = clazz.getAnnotation(Scope.class); if (scope != null && scope.value() == Scopes.GLOBAL) { debug("Add as global class " + clazz); globalClasses.add(clazz); } else { debug("Add as named cache class " + clazz); namedCacheClasses.add(clazz); } } // Init the Javassist class pool. classPool = ClassPool.getDefault(); classPool.insertClassPath(new ClassClassPath(RhqPluginXmlGenerator.class)); PluginGen pg = new PluginGen(); Props root = new Props(); root.setPluginName("Infinispan"); root.setPluginDescription("Supports management and monitoring of Infinispan"); root.setName("Infinispan Cache Manager"); root.setPkg("org.infinispan.rhq"); root.setDependsOnJmxPlugin(true); root.setDiscoveryClass("CacheManagerDiscovery"); root.setComponentClass("CacheManagerComponent"); root.setSingleton(false); root.setCategory(ResourceCategory.SERVICE); Set<TypeKey> servers = new HashSet<TypeKey>(); servers.add(new TypeKey("JMX Server", "JMX")); servers.add(new TypeKey("JBossAS Server", "JBossAS")); servers.add(new TypeKey("JBossAS Server", "JBossAS5")); root.setRunsInsides(servers); populateMetricsAndOperations(globalClasses, root, false); Props cache = new Props(); cache.setName("Infinispan Cache"); cache.setPkg("org.infinispan.rhq"); cache.setDependsOnJmxPlugin(true); cache.setDiscoveryClass("CacheDiscovery"); cache.setComponentClass("CacheComponent"); cache.setSingleton(false); cache.setCategory(ResourceCategory.SERVICE); populateMetricsAndOperations(namedCacheClasses, cache, true); root.getChildren().add(cache); String metaInfDir = "../../../src/main/resources/META-INF"; new File(metaInfDir).mkdirs(); String targetMetaInfDir = "../../../target/classes/META-INF"; new File(targetMetaInfDir).mkdirs(); pg.createFile(root, "descriptor", "rhq-plugin.xml", metaInfDir); copyFile( new File(metaInfDir + "/rhq-plugin.xml"), new File(targetMetaInfDir + "/rhq-plugin.xml")); return true; }
/* 66: */ /* 67: */ private boolean matchClass(String name, ClassPool pool) /* 68: */ { /* 69: 84 */ if (this.classname.equals(name)) { /* 70: 85 */ return true; /* 71: */ } /* 72: */ try /* 73: */ { /* 74: 88 */ CtClass clazz = pool.get(name); /* 75: 89 */ CtClass declClazz = pool.get(this.classname); /* 76: 90 */ if (clazz.subtypeOf(declClazz)) { /* 77: */ try /* 78: */ { /* 79: 92 */ CtMethod m = clazz.getMethod(this.methodname, this.methodDescriptor); /* 80: 93 */ return m.getDeclaringClass().getName().equals(this.classname); /* 81: */ } /* 82: */ catch (NotFoundException e) /* 83: */ { /* 84: 97 */ return true; /* 85: */ } /* 86: */ } /* 87: */ } /* 88: */ catch (NotFoundException e) /* 89: */ { /* 90:101 */ return false; /* 91: */ } /* 92:104 */ return false; /* 93: */ }
private Object[] extractParams(Mapping mapping, HttpServletRequest request) { Object[] params; ClassPool pool = ClassPool.getDefault(); pool.insertClassPath(new ClassClassPath(mapping.clazz)); CtMethod cm = null; CtClass[] parameterTypes = new CtClass[0]; try { cm = pool.get(mapping.clazz.getName()).getDeclaredMethod(mapping.method.getName()); parameterTypes = cm.getParameterTypes(); } catch (NotFoundException e) { e.printStackTrace(); } if (0 == parameterTypes.length) return new Object[0]; params = new Object[parameterTypes.length]; LocalVariableAttribute attr = (LocalVariableAttribute) cm.getMethodInfo().getCodeAttribute().getAttribute(LocalVariableAttribute.tag); int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1; for (int i = 0; i < params.length; i++) { String name = attr.variableName(i + pos); String typeName = parameterTypes[i].getName(); Binder binder = Binder.valueOf(typeName); Object param = binder.get(name, request, mapping); params[i] = param; } return params; }
// TODO: Implement byte code instrumentation to replace calls to methods that do not exist in // proxy by invoke(callee,methodHash/methodName,args) protected void instrument( CtClass toManipulate, String extRef, ClassPool externalPool, String proxyName, ProxyLoader loader) throws NotFoundException, CannotCompileException { ClassPool proxyPool = getPool(externalPool, loader); // javassist bytecode manipulation // LOG.info(" onWrite: getting proxy "+proxyName+" from pool "+loader.getClassPath()); CtClass proxyCtClass = proxyPool.get(proxyName); // LOG.info(" onWrite: getting external class "+extRef+" from pool "+extCop.getClassPath()); CtClass extRefCtClass = externalPool.get(extRef); if (proxyCtClass.getSuperclass() == extRefCtClass) { CodeConverter conv = new CodeConverter(); conv.replaceNew(extRefCtClass, proxyCtClass, TransparentProxyFactory.factoryMethod); // replace any occurence of "new $extRefClass ()" by "$proxyClass.$factoryMathod" in code of // $className toManipulate.instrument(conv); // e.g. "new TestComponentMain()" is replaced by // "Proxy4_TestComponentMain.newExternalInstance()" in bytecode of class // "ComponentUsingAnotherOne" // LOG.info(" Finished bytecode instrumentation of "+toManipulate.getName()); } }
@Override public void describeTo(StringBuilder stringBuilder) { ClosureUtil.SourceInfo sourceInfo = ClosureUtil.getSourceInfo(invoker.getClosure()); if (sourceInfo == null) { ClassPool pool = ClassPool.getDefault(); try { CtClass ctClass = pool.get(invoker.getClosure().getClass().getName()); CtMethod ctMethod = ctClass.getDeclaredMethod("doCall"); int lineNumber = ctMethod.getMethodInfo().getLineNumber(0); ClassFile classFile = ctClass.getClassFile(); String sourceFile = classFile.getSourceFile(); if (lineNumber != -1 && sourceFile != null) { stringBuilder .append("closure at line ") .append(lineNumber) .append(" of ") .append(sourceFile); } else { stringBuilder.append("closure ").append(invoker.getClosure().getClass().getName()); } } catch (NotFoundException e) { stringBuilder.append(invoker.getClosure().getClass().getName()); } } else { stringBuilder .append("closure at line ") .append(sourceInfo.getLineNumber()) .append(" of ") .append(sourceInfo.getUri()); } }
public void first(Set<String> classNames) throws NotFoundException, ClassNotFoundException { // 扫描注册 ClassPool classPool = ClassPool.getDefault(); String tempClassName = null; Class register = Register.class; CtClass clazz; Object isRegister; Iterator<String> it = classNames.iterator(); while (it.hasNext()) { tempClassName = it.next(); clazz = classPool.get(tempClassName); isRegister = clazz.getAnnotation(register); AnnotationsAttribute a = (AnnotationsAttribute) clazz.getClassFile2().getAttribute(AnnotationsAttribute.visibleTag); Annotation[] as = a.getAnnotations(); for (Annotation an : as) { // System.out.println(String.format("MemberNames:%s ", an.getMemberNames())); Set anSet = an.getMemberNames(); Iterator anit = anSet.iterator(); while (anit.hasNext()) { System.out.println("type:" + anit.next().getClass()); } // AnnotationsAttribute a = (AnnotationsAttribute) // clazz.getClassFile().getAttribute(AnnotationsAttribute.visibleTag); // for() } System.err.println(a); System.err.println(a); // System.err.println(a.getName()); if (null != isRegister) System.out.println(isRegister); } }
/** @param filePath */ private static void execute(File file, String pkg, String path) { String fl = file.getName(); Pattern pt = Pattern.compile(".*\\.class$"); Matcher mc = pt.matcher(fl); if (mc.matches()) { fl = fl.replaceAll("\\.class", ""); try { ClassPool cp = ClassPool.getDefault(); cp.appendClassPath(path); CtClass targetClass = cp.get(pkg + fl); System.out.println(targetClass.getName()); Object[] annList = targetClass.getAnnotations(); for (Object ann : annList) { if (ann instanceof MethodList) { classList.add(targetClass); target = targetClass; } else if (ann instanceof TargetClass) { targetList.add(targetClass); } } } catch (Exception ex) { ex.printStackTrace(); } } }
private static ClassPool configureClassPool() { final ClassPool classPool = new ClassPool(ClassPool.getDefault()); classPool.appendClassPath(new LoaderClassPath(Thread.currentThread().getContextClassLoader())); classPool.appendClassPath(new LoaderClassPath(ClassLoader.getSystemClassLoader())); classPool.importPackage("com.lmax.tool.disruptor"); return classPool; }
/** * Similar to main method but is not static * * @param args command line parameters * @throws Exception if something fails during the execution */ public void doIt2(String[] args) throws Exception { // Se carga la clase para la que se quiere modificar sus bytecodes ClassPool pool = ClassPool.getDefault(); CtClass cc = pool.get("com.jzb.ja.Clase1"); // Se puede iterar imprimiendo los metodos, y su signatura, contenidos en la clase for (CtMethod mm : cc.getMethods()) { System.out.println(mm.getName() + " " + mm.getMethodInfo().getDescriptor()); } // Se puede buscar un metodo en concreto... CtMethod mr = cc.getMethod("diHola", "(Ljava/lang/String;)Ljava/lang/String;"); // ... Borrarlo... cc.removeMethod(mr); // .. Y volver a escribir su .class moficado en una carpeta raiz cc.writeFile("c:\\tmp"); // Posteriormente, tanto por este codigo de creación dinamica, o porque se usa // el fichero .class generado antes, se obtiene un error de "Metodo No Existe" Class c1 = cc.toClass(); Clase1 o1 = (Clase1) c1.newInstance(); System.out.println(o1.sumaUno(2)); System.out.println(o1.diHola("Pepe")); }
public T createJavassistProxy( LoadBalancer loadBalance, ConcurrentMap<String, T> map, Class ifaces) throws Exception { Class<?>[] interfaces = ifaces.getInterfaces(); if (interfaces.length == 1) { ClassPool mPool = new ClassPool(true); CtClass ctClass = mPool.get(interfaces[0].getName()); // 新建代理类 CtClass mCtc = mPool.makeClass(ifaces.getName() + "$JavassistProxy"); mCtc.setSuperclass(ctClass); for (CtMethod method : ctClass.getDeclaredMethods()) { System.out.println(method.getName()); // CtMethod m = new CtMethod(method.getReturnType(), // ,method.getParameterTypes(), mCtc); // cc.addMethod(m); // m.setBody("{ x += $1; }"); mCtc.addMethod(method); // method.setBody(""); } // mCtc.debugWriteFile("/home/liguojun"); return null; } else { return null; } }
// @Test public void ctClassName() throws NotFoundException { ClassPool pool = new ClassPool(true); CtClass ctClass = pool.get("java.lang.String"); logger.info("ctClass:{}", ctClass); logger.info("ctClass:{}", ctClass.getName()); logger.info("ctClass:{}", ctClass.getSimpleName()); }
/** * Verify that CtField is exactly the java.util.Collection, java.util.List or java.util.Set, * otherwise cannot instrument the class' field */ private boolean isCtFieldACollection(CtField ctField) { try { return ctField.getType().equals(cp.get(Collection.class.getName())) || ctField.getType().equals(cp.get(List.class.getName())) || ctField.getType().equals(cp.get(Set.class.getName())); } catch (NotFoundException e) { e.printStackTrace(); return false; } }
private Class<?> injectToPlainClassLoader(ClassLoader classLoader, String className) throws NotFoundException, IllegalArgumentException, IOException, CannotCompileException, IllegalAccessException, InvocationTargetException { ClassPool pool = new ClassPool(); pool.appendClassPath(new LoaderClassPath(classLoader)); pool.appendClassPath(pluginJar.getName()); return injectToPlainClassLoader(pool, classLoader, className); }
/** * Instruments the given directory, reading each .class file, processing it, and writing it back * to the filesystem * * @param configurer an {@link InstrumenterConfigurer} that will setup the actual {@link * Instrumenter} that will be used to process the directory * @param processDirectory the directory with .class files to process * @param extraPath a string containing a list of additional paths to add to the classpath used on * instrumentation. This string is system-dependent, using the platform separator and * directory separator * @throws Exception * @see File#pathSeparator * @see File#separator */ public static void runInstrumentation( @NonNull InstrumenterConfigurer configurer, @NonNull Directory processDirectory, @NonNull String extraPath) throws Exception { ClassPool classPool = new ClassPool(true); classPool.appendPathList(extraPath); classPool.appendClassPath(processDirectory.getAbsolutePath()); InstrumenterImpl instrumenter = new InstrumenterImpl(classPool); configurer.configureInstrumenter(instrumenter); instrumenter.ensureConfigured(); new InstrumentationContext(instrumenter, processDirectory, classPool).doInstrument(); }
// not used anymore. private void notTestGetInner() throws Exception { ClassPool pool = ClassPool.getDefault(); CtClass c = pool.get("javassist.CtMethod.ConstParameter"); CtClass d = pool.get("javassist.CtMethod.ConstParameter"); CtClass e = pool.get("javassist.CtMethod$ConstParameter"); assertSame(c, d); assertSame(c, e); try { c = pool.get("test2.Inner.Fake"); fail("found not-existing class"); } catch (NotFoundException ex) { } }
protected ClassPool getPool(ClassPool externalPool, ProxyLoader loader) throws NotFoundException { ClassPool proxyPool; // TODO Cheating here by mapping the ProxyLoader instead of the ProxyResource. But have to // change that as soon as ProxyResource initCL() sets ProxyLoader itself Object cached = cop2pool.get(loader); if (cached instanceof ClassPool) { proxyPool = (ClassPool) cached; } else { proxyPool = ClassPool.getDefault(); proxyPool.appendClassPath(loader.getClassPath()); cop2pool.put(loader, externalPool); } return proxyPool; }
public void not_testURLClassPath() throws Exception { String host = "www.csg.is.titech.ac.jp"; String path = "/~chiba/tmp/"; String url; ClassPool cp = new ClassPool(null); cp.insertClassPath(new URLClassPath(host, 80, path, "test")); url = cp.find("test.TestClassPath").toString(); System.out.println(url); assertEquals("http://" + host + ":80" + path + "test/TestClassPath.class", url); assertNull(cp.find("test.No")); }
/** initial creation of the class EnergyData and associated elements in the robot */ public static void update(ClassPool pool, CtClass robot) throws CannotCompileException, RuntimeException, NotFoundException { CtClass pgui = pool.get("fr.upmc.dtgui.gui.PersonalizedGUI"); // method createBoard CtMethod cb = pool.getMethod("fr.upmc.dtgui.gui.PersonalizedGUI", "createBoard"); cb.setBody( "{\n" + "fr.upmc.dtgui.gui.RobotTeleoperationBoard board;\n" + "board = new " + robot.getName() + "TeleoperationBoard($0, $0.sizeX - 50);\n" + "return board ;\n" + "}\n"); // method createSensorDataReceptor CtMethod csdr = pool.getMethod("fr.upmc.dtgui.gui.PersonalizedGUI", "createSensorDataReceptor"); csdr.setBody( "{\n" + "fr.upmc.dtgui.gui.SensorDataReceptorInterface sdr = null ;\n" + "sdr = $2.makeSensorDataReceptor(" + "$0.positionDisplay, $1.getSensorDataQueue()," + "$0.absoluteX, $0.absoluteY, $0.controlRadius" + ") ;\n" + "return sdr ;\n" + "}\n"); // method detectRobot CtMethod dr = new CtMethod( CtClass.voidType, "detectRobot", new CtClass[] {pool.get("fr.upmc.dtgui.robot.InstrumentedRobot")}, pgui); dr.setBody( "{\n" + "fr.upmc.dtgui.gui.RobotTeleoperationBoard board = null ;\n" + "fr.upmc.dtgui.gui.SensorDataReceptorInterface sdr = null ;\n" + "if (!this.detected($1)) {\n" + "board = $0.createBoard($1) ;\n" + "sdr = $0.createSensorDataReceptor($1, board) ;\n" + "$0.sensors.put($1, sdr) ;\n" + "$0.boards.put($1, board) ;\n" + "sdr.start() ;\n" + "this.validate() ;\n" + "}\n" + "}\n"); pgui.addMethod(dr); }
private static boolean isCtClassSerializable( JarArchiveComparatorOptions options, CtClass clazz, JarArchiveComparator jarArchiveComparator) { ClassPool pool = clazz.getClassPool(); try { return clazz.subtypeOf(pool.get("java.io.Serializable")); } catch (NotFoundException e) { if (options.isIgnoreMissingClasses()) { return false; } else { throw JApiCmpException.forClassLoading(e, clazz.getName(), jarArchiveComparator); } } }
protected ClassPool getPool(UpgradeableComponentResource extCop) throws NotFoundException { // create a pool for every dependency component with external classes ClassPool externalPool; Object cached = cop2pool.get(extCop); if (cached instanceof ClassPool) { externalPool = (ClassPool) cached; } else { externalPool = ClassPool.getDefault(); String path = extCop.getExtResLocation() + extCop.getCodeBase(); externalPool.appendClassPath(path); // LOG.info(" Creating a ClassPool for dependency Component at "+path); cop2pool.put(extCop, externalPool); } return externalPool; }
public void testInheritance() throws Exception { ClassPool pool = ClassPool.getDefault(); String classname = "test2.Inherit"; CtClass target = pool.get(classname); String src = "public void sampleMethod() {" + " test2.Inherit i = new test2.Inherit();" + " test2.Inherit2 i2 = i;" + " test2.Inherit3 i3 = i;" + " i3.foo2(); i3.foo2(); i2.foo1(); }"; CtMethod newmethod = CtNewMethod.make(src, target); target.addMethod(newmethod); target.writeFile(); }
static TypeParameterMatcher generate(Class<?> type, ClassLoader classLoader) { final String className = "io.netty.util.internal.__matchers__." + type.getName() + "Matcher"; try { try { return (TypeParameterMatcher) Class.forName(className, true, classLoader).newInstance(); } catch (Exception e) { // Not defined in the specified class loader. } CtClass c = classPool.getAndRename(NoOpTypeParameterMatcher.class.getName(), className); c.setModifiers(c.getModifiers() | Modifier.FINAL); c.getDeclaredMethod("match").setBody("{ return $1 instanceof " + type.getName() + "; }"); byte[] byteCode = c.toBytecode(); c.detach(); Method method = ClassLoader.class.getDeclaredMethod( "defineClass", String.class, byte[].class, int.class, int.class); method.setAccessible(true); Class<?> generated = (Class<?>) method.invoke(classLoader, className, byteCode, 0, byteCode.length); logger.debug("Generated: {}", generated.getName()); return (TypeParameterMatcher) generated.newInstance(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } }
private void addOutputArg(List<String> args, Object object) { if (!(object instanceof String)) throw new IllegalArgumentException("Only a single output file can be specified"); String value = (String) object; args.add("-o"); if (value.endsWith(".vcf")) { args.add(value); try { ConstPool constPool = annotatedWalker.getClassFile().getConstPool(); AnnotationsAttribute att = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag); Annotation ann = new Annotation(Output.class.getName(), constPool); att.addAnnotation(ann); CtClass writerClass = pool.get(VCFWriter.class.getName()); CtField field = new CtField(writerClass, "out", annotatedWalker); field.setModifiers(Modifier.PUBLIC); field.getFieldInfo().addAttribute(att); annotatedWalker.addField(field); } catch (NotFoundException e) { throw new RuntimeException(e); } catch (CannotCompileException e) { throw new RuntimeException(e); } } else throw new IllegalArgumentException("Only VCF files are supported as output files"); }
static { try { OBJECT_CLASS = ClassPool.getDefault().get(Object.class.getName()); } catch (NotFoundException e) { throw new RuntimeException(e); } }
/* (non-Javadoc) * @see javassist.Translator#onWrite(javassist.ClassPool, java.lang.String) */ public void onWrite(ClassPool pool, String classname) throws NotFoundException, CannotCompileException { // LOG.info(++logCounter+" Searching component for "+classname+" in repository with #cop = // "+ComponentRepository.Instance().getComponentResources().size()); // COMPONENT MUST HAVE BEEN PUT IN REPOSITORY MAP ALREADY (before initComponent()) IComponentResource loadingCop = UpgradeableComponentResourceFactory.getComponentResourceByContent(classname); /* DEBUGGING ONLY: check if have to load from dependency: // MUST NOT happen: load from wrong cop!!! if (loadingCop == null) { LOG.error(cp+" "+v+": class "+classname+" belongs to no cop "); return; } else if( !((UpgradeableComponentResource)loadingCop).contains(classname)) { // wrong cop: hack , check for loadingCop.knowsClass(classname) instead LOG.error(cp+" "+v+": class "+classname+" belongs not to cop "+loadingCop); return; }*/ String cb = ProxyComponentResourceFactory.getProxyCodebase(loadingCop); IComponentResource proxyCop = ComponentRepository.Instance().getComponentResourceByCodebase(cb); if (proxyCop instanceof ProxyComponentResource) { // during an upgrade, check if current version of cop was retreived loadingCop = ((ProxyComponentResource) proxyCop).getOriginalComponent(); } // LOG.info(loadingCop+", "+loadingCop.getVersion()+": pool.get("+classname+")"); // if (loadingCop instanceof ProxyComponentResource) return; int extRefCount = searchExternalReferences(classname, pool, loadingCop); if (extRefCount == 0) return; CtClass toManipulate = pool.get(classname); manipulate(classname, toManipulate, extRefCount); }
@After public void tearDown() throws Exception { final CtClass packageInfoCtClass = ClassPool.getDefault().get("com.edugility.jaxb.package-info"); assertNotNull(packageInfoCtClass); packageInfoCtClass.detach(); }
public void appendClassPath(String classPath) { try { classPool.appendClassPath(classPath); } catch (NotFoundException e) { throw new IllegalStateException(e); } }
@Override protected void cacheCtClass(String className, CtClass c, boolean dynamic) { if (isSrg && !exclude(className)) { return; } super.cacheCtClass(className, c, dynamic); }