Пример #1
0
  private View createCheckBox(ViewGroup parent, MethodInfo methodInfo) {
    final Method method = methodInfo.getMethod();
    final Object instance = methodInfo.getInstance();
    final Context context = parent.getContext();

    View view = inflater.inflate(R.layout.item_settings_checkbox, parent, false);
    ((TextView) view.findViewById(R.id.title)).setText(methodInfo.getTitle());
    CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkbox);
    checkBox.setOnCheckedChangeListener(
        new CompoundButton.OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            try {
              method.invoke(instance, isChecked);
            } catch (Exception e) {
              Log.e("Bee", e.getMessage());
            }

            PrefHelper.setBoolean(context, method.getName(), isChecked);
          }
        });
    checkBox.setChecked(PrefHelper.getBoolean(context, method.getName()));

    return view;
  }
 private void addTagToMethod(
     Map<String, MethodInfo> methods, String tagText, MethodTagType tagType) {
   MethodInfo mi = methods.get(methodName);
   if (mi == null) {
     mi = new MethodInfo();
     methods.put(methodName, mi);
   }
   if (tagType == MethodTagType.OMIT_FROM_UI) {
     mi.omitFromUI = true;
     return;
   }
   String[] tagParts =
       Iterables.toArray(
           Splitter.on(WHITESPACE_PATTERN)
               .trimResults()
               .omitEmptyStrings()
               .limit(2)
               .split(tagText),
           String.class);
   if (tagParts.length == 2) {
     if (tagType == MethodTagType.DESCRIPTION) {
       mi.descriptions.put(tagParts[0], tagParts[1]);
     } else {
       mi.useSchemas.put(tagParts[0], tagParts[1]);
     }
   }
 }
Пример #3
0
  public Method lookupMethod(
      CtClass clazz,
      CtClass currentClass,
      MethodInfo current,
      String methodName,
      int[] argTypes,
      int[] argDims,
      String[] argClassNames)
      throws CompileError {
    Method maybe = null;
    // to enable the creation of a recursively called method
    if (current != null && clazz == currentClass)
      if (current.getName().equals(methodName)) {
        int res = compareSignature(current.getDescriptor(), argTypes, argDims, argClassNames);
        if (res != NO) {
          Method r = new Method(clazz, current, res);
          if (res == YES) return r;
          else maybe = r;
        }
      }

    Method m = lookupMethod(clazz, methodName, argTypes, argDims, argClassNames, maybe != null);
    if (m != null) return m;
    else return maybe;
  }
Пример #4
0
 @Override
 public void end(MethodInfo methodInfo, Throwable throwable) {
   logger.info(
       String.valueOf(methodInfo.getParameter().size())
           + "="
           + Arrays.toString(methodInfo.getParameter().getValues()));
 }
Пример #5
0
 public static MethodInfo refactorMehtodfromUUID(String methodUUID) throws ClassNotFoundException
 {
     int index = methodUUID.lastIndexOf("_");
     MethodInfo methodInfo = new MethodInfo();
     if(index <= 0)
     {
         methodInfo.setMethodName(methodUUID);
         return methodInfo;
     }
     
     else
     {
         String[] infos = methodUUID.split("_");
         methodInfo.setMethodName(infos[0]);
         Class[] classes = new Class[infos.length - 1];
         for(int i = 1; i < infos.length; i ++)
         {
             
             classes[i - 1] = BeanAccembleHelper.getClass(infos[i]);
         }
         methodInfo.setParamTypes(classes);
     }
     return methodInfo;
     
 }
  public SearchResult searchFor(String pattern, String threadName) {
    pattern = pattern.toLowerCase(Locale.US);

    Set<MethodInfo> methods = new HashSet<MethodInfo>();
    Set<Call> calls = new HashSet<Call>();

    Call topLevelCall = getThread(threadName).getTopLevelCall();
    if (topLevelCall == null) {
      // no matches
      return new SearchResult(methods, calls);
    }

    // Find all methods matching given pattern called on given thread
    for (MethodInfo method : getMethods().values()) {
      String fullName = method.getFullName().toLowerCase(Locale.US);
      if (fullName.contains(pattern)) { // method name matches
        if (method.getInclusiveTime(threadName, ClockType.GLOBAL)
            > 0) { // method was called in this thread
          methods.add(method);
        }
      }
    }

    // Find all invocations of the matched methods
    Iterator<Call> iterator = topLevelCall.getCallHierarchyIterator();
    while (iterator.hasNext()) {
      Call c = iterator.next();
      MethodInfo method = getMethod(c.getMethodId());
      if (methods.contains(method)) {
        calls.add(c);
      }
    }

    return new SearchResult(methods, calls);
  }
Пример #7
0
  public void load(XDataInput in) {
    newContext();
    try {
      magic = in.readInt();
      minor = in.readUnsignedShort();
      major = in.readUnsignedShort();

      pool = ConstantPool.create(true);

      pool.load(in, pool);

      flags = Flags.create(in, pool);
      classname = pool.getConstant(in.readUnsignedShort(), ClassRef.class);
      Log.debug("Loading class %s", classname.value());

      superclass = pool.getConstant(in.readUnsignedShort(), ClassRef.class);

      // interfaces
      {
        int count = in.readUnsignedShort();
        interfaces = new ArrayList<ClassRef>(count);
        while (count-- > 0) {
          ClassRef iface = pool.getConstant(in.readUnsignedShort(), ClassRef.class);
          interfaces.add(iface);
        }
      }

      // fields
      {
        int count = in.readUnsignedShort();
        fields = new ArrayList<FieldInfo>(count);
        while (count-- > 0) {
          FieldInfo f = new FieldInfo(this);
          f.load(in, pool);
          fields.add(f);
        }
      }

      // methods
      {
        int count = in.readUnsignedShort();
        methods = new ArrayList<MethodInfo>(count);
        while (count-- > 0) {
          MethodInfo m = new MethodInfo(this);
          m.load(in, pool);
          methods.add(m);
        }
      }

      attributes = AttributeHelper.loadAttributes(this, in);
      AttributeHelper.qdhRemoveUnsupportedAttributes(attributes);

      pool.close();

    } finally {
      closeContext();
    }
  }
Пример #8
0
 public MethodInfo getMethod(String name, String descriptor) {
   // fixme performance
   for (MethodInfo m : methods()) {
     if (m.name().equals(name) && m.descriptor().equals(descriptor)) {
       return m;
     }
   }
   return null;
 }
 public MethodParameterInjection copyFrom(@NotNull BaseInjection o) {
   super.copyFrom(o);
   if (o instanceof MethodParameterInjection) {
     final MethodParameterInjection other = (MethodParameterInjection) o;
     myClassName = other.getClassName();
     myParameterMap.clear();
     for (MethodInfo info : other.myParameterMap.values()) {
       myParameterMap.put(info.methodSignature, info.copy());
     }
   }
   return this;
 }
  void processMethods() throws IOException {

    int methodsCount = is.readUnsignedShort();
    os.writeShort(methodsCount);

    for (int i = 0; i < methodsCount; i++) {
      MethodInfo methodInfo = readMethod();
      if (methodInfo.getInterceptorClass() != null) {
        injectCode(methodInfo);
      }
      methods.add(methodInfo);
    }

    writeMethods();
  }
Пример #11
0
 private void registerConstants(ConstantPool pool) {
   classname = pool.register(classname);
   superclass = pool.register(superclass);
   interfaces = Helper.register(interfaces, pool);
   for (FieldInfo f : iterable(fields)) {
     f.registerConstants(pool);
   }
   for (MethodInfo m : iterable(methods)) {
     m.registerConstants(pool);
   }
   for (AttributeInfo a : iterable(attributes)) {
     a.registerConstants(pool);
   }
   pool.rebuild();
 }
Пример #12
0
 public ResourceInfo.MethodInfo[] getMethodDescriptors() {
   Set<java.lang.reflect.Method> accessors = new HashSet<java.lang.reflect.Method>();
   for (PropertyDescriptor p : getPropertyDescriptors()) {
     accessors.add(p.getReadMethod());
     accessors.add(p.getWriteMethod());
   }
   for (MethodDescriptor o : getRemoteMethodDescriptors()) {
     accessors.add(o.getMethod());
   }
   TreeSet<MethodDescriptor> methods =
       new TreeSet<MethodDescriptor>(
           new Comparator<MethodDescriptor>() {
             public int compare(MethodDescriptor a, MethodDescriptor b) {
               return a.getName().compareTo(b.getName());
             }
           });
   methods.addAll(Arrays.asList(info.getMethodDescriptors()));
   Iterator<MethodDescriptor> iter = methods.iterator();
   while (iter.hasNext()) {
     MethodDescriptor m = iter.next();
     if (accessors.contains(m.getMethod())) {
       iter.remove();
     }
   }
   return MethodInfo.wrap(methods);
 }
Пример #13
0
 public void generate(ClassEmitter ce, Context context, List methods) {
   for (Iterator it = methods.iterator(); it.hasNext(); ) {
     MethodInfo method = (MethodInfo) it.next();
     if (!TypeUtils.isProtected(method.getModifiers())) {
       CodeEmitter e = context.beginMethod(ce, method);
       context.emitCallback(e, context.getIndex(method));
       if (proxyRef) {
         e.load_this();
         e.invoke_interface(PROXY_REF_DISPATCHER, PROXY_REF_LOAD_OBJECT);
       } else {
         e.invoke_interface(DISPATCHER, LOAD_OBJECT);
       }
       e.checkcast(method.getClassInfo().getType());
       e.load_args();
       e.invoke(method);
       e.return_value();
       e.end_method();
     }
   }
 }
Пример #14
0
  public void generate(ClassEmitter ce, Context context, List methods) {
    for (Iterator it = methods.iterator(); it.hasNext(); ) {
      MethodInfo method = (MethodInfo) it.next();
      Signature impl = context.getImplSignature(method);
      ce.declare_field(Constants.PRIVATE_FINAL_STATIC, impl.getName(), METHOD, null);

      CodeEmitter e = context.beginMethod(ce, method);
      Block handler = e.begin_block();
      context.emitCallback(e, context.getIndex(method));
      e.load_this();
      e.getfield(impl.getName());
      e.create_arg_array();
      e.invoke_interface(INVOCATION_HANDLER, INVOKE);
      e.unbox(method.getSignature().getReturnType());
      e.return_value();
      handler.end();
      EmitUtils.wrap_undeclared_throwable(
          e, handler, method.getExceptionTypes(), UNDECLARED_THROWABLE_EXCEPTION);
      e.end_method();
    }
  }
Пример #15
0
 private void generateSet(final Class target, final Method[] setters) {
     // setPropertyValues
     CodeEmitter e = begin_method(Constants.ACC_PUBLIC, SET_PROPERTY_VALUES, null);
     if (setters.length > 0) {
         Local index = e.make_local(Type.INT_TYPE);
         e.push(0);
         e.store_local(index);
         e.load_arg(0);
         e.checkcast(Type.getType(target));
         e.load_arg(1);
         Block handler = e.begin_block();
         int lastIndex = 0;
         for (int i = 0; i < setters.length; i++) {
             if (setters[i] != null) {
                 MethodInfo setter = ReflectUtils.getMethodInfo(setters[i]);
                 int diff = i - lastIndex;
                 if (diff > 0) {
                     e.iinc(index, diff);
                     lastIndex = i;
                 }
                 e.dup2();
                 e.aaload(i);
                 e.unbox(setter.getSignature().getArgumentTypes()[0]);
                 e.invoke(setter);
             }
         }
         handler.end();
         e.return_value();
         e.catch_exception(handler, Constants.TYPE_THROWABLE);
         e.new_instance(BULK_BEAN_EXCEPTION);
         e.dup_x1();
         e.swap();
         e.load_local(index);
         e.invoke_constructor(BULK_BEAN_EXCEPTION, CSTRUCT_EXCEPTION);
         e.athrow();
     } else {
         e.return_value();
     }
     e.end_method();
 }
Пример #16
0
  private void buildTables(Index index) {
    pool = new StrongInternPool<String>();
    classTable = new TreeMap<DotName, Integer>();

    // Build the pool for all strings
    for (ClassInfo clazz : index.getKnownClasses()) {
      addClassName(clazz.name());
      if (clazz.superName() != null) addClassName(clazz.superName());

      for (DotName intf : clazz.interfaces()) addClassName(intf);

      for (Entry<DotName, List<AnnotationTarget>> entry : clazz.annotations().entrySet()) {
        addClassName(entry.getKey());

        for (AnnotationTarget target : entry.getValue()) {
          if (target instanceof FieldInfo) {
            FieldInfo field = (FieldInfo) target;
            intern(field.name());
            addClassName(field.type().name());

          } else if (target instanceof MethodInfo) {
            MethodInfo method = (MethodInfo) target;
            intern(method.name());
            for (Type type : method.args()) addClassName(type.name());

            addClassName(method.returnType().name());
          } else if (target instanceof MethodParameterInfo) {
            MethodParameterInfo param = (MethodParameterInfo) target;
            intern(param.method().name());
            for (Type type : param.method().args()) addClassName(type.name());

            addClassName(param.method().returnType().name());
          }
        }
      }
    }

    poolIndex = pool.index();
  }
Пример #17
0
  private View createButton(ViewGroup parent, MethodInfo methodInfo) {

    final Method method = methodInfo.getMethod();
    final Object instance = methodInfo.getInstance();

    View view = inflater.inflate(R.layout.item_settings_button, parent, false);
    Button button = (Button) view.findViewById(R.id.button);
    button.setText(methodInfo.getTitle());
    button.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            try {
              method.invoke(instance);
            } catch (Exception e) {
              Log.e("Bee", e.getMessage());
            }
          }
        });

    return view;
  }
Пример #18
0
 private void generateGet(final Class target, final Method[] getters) {
     CodeEmitter e = begin_method(Constants.ACC_PUBLIC, GET_PROPERTY_VALUES, null);
     if (getters.length >= 0) {
         e.load_arg(0);
         e.checkcast(Type.getType(target));
         Local bean = e.make_local();
         e.store_local(bean);
         for (int i = 0; i < getters.length; i++) {
             if (getters[i] != null) {
                 MethodInfo getter = ReflectUtils.getMethodInfo(getters[i]);
                 e.load_arg(1);
                 e.push(i);
                 e.load_local(bean);
                 e.invoke(getter);
                 e.box(getter.getSignature().getReturnType());
                 e.aastore();
             }
         }
     }
     e.return_value();
     e.end_method();
 }
Пример #19
0
  @Test
  public void testAnnotations() throws Exception {
    String testValue = "TEST";
    String methodName = "getTest";
    String className = "org.teatrove.trove.test.Annotated";

    ClassFile cf = new ClassFile(className);
    Annotation ann = cf.addRuntimeVisibleAnnotation(TypeDesc.forClass(TestAnnotation.class));
    ann.putMemberValue("value", testValue);

    MethodInfo ctor = cf.addDefaultConstructor();
    CodeBuilder builder = new CodeBuilder(ctor);
    builder.loadThis();
    builder.invokeSuperConstructor();
    builder.returnVoid();

    Modifiers mods = new Modifiers(Modifier.PUBLIC);
    MethodInfo getName = cf.addMethod(mods, methodName, TypeDesc.STRING);
    builder = new CodeBuilder(getName);
    builder.loadConstant(null);
    builder.returnValue(TypeDesc.STRING);

    getName.addRuntimeVisibleAnnotation(TypeDesc.forClass(Deprecated.class));

    ClassInjector injector = ClassInjector.getInstance();
    OutputStream os = injector.getStream(className);
    cf.writeTo(os);
    os.close();

    Class<?> clazz = injector.loadClass(className);
    assertEquals("expected class name", className, clazz.getName());

    TestAnnotation annotation = clazz.getAnnotation(TestAnnotation.class);
    assertNotNull("expected annotation", annotation);
    assertEquals("expected test value", testValue, annotation.value());

    Method method = clazz.getMethod(methodName);
    assertNotNull("expected deprecated", method.getAnnotation(Deprecated.class));
  }
 private void writeMethods() throws IOException {
   for (MethodInfo method : methods) {
     os.writeShort(method.getAccessFlags());
     os.writeShort(method.getNameIndex());
     os.writeShort(method.getDescriptorIndex());
     os.writeShort(method.getAttributes().length);
     attributeFacility.writeAttributes(method.getAttributes());
   }
 }
 @Override
 public void endElement(String uri, String localName, String qName) throws SAXException {
   if (qName.equalsIgnoreCase("class")) {
     classInfo.put(className, oci);
     className = null;
     oci = null;
   } else if (qName.equalsIgnoreCase("comment") && oci != null) {
     if (methodName != null) {
       // do nothing
       if (isGetter(methodName)) {
         MethodInfo mi = oci.getMethods.get(methodName);
         if (mi == null) {
           mi = new MethodInfo();
           oci.getMethods.put(methodName, mi);
         }
         mi.comment = comment.toString();
       } else if (isSetter(methodName)) {
         MethodInfo mi = oci.setMethods.get(methodName);
         if (mi == null) {
           mi = new MethodInfo();
           oci.setMethods.put(methodName, mi);
         }
         mi.comment = comment.toString();
       }
     } else if (fieldName != null) {
       oci.fields.put(fieldName, comment.toString());
     } else {
       oci.comment = comment.toString();
     }
     comment = null;
   } else if (qName.equalsIgnoreCase("field")) {
     fieldName = null;
   } else if (qName.equalsIgnoreCase("method")) {
     methodName = null;
   }
 }
Пример #22
0
  private View createSpinner(ViewGroup parent, MethodInfo methodInfo) {

    final Method method = methodInfo.getMethod();
    final Object instance = methodInfo.getInstance();
    final Context context = parent.getContext();

    View view = inflater.inflate(R.layout.item_settings_spinner, parent, false);
    ((TextView) view.findViewById(R.id.title)).setText(methodInfo.getTitle());

    String[] dataList = (String[]) methodInfo.getData();
    ArrayAdapter<String> adapter =
        new ArrayAdapter<>(parent.getContext(), R.layout.simple_spinner_item, dataList);

    Spinner spinner = (Spinner) view.findViewById(R.id.spinner);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(
        new AdapterView.OnItemSelectedListener() {
          @Override
          public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String value = (String) parent.getItemAtPosition(position);

            try {
              method.invoke(instance, value);
            } catch (Exception e) {
              Log.e("Bee", e.getMessage());
            }

            PrefHelper.setInt(context, method.getName(), position);
          }

          @Override
          public void onNothingSelected(AdapterView<?> parent) {}
        });
    spinner.setSelection(PrefHelper.getInt(context, method.getName()));
    return view;
  }
Пример #23
0
  public static void writeLists() {
    Data data = makeHDF();

    ClassInfo[] classes = Converter.rootClasses();

    SortedMap<String, Object> sorted = new TreeMap<String, Object>();
    for (ClassInfo cl : classes) {
      if (cl.isHidden()) {
        continue;
      }
      sorted.put(cl.qualifiedName(), cl);
      PackageInfo pkg = cl.containingPackage();
      String name;
      if (pkg == null) {
        name = "";
      } else {
        name = pkg.name();
      }
      sorted.put(name, pkg);
      for (MethodInfo method : cl.methods()) {
        if (method.isProcessor() || method.isSource() || method.isTransformer()) {
          sorted.put(method.elementName(), method);
        }
      }
    }

    int i = 0;
    for (String s : sorted.keySet()) {
      data.setValue("docs.pages." + i + ".id", "" + i);
      data.setValue("docs.pages." + i + ".label", s);

      Object o = sorted.get(s);
      if (o instanceof PackageInfo) {
        PackageInfo pkg = (PackageInfo) o;
        data.setValue("docs.pages." + i + ".link", "java/" + pkg.htmlPage());
        data.setValue("docs.pages." + i + ".type", "package");
      } else if (o instanceof ClassInfo) {
        ClassInfo cl = (ClassInfo) o;
        data.setValue("docs.pages." + i + ".link", "java/" + cl.htmlPage());
        data.setValue("docs.pages." + i + ".type", "class");
      } else if (o instanceof MethodInfo) {
        MethodInfo mi = (MethodInfo) o;
        data.setValue("docs.pages." + i + ".id", "" + i);
        data.setValue("docs.pages." + i + ".link", "mule/" + mi.relativeModulePath());
        data.setValue("docs.pages." + i + ".type", "method");
      }
      i++;
    }

    ClearPage.write(data, "lists.cs", javadocDir + "lists.js");
  }
 @NotNull
 public String getDisplayName() {
   final String className = getClassName();
   if (StringUtil.isEmpty(className)) return "<unnamed>";
   MethodInfo singleInfo = null;
   for (MethodInfo info : myParameterMap.values()) {
     if (info.isEnabled()) {
       if (singleInfo == null) {
         singleInfo = info;
       } else {
         singleInfo = null;
         break;
       }
     }
   }
   final String name =
       singleInfo != null
           ? StringUtil.getShortName(className) + "." + singleInfo.methodName
           : StringUtil.getShortName(className);
   return /*"["+getInjectedLanguageId()+"] " +*/ name
       + " ("
       + StringUtil.getPackageName(className)
       + ")";
 }
 protected void toStringContent(StringBuffer buffer) {
   super.toStringContent(buffer);
   if (this.defaultValue != null) {
     buffer.append(" default "); // $NON-NLS-1$
     if (this.defaultValue instanceof Object[]) {
       buffer.append('{');
       Object[] elements = (Object[]) this.defaultValue;
       for (int i = 0, len = elements.length; i < len; i++) {
         if (i > 0) buffer.append(", "); // $NON-NLS-1$
         buffer.append(elements[i]);
       }
       buffer.append('}');
     } else {
       buffer.append(this.defaultValue);
     }
     buffer.append('\n');
   }
 }
Пример #26
0
 public ResourceInfo.MethodInfo[] getRemoteMethodDescriptors() {
   List<MethodDescriptor> operations = new ArrayList<MethodDescriptor>();
   operations.addAll(Arrays.asList(info.getMethodDescriptors()));
   Iterator<MethodDescriptor> iter = operations.iterator();
   while (iter.hasNext()) {
     java.lang.reflect.Method m = iter.next().getMethod();
     if (!m.isAnnotationPresent(Method.class) && !m.isAnnotationPresent(Path.class)) {
       iter.remove();
     }
   }
   MethodInfo[] result = MethodInfo.wrap(operations);
   Arrays.sort(
       result,
       new Comparator<MethodInfo>() {
         public int compare(MethodInfo a, MethodInfo b) {
           return a.getRemoteName().compareTo(b.getRemoteName());
         }
       });
   return result;
 }
  @Override
  public MethodInfo[] getDeclaredMethods() {
    Iterable<? extends Method> implMethods = classDef.getMethods();
    List<MethodInfo> result = new ArrayList<>();

    for (Method method : implMethods) {
      if (!isConstructor(method)) {
        MethodInfo mi = new MethodInfo();
        mi.parameterTypes = convertParameters(method.getParameters());
        mi.annotations = convertAnnotations(method.getAnnotations());
        mi.modifiers = method.getAccessFlags();
        mi.name = method.getName();
        mi.exceptionTypes = new ExceptionInfo[0];
        mi.returnType = DexlibAdapter.getTypeName(method.getReturnType());

        result.add(mi);
      }
    }

    MethodInfo[] array = new MethodInfo[result.size()];
    return result.toArray(array);
  }
  private void injectCode(MethodInfo methodInfo) throws IOException {
    if (methodInfo.getCode() == null) {
      return;
    }

    InterceptorConstants interceptorConstants =
        getOrInsertInterceptorConstants(methodInfo.getInterceptorClass());

    fixupSignature(methodInfo.getSignature());

    Map<String, Integer> wrapperMethods =
        getOrInsertPrimitiveWrapperMethods(methodInfo.getSignature());

    ByteArrayOutputStream codeToInject = new ByteArrayOutputStream();
    InstructionsFacility instructionsFacility =
        new InstructionsFacility(
            new DataOutputStream(codeToInject),
            methodInfo.getSignature(),
            interceptorConstants,
            wrapperMethods);

    instructionsFacility.generateInterceptorInstantiationCode();

    instructionsFacility.generateInterceptorMethodParametersCode(getObjectClassIndex());

    instructionsFacility.generateObjectArrayFillingCode();

    instructionsFacility.generateInterceptorInvocationCode(
        interceptorConstants.getInterceptorMethod());

    Code code = methodInfo.getCode();

    int originalStackSize = code.getMaxStack();
    code.setMaxStack(Math.max(originalStackSize, instructionsFacility.getStackSizeNeeded()));

    code.setInjected(codeToInject.toByteArray());
    code.refresh();
  }
Пример #29
0
  public static void begin(MethodInfo methodInfo) {
    logger.info(methodInfo.getName() + methodInfo.getDesc());
    // TODO use trace context

    trace.begin(methodInfo);
  }
  public static MethodInfo createAnnotationMethod(
      byte classFileBytes[], int offsets[], int offset) {
    MethodInfo methodInfo = new MethodInfo(classFileBytes, offsets, offset);
    int attributesCount = methodInfo.u2At(6);
    int readOffset = 8;
    AnnotationInfo[] annotations = null;
    Object defaultValue = null;
    for (int i = 0; i < attributesCount; i++) {
      // check the name of each attribute
      int utf8Offset =
          methodInfo.constantPoolOffsets[methodInfo.u2At(readOffset)] - methodInfo.structOffset;
      char[] attributeName = methodInfo.utf8At(utf8Offset + 3, methodInfo.u2At(utf8Offset + 1));
      if (attributeName.length > 0) {
        switch (attributeName[0]) {
          case 'A':
            if (CharOperation.equals(
                attributeName, AttributeNamesConstants.AnnotationDefaultName)) {
              // readOffset + 6 so the offset is at the start of the 'member_value' entry
              // u2 attribute_name_index + u4 attribute_length = + 6
              AnnotationInfo info =
                  new AnnotationInfo(
                      methodInfo.reference,
                      methodInfo.constantPoolOffsets,
                      readOffset + 6 + methodInfo.structOffset);
              defaultValue = info.decodeDefaultValue();
            }
            break;
          case 'S':
            if (CharOperation.equals(AttributeNamesConstants.SignatureName, attributeName))
              methodInfo.signatureUtf8Offset =
                  methodInfo.constantPoolOffsets[methodInfo.u2At(readOffset + 6)]
                      - methodInfo.structOffset;
            break;
          case 'R':
            AnnotationInfo[] methodAnnotations = null;
            if (CharOperation.equals(
                attributeName, AttributeNamesConstants.RuntimeVisibleAnnotationsName)) {
              methodAnnotations = decodeMethodAnnotations(readOffset, true, methodInfo);
            } else if (CharOperation.equals(
                attributeName, AttributeNamesConstants.RuntimeInvisibleAnnotationsName)) {
              methodAnnotations = decodeMethodAnnotations(readOffset, false, methodInfo);
            }
            if (methodAnnotations != null) {
              if (annotations == null) {
                annotations = methodAnnotations;
              } else {
                int length = annotations.length;
                AnnotationInfo[] newAnnotations =
                    new AnnotationInfo[length + methodAnnotations.length];
                System.arraycopy(annotations, 0, newAnnotations, 0, length);
                System.arraycopy(
                    methodAnnotations, 0, newAnnotations, length, methodAnnotations.length);
                annotations = newAnnotations;
              }
            }
            break;
        }
      }
      readOffset += (6 + methodInfo.u4At(readOffset + 2));
    }
    methodInfo.attributeBytes = readOffset;

    if (defaultValue != null) {
      if (annotations != null) {
        return new AnnotationMethodInfoWithAnnotations(methodInfo, defaultValue, annotations);
      }
      return new AnnotationMethodInfo(methodInfo, defaultValue);
    }
    if (annotations != null) return new MethodInfoWithAnnotations(methodInfo, annotations);
    return methodInfo;
  }