Java Code Examples for javassist.bytecode.AnnotationsAttribute#getAnnotations()

The following examples show how to use javassist.bytecode.AnnotationsAttribute#getAnnotations() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ClassPathScanner.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public void scan(final Object cls) {
  final ClassFile classFile = (ClassFile)cls;
  AnnotationsAttribute annotations = ((AnnotationsAttribute)classFile.getAttribute(AnnotationsAttribute.visibleTag));
  if (annotations != null) {
    boolean isAnnotated = false;
    for (javassist.bytecode.annotation.Annotation a : annotations.getAnnotations()) {
      if (annotationsToScan.contains(a.getTypeName())) {
        isAnnotated = true;
      }
    }
    if (isAnnotated) {
      List<AnnotationDescriptor> classAnnotations = getAnnotationDescriptors(annotations);
      List<FieldInfo> classFields = classFile.getFields();
      List<FieldDescriptor> fieldDescriptors = new ArrayList<>(classFields.size());
      for (FieldInfo field : classFields) {
        String fieldName = field.getName();
        AnnotationsAttribute fieldAnnotations = ((AnnotationsAttribute) field.getAttribute(AnnotationsAttribute.visibleTag));
        fieldDescriptors.add(new FieldDescriptor(fieldName, field.getDescriptor(), getAnnotationDescriptors(fieldAnnotations)));
      }
      functions.add(new AnnotatedClassDescriptor(classFile.getName(), classAnnotations, fieldDescriptors));
    }
  }
}
 
Example 2
Source File: ClassPathScanner.java    From Bats with Apache License 2.0 6 votes vote down vote up
private List<AnnotationDescriptor> getAnnotationDescriptors(AnnotationsAttribute annotationsAttr) {
  if (annotationsAttr == null) {
    return Collections.emptyList();
  }
  List<AnnotationDescriptor> annotationDescriptors = new ArrayList<>(annotationsAttr.numAnnotations());
  for (javassist.bytecode.annotation.Annotation annotation : annotationsAttr.getAnnotations()) {
    // Sigh: javassist uses raw collections (is this 2002?)
    Set<String> memberNames = annotation.getMemberNames();
    List<AttributeDescriptor> attributes = new ArrayList<>();
    if (memberNames != null) {
      for (String name : memberNames) {
        MemberValue memberValue = annotation.getMemberValue(name);
        final List<String> values = new ArrayList<>();
        memberValue.accept(new ListingMemberValueVisitor(values));
        attributes.add(new AttributeDescriptor(name, values));
      }
    }
    annotationDescriptors.add(new AnnotationDescriptor(annotation.getTypeName(), attributes));
  }
  return annotationDescriptors;
}
 
Example 3
Source File: ClassPathScanner.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
private List<AnnotationDescriptor> getAnnotationDescriptors(AnnotationsAttribute annotationsAttr) {
  List<AnnotationDescriptor> annotationDescriptors = new ArrayList<>(annotationsAttr.numAnnotations());
  for (javassist.bytecode.annotation.Annotation annotation : annotationsAttr.getAnnotations()) {
    // Sigh: javassist uses raw collections (is this 2002?)
    @SuppressWarnings("unchecked")
    Set<String> memberNames = annotation.getMemberNames();
    List<AttributeDescriptor> attributes = new ArrayList<>();
    if (memberNames != null) {
      for (String name : memberNames) {
        MemberValue memberValue = annotation.getMemberValue(name);
        final List<String> values = new ArrayList<>();
        memberValue.accept(new ListingMemberValueVisitor(values));
        attributes.add(new AttributeDescriptor(name, values));
      }
    }
    annotationDescriptors.add(new AnnotationDescriptor(annotation.getTypeName(), attributes));
  }
  return annotationDescriptors;
}
 
Example 4
Source File: JavassistAdapter.java    From panda with Apache License 2.0 6 votes vote down vote up
private List<String> getAnnotationNames(AnnotationsAttribute... annotationsAttributes) {
    List<String> result = new ArrayList<>();

    if (annotationsAttributes == null) {
        return result;
    }

    for (AnnotationsAttribute annotationsAttribute : annotationsAttributes) {
        if (annotationsAttribute == null) {
            continue;
        }

        for (Annotation annotation : annotationsAttribute.getAnnotations()) {
            result.add(annotation.getTypeName());
        }
    }

    return result;
}
 
Example 5
Source File: JavaAssistClass.java    From smart-testing with Apache License 2.0 5 votes vote down vote up
private void addAnnotations(Collection<String> imports, AnnotationsAttribute annotations) {
    if (annotations != null) {
        for (Annotation each : annotations.getAnnotations()) {
            imports.add(each.getTypeName());

            final Set<String> memberNames = each.getMemberNames();

            if (memberNames != null) {
                for (String memberName : memberNames) {
                    imports.addAll(addSubtypes(each, memberName));
                }
            }
        }
    }
}
 
Example 6
Source File: ClassPathScanner.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public void scan(final Object cls) {
  final ClassFile classFile = (ClassFile)cls;
  AnnotationsAttribute annotations = ((AnnotationsAttribute)classFile.getAttribute(AnnotationsAttribute.visibleTag));
  if (annotations != null) {
    boolean isAnnotated = false;
    for (javassist.bytecode.annotation.Annotation a : annotations.getAnnotations()) {
      if (annotationsToScan.contains(a.getTypeName())) {
        isAnnotated = true;
      }
    }
    if (isAnnotated) {
      List<AnnotationDescriptor> classAnnotations = getAnnotationDescriptors(annotations);
      @SuppressWarnings("unchecked")
      List<FieldInfo> classFields = classFile.getFields();
      List<FieldDescriptor> fieldDescriptors = new ArrayList<>(classFields.size());
      for (FieldInfo field : classFields) {
        String fieldName = field.getName();
        AnnotationsAttribute fieldAnnotations = ((AnnotationsAttribute)field.getAttribute(AnnotationsAttribute.visibleTag));
        final List<AnnotationDescriptor> annotationDescriptors =
            (fieldAnnotations != null) ? getAnnotationDescriptors(fieldAnnotations) : Collections.<AnnotationDescriptor>emptyList();
        fieldDescriptors.add(new FieldDescriptor(fieldName, field.getDescriptor(), annotationDescriptors));
      }
      functions.add(new AnnotatedClassDescriptor(classFile.getName(), classAnnotations, fieldDescriptors));
    }
  }
}
 
Example 7
Source File: CheckForConcept.java    From anno4j with Apache License 2.0 5 votes vote down vote up
protected boolean isAnnotationPresent(AnnotationsAttribute attr) {
	if (attr != null) {
		Annotation[] annotations = attr.getAnnotations();
		if (annotations != null) {
			for (Annotation ann : annotations) {
				if (ann.getTypeName().equals(Iri.class.getName()))
					return true;
				if (ann.getTypeName().equals(Matching.class.getName()))
					return true;
			}
		}
	}
	return false;
}
 
Example 8
Source File: JCommanderTranslationMap.java    From geowave with Apache License 2.0 5 votes vote down vote up
/**
 * Iterate the annotations, look for a 'required' parameter, and set it to false.
 */
private void disableBooleanMember(final String booleanMemberName, final CtField field) {

  // This is the JCommander package name
  final String packageName = JCommander.class.getPackage().getName();

  final AnnotationsAttribute fieldAttributes =
      (AnnotationsAttribute) field.getFieldInfo().getAttribute(AnnotationsAttribute.visibleTag);

  // Look for annotations that have a 'names' attribute, and whose package
  // starts with the expected JCommander package.
  for (final Annotation annotation : fieldAttributes.getAnnotations()) {
    if (annotation.getTypeName().startsWith(packageName)) {
      // See if it has a 'names' member variable.
      final MemberValue requiredMember = annotation.getMemberValue(booleanMemberName);

      // We have a names member!!!
      if (requiredMember != null) {
        final BooleanMemberValue booleanRequiredMember = (BooleanMemberValue) requiredMember;

        // Set it to not required.
        booleanRequiredMember.setValue(false);

        // This is KEY! For some reason, the existing annotation
        // will not be modified unless
        // you call 'setAnnotation' here. I'm guessing
        // 'getAnnotation()' creates a copy.
        fieldAttributes.setAnnotation(annotation);

        // Finished processing names.
        break;
      }
    }
  }
}
 
Example 9
Source File: JavassistAnnotationsHelper.java    From jadira with Apache License 2.0 5 votes vote down vote up
private static Set<Annotation> findAnnotationsForAnnotationsAttribute(AnnotationsAttribute attr) {

		if (attr != null) {
			javassist.bytecode.annotation.Annotation[] anns = attr.getAnnotations();
			return findAnnotationsForAnnotationsArray(anns);
		}
		return Collections.emptySet();
	}
 
Example 10
Source File: AnnotationHelper.java    From japicmp with Apache License 2.0 5 votes vote down vote up
public static boolean hasAnnotation(List attributes, String annotationClassName) {
	for (Object obj : attributes) {
		if (obj instanceof AnnotationsAttribute) {
			AnnotationsAttribute annotationsAttribute = (AnnotationsAttribute) obj;
			Annotation[] annotations = annotationsAttribute.getAnnotations();
			for (Annotation annotation : annotations) {
				if (annotation.getTypeName().equals(annotationClassName)) {
					return true;
				}
			}
		}
	}
	return false;
}
 
Example 11
Source File: ClassScanner.java    From startup-os with Apache License 2.0 4 votes vote down vote up
private ImmutableList<Field> getPackageFields(String packageName) throws IOException {
  ImmutableList.Builder<Field> result = ImmutableList.builder();
  Set<String> classes = new HashSet<>();
  String resourceName = resourceName(packageName);
  Enumeration<URL> urls = ClassLoader.getSystemClassLoader().getResources(resourceName);
  while (urls.hasMoreElements()) {
    URL url = urls.nextElement();
    JarFile jarFile = getJarFile(url);
    Enumeration<? extends ZipEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
      ClassFile classFile = getClassFile(jarFile, entries.nextElement());
      if (classFile == null) {
        continue;
      }
      if (!classes.add(classFile.getName())) {
        // We've already gone through this class - skip
        continue;
      }

      for (Object fieldInfoObject : classFile.getFields()) {
        FieldInfo fieldInfo = (FieldInfo) fieldInfoObject;
        AnnotationsAttribute annotationsAttribute =
            (AnnotationsAttribute) fieldInfo.getAttribute(AnnotationsAttribute.visibleTag);
        if (annotationsAttribute != null) {
          for (Annotation annotation : annotationsAttribute.getAnnotations()) {
            try {
              if (FlagDesc.class.getName().equals(annotation.getTypeName())) {
                Class clazz = ClassLoader.getSystemClassLoader().loadClass(classFile.getName());
                Field field = clazz.getDeclaredField(fieldInfo.getName());
                if (Flag.class.isAssignableFrom(field.getType())) {
                  result.add(field);
                } else {
                  throw new IllegalArgumentException(
                      "Field annotated with FlagDesc does not inherit from Flag " + field);
                }
              }
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        }
      }
    }
  }
  return result.build();
}
 
Example 12
Source File: JCommanderTranslationMap.java    From geowave with Apache License 2.0 4 votes vote down vote up
/**
 * Iterate the annotations, look for a 'names' parameter, and override it to prepend the given
 * prefix.
 */
private void overrideParameterPrefixes(final CtField field, final String[] names) {

  // This is the JCommander package name
  final String packageName = JCommander.class.getPackage().getName();

  final AnnotationsAttribute fieldAttributes =
      (AnnotationsAttribute) field.getFieldInfo().getAttribute(AnnotationsAttribute.visibleTag);

  // Look for annotations that have a 'names' attribute, and whose package
  // starts with the expected JCommander package.
  for (final Annotation annotation : fieldAttributes.getAnnotations()) {
    if (annotation.getTypeName().startsWith(packageName)) {
      // See if it has a 'names' member variable.
      final MemberValue namesMember = annotation.getMemberValue(NAMES_MEMBER);

      // We have a names member!!!
      if (namesMember != null) {
        final ArrayMemberValue arrayNamesMember = (ArrayMemberValue) namesMember;

        // Iterate and transform each item in 'names()' list and
        // transform it.
        final MemberValue[] newMemberValues = new MemberValue[names.length];
        for (int i = 0; i < names.length; i++) {
          newMemberValues[i] =
              new StringMemberValue(names[i], field.getFieldInfo2().getConstPool());
        }

        // Override the member values in nameMember with the new
        // one's we've generated
        arrayNamesMember.setValue(newMemberValues);

        // This is KEY! For some reason, the existing annotation
        // will not be modified unless
        // you call 'setAnnotation' here. I'm guessing
        // 'getAnnotation()' creates a copy.
        fieldAttributes.setAnnotation(annotation);

        // Finished processing names.
        break;
      }
    }
  }
}
 
Example 13
Source File: JavassistUtils.java    From geowave with Apache License 2.0 4 votes vote down vote up
/**
 * This function will take the given annotations attribute and create a new attribute, cloning all
 * the annotations and specified values within the attribute. The annotations attribute can then
 * be set on a method, class, or field.
 */
public static AnnotationsAttribute cloneAnnotationsAttribute(
    final ConstPool constPool,
    final AnnotationsAttribute attr,
    final ElementType validElementType) {

  // We can use system class loader here because the annotations for
  // Target
  // are part of the Java System.
  final ClassLoader cl = ClassLoader.getSystemClassLoader();

  final AnnotationsAttribute attrNew =
      new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);

  if (attr != null) {
    for (final Annotation annotation : attr.getAnnotations()) {
      final Annotation newAnnotation = new Annotation(annotation.getTypeName(), constPool);

      // If this must target a certain type of field, then ensure we
      // only
      // copy over annotations that can target that type of field.
      // For instances, a METHOD annotation can't be applied to a
      // FIELD or TYPE.
      Class<?> annoClass;
      try {
        annoClass = cl.loadClass(annotation.getTypeName());
        final Target target = annoClass.getAnnotation(Target.class);
        if ((target != null) && !Arrays.asList(target.value()).contains(validElementType)) {
          continue;
        }
      } catch (final ClassNotFoundException e) {
        // Cannot apply this annotation because its type cannot be
        // found.
        LOGGER.error("Cannot apply this annotation because it's type cannot be found", e);
        continue;
      }

      // Copy over the options for this annotation. For example:
      // @Parameter(names = "-blah")
      // For this, a member value would be "names" which would be a
      // StringMemberValue
      if (annotation.getMemberNames() != null) {
        for (final Object memberName : annotation.getMemberNames()) {
          final MemberValue memberValue = annotation.getMemberValue((String) memberName);
          if (memberValue != null) {
            newAnnotation.addMemberValue((String) memberName, memberValue);
          }
        }
      }
      attrNew.addAnnotation(newAnnotation);
    }
  }
  return attrNew;
}
 
Example 14
Source File: EnhanceMojo.java    From uima-uimafit with Apache License 2.0 4 votes vote down vote up
/**
 * Enhance descriptions in configuration parameters.
 */
private void enhanceConfigurationParameter(JavaSource aAST, Class<?> aClazz, CtClass aCtClazz,
        Multimap<String, String> aReportData) throws MojoExecutionException {
  // Get the parameter name constants
  Map<String, String> parameterNameFields = getParameterConstants(aClazz,
          parameterNameConstantPrefixes);
  Map<String, String> resourceNameFields = getParameterConstants(aClazz,
          externalResourceNameConstantPrefixes);

  // Fetch configuration parameters from the @ConfigurationParameter annotations in the
  // compiled class. We only need the fields in the class itself. Superclasses should be
  // enhanced by themselves.
  for (Field field : aClazz.getDeclaredFields()) {
    final String pname;
    final String type;
    final String pdesc;

    // Is this a configuration parameter?
    if (ConfigurationParameterFactory.isConfigurationParameterField(field)) {
      type = "parameter";
      // Extract configuration parameter information from the uimaFIT annotation
      pname = ConfigurationParameterFactory.createPrimitiveParameter(field).getName();
      // Extract JavaDoc for this resource from the source file
      pdesc = Util.getParameterDocumentation(aAST, field.getName(),
              parameterNameFields.get(pname));
    }

    // Is this an external resource?
    else if (ExternalResourceFactory.isExternalResourceField(field)) {
      type = "external resource";
      // Extract resource key from the uimaFIT annotation
      pname = ExternalResourceFactory.createResourceDependency(field).getKey();
      // Extract JavaDoc for this resource from the source file
      pdesc = Util.getParameterDocumentation(aAST, field.getName(), 
              resourceNameFields.get(pname));
    } else {
      continue;
    }

    if (pdesc == null) {
      String msg = "No description found for " + type + " [" + pname + "]";
      getLog().debug(msg);
      aReportData.put(aClazz.getName(), msg);
      continue;
    }

    // Update the "description" field of the annotation
    try {
      CtField ctField = aCtClazz.getField(field.getName());
      AnnotationsAttribute annoAttr = (AnnotationsAttribute) ctField.getFieldInfo().getAttribute(
              AnnotationsAttribute.visibleTag);

      // Locate and update annotation
      if (annoAttr != null) {
        Annotation[] annotations = annoAttr.getAnnotations();

        // Update existing annotation
        for (Annotation a : annotations) {
          if (a.getTypeName().equals(
                  org.apache.uima.fit.descriptor.ConfigurationParameter.class.getName())
                  || a.getTypeName().equals(
                          org.apache.uima.fit.descriptor.ExternalResource.class.getName())
                  || a.getTypeName().equals("org.uimafit.descriptor.ConfigurationParameter")
                  || a.getTypeName().equals("org.uimafit.descriptor.ExternalResource")) {
            if (a.getMemberValue("description") == null) {
              a.addMemberValue("description", new StringMemberValue(pdesc, aCtClazz
                      .getClassFile().getConstPool()));
              getLog().debug("Enhanced description of " + type + " [" + pname + "]");
              // Replace updated annotation
              annoAttr.addAnnotation(a);
            } else {
              // Extract configuration parameter information from the uimaFIT annotation
              // We only want to override if the description is not set yet.
              getLog().debug("Not overwriting description of " + type + " [" + pname + "] ");
            }
          }
        }
      }

      // Replace annotations
      ctField.getFieldInfo().addAttribute(annoAttr);
    } catch (NotFoundException e) {
      throw new MojoExecutionException("Field [" + field.getName() + "] not found in byte code: "
              + ExceptionUtils.getRootCauseMessage(e), e);
    }
  }
}