Beispiel #1
0
 /*  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:    */ }
  // 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());
    }
  }
  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();
  }
 /**
  * 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;
   }
 }
Beispiel #5
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) {
   }
 }
  /** 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);
  }
  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);
    }
  }
Beispiel #8
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();
      }
    }
  }
  @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());
    }
  }
  /* (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);
  }
Beispiel #11
0
  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");
  }
  /**
   * 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;
    }
  }
Beispiel #14
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;
  }
  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);
    }
  }
  //    @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());
  }
 public boolean isAdvised(ClassPool pool, CtClass clazz) throws NotFoundException {
   CtClass[] interfaces = clazz.getInterfaces();
   CtClass advised = pool.get(AOP_PACKAGE + ".Advised");
   for (int i = 0; i < interfaces.length; i++) {
     if (interfaces[i].equals(advised)) return true;
     if (interfaces[i].getName().equals(AOP_PACKAGE + ".Advised")) return true;
   }
   return false;
 }
 @Test
 public void testMakeClass() throws Throwable {
   try {
     pool.get("fr.upmc.dtgui.tests.LittleRobot$SteeringData");
   } catch (Exception e) {
     // classFound=false;
     throw new Exception(e.toString());
   }
   assertTrue(classFound);
 }
Beispiel #19
0
  private void addVCFArg(List<String> args, Object object) {
    List<String> vcfs = new ArrayList<String>();
    if (object instanceof String) {
      vcfs.addAll(Arrays.asList(((String) object).split(",")));
    } else if (object instanceof List) {
      vcfs.add((String) object);
    }

    int count = 1;
    for (String vcf : vcfs) {
      args.add("--vcf" + count);
      args.add(vcf);
      try {
        ConstPool constPool = annotatedWalker.getClassFile().getConstPool();
        AnnotationsAttribute att =
            new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
        Annotation ann = new Annotation(Input.class.getName(), constPool);

        MemberValue fullName = new StringMemberValue("vcf" + count, constPool);
        ann.addMemberValue("fullName", fullName);
        att.addAnnotation(ann);

        RodBinding<VariantContext> dummy =
            new RodBinding<VariantContext>(VariantContext.class, "vcf", vcf, "VCF", null);
        CtClass rodClass = pool.get(dummy.getClass().getName());

        // If there are multiple vcfs, we number each one - vcf1, vcf2, ...
        // if there is only one, we just call it "vcf"
        CtField field =
            new CtField(rodClass, vcfs.size() > 1 ? "vcf" + count : "vcf", annotatedWalker);
        field.setModifiers(Modifier.PUBLIC);
        field.getFieldInfo().addAttribute(att);

        SignatureAttribute sig =
            new SignatureAttribute(
                constPool,
                "Lorg/broadinstitute/sting/commandline/RodBinding<Lorg/broadinstitute/sting/utils/variantcontext/VariantContext;>;;");
        field.getFieldInfo().addAttribute(sig);

        annotatedWalker.addField(field);

        if (config.containsKey("out")) {
          VCFHeaderInitializer vcfInit = new VCFHeaderInitializer(this);
          this.injections.get("initializers").add(vcfInit);
        }
      } catch (CannotCompileException e) {
        throw new RuntimeException(e);

      } catch (NotFoundException e) {
        throw new RuntimeException(e);
      }
      ++count;
    }
  }
Beispiel #20
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();
  }
  private String buildWriteInterceptionBodyFragment(CtField field) throws NotFoundException {
    // remember: In the source text given to setBody(), the identifiers starting with $ have special
    // meaning
    // $0, $1, $2, ...     this and actual parameters

    LOG.debug(
        "buildWriteInterceptionBodyFragment: {} {}", field.getType().getClass(), field.getType());

    if (isCtFieldACollection(field)) {
      if (field.getType().equals(cp.get(Set.class.getName()))) {
        // it implements Set, so wrap accordingly with ReactiveSet:
        return String.format(
            "  this.%1$s = new " + ReactiveSet.class.getName() + "($1); ", field.getName());
      }

      if (field.getType().equals(cp.get(List.class.getName()))) {
        // it implements List, so wrap accordingly with ReactiveList:
        return String.format(
            "  this.%1$s = new " + ReactiveList.class.getName() + "($1); ", field.getName());
      }

      return String.format(
          "  this.%1$s = new " + ReactiveCollection.class.getName() + "($1); ", field.getName());
    }

    // 2nd line will result in: ReactiveObjectUtil.notifyModification((ReactiveObject) this);
    // and that is fine because ASM: INVOKESTATIC
    // org/drools/core/phreak/ReactiveObjectUtil.notifyModification
    // (Lorg/drools/core/phreak/ReactiveObject;)V
    return String.format(
        "  this.%1$s = $1;%n"
            + "  "
            + ReactiveObjectUtil.class.getName()
            + ".notifyModification($0); ",
        field.getName());
  }
 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);
     }
   }
 }
  private Class<?> injectToPlainClassLoader(
      ClassPool pool, ClassLoader classLoader, String className)
      throws NotFoundException, IOException, CannotCompileException, IllegalArgumentException,
          IllegalAccessException, InvocationTargetException {
    Class<?> c = null;

    try {
      c = classLoader.loadClass(className);
    } catch (ClassNotFoundException ignore) {

    }

    if (c != null) {
      return c;
    }

    CtClass ct = pool.get(className);

    if (ct == null) {
      throw new NotFoundException(className);
    }

    CtClass superClass = ct.getSuperclass();

    if (superClass != null) {
      injectToPlainClassLoader(pool, classLoader, superClass.getName());
    }

    CtClass[] interfaces = ct.getInterfaces();

    for (CtClass i : interfaces) {
      injectToPlainClassLoader(pool, classLoader, i.getName());
    }

    Collection<String> refs = ct.getRefClasses();

    for (String ref : refs) {
      try {
        injectToPlainClassLoader(pool, classLoader, ref);
      } catch (NotFoundException e) {
        logger.warn("Skip a referenced class because of NotFoundException : ", e);
      }
    }

    byte[] bytes = ct.toBytecode();
    return (Class<?>) DEFINE_CLASS.invoke(classLoader, ct.getName(), bytes, 0, bytes.length);
  }
Beispiel #24
0
 public void onWrite(ClassPool pool, String className)
     throws NotFoundException, CannotCompileException {
   CtClass cc = pool.get(className);
   try {
     if (isPersistent(className)) {
       CtClass base = cc.getSuperclass();
       CtConstructor cons = new CtConstructor(constructorParams, cc);
       if (base.subclassOf(persistent) || base == object) {
         cons.setBody(null);
         cc.addConstructor(cons);
         if (base == object) {
           cc.setSuperclass(persistent);
         }
       } else {
         if (!isPersistent(base.getName())) {
           throw new NotFoundException(
               "Base class " + base.getName() + " was not declared as persistent");
         }
         cons.setBody("super($0);");
         cc.addConstructor(cons);
       }
       preprocessMethods(cc, true, true);
       if (base == persistent || base == object) {
         CtMethod m = new CtMethod(isRecursive, cc, null);
         m.setBody("return false;");
         cc.addMethod(m);
         addSerializeMethods(cc, false);
       } else if (base.subtypeOf(serializable)) {
         addSerializeMethods(cc, true);
       }
       if ((cc.getModifiers() & Modifier.PRIVATE) == 0) {
         CtClass f = pool.makeClass(className + "LoadFactory");
         f.addInterface(factory);
         CtMethod c = new CtMethod(create, f, null);
         c.setBody("return new " + className + "($1);");
         f.addMethod(c);
         CtNewConstructor.defaultConstructor(f);
       }
     } else {
       preprocessMethods(
           cc, cc.subtypeOf(persistent) && cc != persistent, !className.startsWith("org.nachodb"));
     }
   } catch (Exception x) {
     x.printStackTrace();
   }
 }
Beispiel #25
0
 public void start(ClassPool pool) throws NotFoundException {
   persistent = pool.get("org.nachodb.Persistent");
   persistentInterface = pool.get("org.nachodb.IPersistent");
   factory = pool.get("org.nachodb.impl.LoadFactory");
   object = pool.get("java.lang.Object");
   isRecursive = persistent.getDeclaredMethod("recursiveLoading");
   constructorParams = new CtClass[] {pool.get("org.nachodb.impl.ClassDescriptor")};
   serializable = pool.get("org.nachodb.impl.FastSerializable");
   pack = serializable.getDeclaredMethod("pack");
   unpack = serializable.getDeclaredMethod("unpack");
   create = factory.getDeclaredMethod("create");
 }
 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();
 }
Beispiel #27
0
  public void addMDataFieldToClass(ClassPool pool, CtClass cclass)
      throws CannotCompileException, NotFoundException {
    CtField cfield = new CtField(pool.get("java.util.Map"), "mDynamicColData", cclass);
    cfield.setModifiers(Modifier.PRIVATE);
    cclass.addField(cfield);

    StringBuffer methodBuf = new StringBuffer();
    methodBuf.append("public Object getDynamicColData(String colname)");
    methodBuf.append("{if(mDynamicColData==null) return null;");
    methodBuf.append("return mDynamicColData.get(colname);}");
    CtMethod getMDataMethod = CtNewMethod.make(methodBuf.toString(), cclass);
    cclass.addMethod(getMDataMethod);

    methodBuf = new StringBuffer();
    methodBuf.append("public void setDynamicColData(String colname,Object value)");
    methodBuf.append("{if(mDynamicColData==null) mDynamicColData=new HashMap();");
    methodBuf.append("mDynamicColData.put(colname,value);}");
    CtMethod setMDataMethod = CtNewMethod.make(methodBuf.toString(), cclass);
    cclass.addMethod(setMDataMethod);
  }
Beispiel #28
0
  /**
   * Finds the specified class using <code>ClassPath</code>. If the source throws an exception, this
   * returns null.
   *
   * <p>This method can be overridden by a subclass of <code>Loader</code>. Note that the overridden
   * method must not throw an exception when it just fails to find a class file.
   *
   * @return null if the specified class could not be found.
   * @throws ClassNotFoundException if an exception is thrown while obtaining a class file.
   */
  protected Class findClass(String name) throws ClassNotFoundException {
    byte[] classfile;
    try {
      if (source != null) {
        if (translator != null) translator.onLoad(source, name);

        try {
          classfile = source.get(name).toBytecode();
        } catch (NotFoundException e) {
          return null;
        }
      } else {
        String jarname = "/" + name.replace('.', '/') + ".class";
        InputStream in = this.getClass().getResourceAsStream(jarname);
        if (in == null) return null;

        classfile = ClassPoolTail.readStream(in);
      }
    } catch (Exception e) {
      throw new ClassNotFoundException(
          "caught an exception while obtaining a class file for " + name, e);
    }

    int i = name.lastIndexOf('.');
    if (i != -1) {
      String pname = name.substring(0, i);
      if (getPackage(pname) == null)
        try {
          definePackage(pname, null, null, null, null, null, null, null);
        } catch (IllegalArgumentException e) {
          // ignore.  maybe the package object for the same
          // name has been created just right away.
        }
    }

    if (domain == null) return defineClass(name, classfile, 0, classfile.length);
    else return defineClass(name, classfile, 0, classfile.length, domain);
  }
  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"));
  }
  private InjectionTarget resolveInjectionTarget(TargetMember targetMember) {
    try {
      final CtClass ctClass = classPool.get(targetMember.getClassName());
      // see if it is a field...
      try {
        CtField field = ctClass.getField(targetMember.getMemberName());
        return new FieldInjectionTarget(targetMember, ctClass, field);
      } catch (NotFoundException ignore) {
      }

      // see if it is a method...
      for (CtMethod method : ctClass.getMethods()) {
        if (method.getName().equals(targetMember.getMemberName())) {
          return new MethodInjectionTarget(targetMember, ctClass, method);
        }
      }

      // finally throw an exception
      throw new InjectionException("Unknown member [" + targetMember.getQualifiedName() + "]");
    } catch (Throwable e) {
      throw new InjectionException(
          "Unable to resolve class [" + targetMember.getClassName() + "]", e);
    }
  }