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;
  }
Esempio n. 2
0
  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;
  }
Esempio n. 3
0
  private static TemplateRenderer tryToCompile(String source, Map<String, String> expressions)
      throws NotFoundException, CannotCompileException, InstantiationException,
          IllegalAccessException {

    ClassPool cp = ClassPool.getDefault();
    CtClass sup = cp.get(Object.class.getCanonicalName());
    CtClass cls = cp.makeClass("RapidoidTemplate" + ID_GEN.incrementAndGet(), sup);

    cls.addInterface(cp.get(TemplateRenderer.class.getCanonicalName()));
    cls.addConstructor(CtNewConstructor.defaultConstructor(cls));

    for (Map.Entry<String, String> expr : expressions.entrySet()) {
      String fld =
          "private static final org.rapidoid.render.retriever.ValueRetriever %s = org.rapidoid.render.retriever.Retriever.of(%s);";

      String retrieverId = retrieverId(expr.getKey());
      String prop = expr.getValue();

      String field = U.frmt(fld, retrieverId, prop);

      cls.addField(CtField.make(field, cls));
    }

    CtClass[] params = {cp.get(RenderCtx.class.getCanonicalName())};
    CtClass clsVoid = cp.get(void.class.getCanonicalName());
    cls.addMethod(
        CtNewMethod.make(Modifier.PUBLIC, clsVoid, "render", params, new CtClass[0], source, cls));

    return (TemplateRenderer) cls.toClass().newInstance();
  }
 static {
   try {
     OBJECT_CLASS = ClassPool.getDefault().get(Object.class.getName());
   } catch (NotFoundException e) {
     throw new RuntimeException(e);
   }
 }
 @After
 public void tearDown() throws Exception {
   final CtClass packageInfoCtClass =
       ClassPool.getDefault().get("com.edugility.jaxb.package-info");
   assertNotNull(packageInfoCtClass);
   packageInfoCtClass.detach();
 }
  @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());
    }
  }
Esempio n. 7
0
  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);
    }
  }
 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"));
  }
Esempio n. 10
0
 public void testBadClass() throws Exception {
   CtClass badClass = ClassPool.getDefault().makeClass("badClass");
   String src =
       String.join(
           System.getProperty("line.separator"),
           "public void eval () {",
           "    if (true) {",
           "        double t=0;",
           "    } else {",
           "        double t=0;",
           "    }",
           "    for (int i=0; i < 2; i++) {",
           "        int a=0;",
           "        int b=0;",
           "        int c=0;",
           "        int d=0;",
           "        if (true) {",
           "            int e = 0;",
           "        }",
           "    }",
           "}");
   System.out.println(src);
   badClass.addMethod(CtMethod.make(src, badClass));
   Class clazzz = badClass.toClass();
   Object obj = clazzz.getConstructor().newInstance(); // <-- falls here
 }
Esempio n. 11
0
  /** @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();
      }
    }
  }
 @Test
 public void testSetter() throws Exception {
   CtClass mock = new WicketMockClassFactory(Date.class).getMock();
   assertNotNull(
       mock.getMethod(
           "setSeconds",
           Descriptor.ofMethod(
               voidType, new CtClass[] {ClassPool.getDefault().get(Object.class.getName())})));
 }
Esempio n. 13
0
  /**
   * Exécute l'injection
   *
   * @param args arguments passés en paramètre
   * @throws Throwable une exception
   */
  public static void main(String[] args) throws Throwable {

    MyReflectionInjection r = new MyReflectionInjection();
    ClassPool pool = ClassPool.getDefault();
    Loader cl = new Loader(pool);
    cl.addTranslator(pool, r);

    cl.run("fr.upmc.aladyn.dyn_generics.transform.MainUser", args);
  }
Esempio n. 14
0
 public void testProceedToDefaultMethod() throws Exception {
   CtClass cc = ClassPool.getDefault().get("test5.ProceedDefault");
   CtMethod mth = cc.getDeclaredMethod("bar");
   mth.instrument(
       new ExprEditor() {
         public void edit(MethodCall c) throws CannotCompileException {
           c.replace("$_ = $proceed($$) + 10000;");
         }
       });
   cc.writeFile();
   Object obj = make(cc.getName());
   assertEquals(21713, invoke(obj, "run"));
 }
Esempio n. 15
0
 // 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;
 }
 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;
 }
Esempio n. 18
0
  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();
  }
Esempio n. 19
0
  public static Getter generateGetter(OgnlContext context, String code) throws OgnlException {
    String className = NAME_FACTORY.getNewClassName();

    try {
      ClassPool pool = (ClassPool) pools.get(context.getClassResolver());
      EnhancedClassLoader loader = (EnhancedClassLoader) loaders.get(context.getClassResolver());
      CtClass newClass;
      CtClass ognlContextClass;
      CtClass objectClass;
      CtClass stringClass;
      CtMethod method;
      byte[] byteCode;
      Class compiledClass;

      if ((pool == null) || (loader == null)) {
        ClassLoader classLoader =
            new ContextClassLoader(OgnlContext.class.getClassLoader(), context);

        pool = ClassPool.getDefault();
        pool.insertClassPath(new LoaderClassPath(classLoader));
        pools.put(context.getClassResolver(), pool);

        loader = new EnhancedClassLoader(classLoader);
        loaders.put(context.getClassResolver(), loader);
      }

      newClass = pool.makeClass(className);
      ognlContextClass = pool.get(OgnlContext.class.getName());
      objectClass = pool.get(Object.class.getName());
      stringClass = pool.get(String.class.getName());

      newClass.addInterface(pool.get(Getter.class.getName()));
      method =
          new CtMethod(
              objectClass,
              "get",
              new CtClass[] {ognlContextClass, objectClass, stringClass},
              newClass);
      method.setBody("{" + code + "}");
      newClass.addMethod(method);
      byteCode = newClass.toBytecode();
      compiledClass = loader.defineClass(className, byteCode);
      return (Getter) compiledClass.newInstance();
    } catch (Throwable ex) {
      throw new OgnlException("Cannot create class", ex);
    }
  }
Esempio n. 20
0
 /** 初始化. */
 @Override
 public void init(ServletConfig config) throws ServletException {
   super.init(config);
   if (contextConfigLocation == null) {
     contextConfigLocation = config.getInitParameter("contextConfigLocation");
     try {
       String classPath =
           Thread.currentThread().getContextClassLoader().getResource("").toString();
       classPath = classPath.substring(6, classPath.length());
       System.out.println(classPath);
       ClassPool.getDefault().insertClassPath(classPath);
     } catch (NotFoundException e) {
       throw new WqMvcException(e);
     }
     new ContextConfig(contextConfigLocation).init();
   }
 }
Esempio n. 21
0
  /**
   * Javassist是一个开源的分析、编辑和创建Java字节码的类库。 是由东京工业大学的数学和计算机科学系的 Shigeru Chiba (千叶 滋)所创建的。它已加入了开放源代码JBoss
   * 应用服务器项目, 通过使用Javassist对字节码操作为JBoss实现动态AOP框架。javassist是jboss的一个子项目.
   * 其主要的优点,在于简单,而且快速。直接使用java编码的形式,而不需要了解虚拟机指令,就能动态改变类的结构,或者动态生成类。
   *
   * @param path
   * @throws Exception
   */
  public static void generateClassByJavassist(String path) throws Exception {
    ClassPool pool = ClassPool.getDefault();

    // 创建类
    CtClass clazz = pool.makeClass("Demo");
    // 创建方法
    CtMethod method = CtNewMethod.make("public void call(){}", clazz);

    // 插入方法代码
    method.insertBefore("System.out.println(\"I'm a Programmer,Just Coding.....\");");

    // 将方法添加到类中
    clazz.addMethod(method);

    // 将class 写入文件
    clazz.writeFile(path);
  }
  public void rewrite(final CtClass clazz) throws CannotCompileException {
    try {
      ClassPool cp = ClassPool.getDefault();

      byte[] b1 = clazz.toBytecode();
      clazz.defrost();
      ClassReader cr = new ClassReader(b1);
      ClassWriter cw = new ClassWriter(0); // new ClassWriter(cr, 0);
      // TraceClassVisitor ca = new TraceClassVisitor( cw, new PrintWriter(System.out, true) );
      // CheckClassAdapter cca = new CheckClassAdapter(ca);
      ConcurrencyControlRewriter.Adapter ca2 = new ConcurrencyControlRewriter.Adapter(cw, clazz);
      cr.accept(ca2, 0);
      byte[] b2 = cw.toByteArray();
      cp.makeClass(new ByteArrayInputStream(b2));
    } catch (IOException e) {
      throw new CannotCompileException(e);
    }
  }
Esempio n. 23
0
 public static void main(String[] args)
     throws NotFoundException, CannotCompileException, IOException {
   ClassPool classPool = ClassPool.getDefault();
   classPool.appendClassPath(new ClassClassPath(JavassistLengthBug.class));
   CtClass dummyClass = classPool.get("net.fwbrasil.activate.entity.Dummy");
   dummyClass.instrument(
       new ExprEditor() {
         public void edit(FieldAccess fa) {
           if (fa.isReader() && fa.getFieldName().equals("length"))
             try {
               fa.replace("$_ = ($r) this.length.substring(1);");
             } catch (CannotCompileException e) {
               e.printStackTrace();
             }
         }
       });
   dummyClass.toClass();
   new Dummy().print();
 }
  public void generateJavaClass() {
    // create a cache
    ClassPool pool = ClassPool.getDefault();

    CtClass ctClass = pool.makeClass("com.linuxclicks.bytecode.generation.TerryJavaAssist");

    CtMethod ctMethod = null;
    try {
      ctMethod =
          CtMethod.make(
              "public void sayHello() {  System.out.println(\"Hello World..from the JavaAssist bytecode generator\"); }",
              ctClass);
      ctClass.addMethod(ctMethod);

      System.out.println("writing generated JavaAssist file to filesystem");
      ctClass.writeFile("./build/java/src/");

      Class javaClass = ctClass.toClass();

      Object terry = javaClass.newInstance();

      Class partypes[] = new Class[0];

      Method terrySayHelloMethod = terry.getClass().getMethod("sayHello", partypes);

      Object arglist[] = new Object[0];

      terrySayHelloMethod.invoke(terry, arglist);

    } catch (CannotCompileException cce) {
      System.out.println("cce ..." + cce);
    } catch (IOException ioe) {
      System.out.println("ioe ..." + ioe);
    } catch (IllegalAccessException iae) {
      System.out.println("iae ..." + iae);
    } catch (InstantiationException ie) {
      System.out.println("ie ..." + ie);
    } catch (NoSuchMethodException nsme) {
      System.out.println("nsme ..." + nsme);
    } catch (InvocationTargetException ite) {
      System.out.println("ite ..." + ite);
    }
  }
  public TransformContext(String transformerClass, String filterPackage) {
    classPool = new ClassPool(ClassPool.getDefault());
    try {
      transformer =
          (ClassTransformer)
              Class.forName(transformerClass, true, Thread.currentThread().getContextClassLoader())
                  .newInstance();
    } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
      throw new IllegalStateException(e);
    }
    transformer.setFilterPackageName(filterPackage);
    transformer.setLogger(
        new ILogger() {

          @Override
          public void warn(String message, Throwable throwable) {}

          @Override
          public void warn(String message) {}

          @Override
          public void info(String message, Throwable throwable) {}

          @Override
          public void info(String message) {}

          @Override
          public void error(String message, Throwable throwable) {}

          @Override
          public void error(String message) {}

          @Override
          public void debug(String message, Throwable throwable) {}

          @Override
          public void debug(String message) {}

          @Override
          public void addMessage(File file, int line, int pos, String message, Throwable e) {}
        });
  }
Esempio n. 26
0
  public void testJIRA242() throws Exception {
    Boolean ss = Boolean.valueOf(2 > 3);
    ClassPool cp = ClassPool.getDefault();
    CtClass cc = cp.get("test5.JIRA242$Hello");
    CtMethod m = cc.getDeclaredMethod("say");
    m.insertBefore("{ System.out.println(\"Say Hello...\"); }");

    StringBuilder sb = new StringBuilder();
    sb.append("BOOL_SERIES = createBooleanSeriesStep();");
    // Below code cause the issue
    sb.append("BOOL_SERIES.setValue(3>=3);"); // lets comment this and run it will work
    // Below code snippets will work
    // this cast into exact class and call the same function
    sb.append("((test5.JIRA242$BooleanDataSeries)BOOL_SERIES).setValue(3>=3);");
    // this code snippet will set exact boolean variable to the function.
    sb.append("boolean var = 3>=3;");
    sb.append("BOOL_SERIES.setValue(var);");

    m.insertBefore(sb.toString());
    cc.writeFile();
    Object obj = make(cc.getName());
    assertEquals(0, invoke(obj, "say"));
  }
Esempio n. 27
0
  @Override
  public byte[] transform(
      ClassLoader loader,
      String className,
      Class<?> classBeingRedefined,
      ProtectionDomain protectionDomain,
      byte[] classfileBuffer)
      throws IllegalClassFormatException {
    byte[] bytes = null;
    try {
      final ClassPool pool = ClassPool.getDefault();
      pool.appendClassPath(new LoaderClassPath(getClass().getClassLoader()));
      final CtClass ctClass = pool.getCtClass(className.replaceAll("/", "."));
      if (ctClass != null) {
        try {
          for (CtMethod ctMethod : ctClass.getMethods()) {
            if (ctMethod.hasAnnotation(Retryable.class)) {
              try {
                changeMethod(ctClass, ctMethod);
                bytes = ctClass.toBytecode();
                writeClassFile(bytes);

              } catch (CannotCompileException | IOException e) {
                e.printStackTrace();
              }
              System.out.println("found it!");
            }
          }
        } finally {
          ctClass.detach();
        }
      }
    } catch (NotFoundException e) {
      e.printStackTrace();
    }
    return bytes;
  }
Esempio n. 28
0
  public static void main(String[] args) {
    args = new String[] {"test.codeconvert.BeanTest"};
    if (args.length >= 1) {
      try {

        // set up class loader with translator
        Translator xlat = new DissectionTranslator();
        ClassPool pool = ClassPool.getDefault();
        Loader loader = new Loader();
        loader.addTranslator(pool, xlat);

        // invoke the "main" method of the application class
        String[] pargs = new String[args.length - 1];
        System.arraycopy(args, 1, pargs, 0, pargs.length);
        loader.run(args[0], pargs);

      } catch (Throwable ex) {
        ex.printStackTrace();
      }

    } else {
      System.out.println("Usage: Dissect main-class args...");
    }
  }
Esempio n. 29
0
  @Test
  public void testToString() throws Exception {

    ClassPool pool = ClassPool.getDefault();
    System.out.println(pool.toString());

    pool.appendSystemPath();
    System.out.println(pool.toString());

    pool.appendClassPath("/*");
    System.out.println(pool.toString());

    pool.importPackage("java.util");
    System.out.println(pool.toString());

    StringTokenizer st =
        new StringTokenizer(System.getProperty("java.class.path"), File.pathSeparator);
    Set<String> classpath = new HashSet<String>();
    while (st.hasMoreElements()) classpath.add(st.nextToken());
    for (String element : classpath) pool.appendClassPath(element);
    System.out.println(pool.toString());

    Assert.assertTrue(true);
  }
Esempio n. 30
0
  public void testInner() throws Exception {
    ClassPool pool = ClassPool.getDefault();
    String classname = "test2.Inner";
    CtClass target = pool.get(classname);
    String src =
        "public void sampleMethod() throws Exception {"
            + "java.util.Properties props = new java.util.Properties();"
            + "java.rmi.activation.ActivationGroupDesc.CommandEnvironment ace "
            + " = null;"
            + "java.rmi.activation.ActivationGroupDesc agd "
            + " = new java.rmi.activation.ActivationGroupDesc(props,ace);}";
    CtMethod newmethod = CtNewMethod.make(src, target);
    target.addMethod(newmethod);

    String src2 =
        "public java.lang.Character.Subset sampleMethod2() {"
            + "  java.lang.Character.Subset s "
            + "    = Character.UnicodeBlock.HIRAGANA; "
            + "  return s; }";
    CtMethod newmethod2 = CtNewMethod.make(src2, target);
    target.addMethod(newmethod2);

    target.writeFile();
  }