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

The following examples show how to use javassist.bytecode.AnnotationsAttribute#addAnnotation() . 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: JavassistUtilsTest.java    From geowave with Apache License 2.0 6 votes vote down vote up
private AnnotationsAttribute annotateMethod(
    final CtMethod ctmethod,
    final String annotationName,
    final int annotationValue) {
  final AnnotationsAttribute attr =
      new AnnotationsAttribute(
          ctmethod.getMethodInfo().getConstPool(),
          AnnotationsAttribute.visibleTag);
  final Annotation anno =
      new Annotation("java.lang.Integer", ctmethod.getMethodInfo().getConstPool());
  anno.addMemberValue(
      annotationName,
      new IntegerMemberValue(ctmethod.getMethodInfo().getConstPool(), annotationValue));
  attr.addAnnotation(anno);

  ctmethod.getMethodInfo().addAttribute(attr);

  return attr;
}
 
Example 2
Source File: JavassistUtils.java    From statefulj with Apache License 2.0 6 votes vote down vote up
public static void addClassAnnotation(CtClass clazz, Class<?> annotationClass, Object... values) {
	ClassFile ccFile = clazz.getClassFile();
	ConstPool constPool = ccFile.getConstPool();
	AnnotationsAttribute attr = getAnnotationsAttribute(ccFile);
	Annotation annot = new Annotation(annotationClass.getName(), constPool);
	
	for(int i = 0; i < values.length; i = i + 2) {
		String valueName = (String)values[i];
		Object value = values[i+1];
		if (valueName != null && value != null) {
			MemberValue memberValue = createMemberValue(constPool, value);
			annot.addMemberValue(valueName, memberValue);
		}
	}
	
	attr.addAnnotation(annot);
}
 
Example 3
Source File: SwaggerMoreDoclet.java    From swagger-more with Apache License 2.0 6 votes vote down vote up
private static void annotateApiAnn(ApiInfo info, AnnotationsAttribute attr, ConstPool constPool) {
    Annotation apiAnn = attr.getAnnotation(Api.class.getTypeName());
    MemberValue value;
    if (isNull(apiAnn)) {
        apiAnn = new Annotation(Api.class.getName(), constPool);
    }
    if (isNull(value = apiAnn.getMemberValue(ApiInfo.HIDDEN)) || !((BooleanMemberValue) value).getValue()) {
        apiAnn.addMemberValue(ApiInfo.HIDDEN, new BooleanMemberValue(info.hidden(), constPool));
    }
    ArrayMemberValue arrayMemberValue = (ArrayMemberValue) apiAnn.getMemberValue(TAGS);
    if (isNull(arrayMemberValue)) {
        arrayMemberValue = new ArrayMemberValue(constPool);
        arrayMemberValue.setValue(new MemberValue[1]);
    }
    StringMemberValue tagMemberValue = (StringMemberValue) arrayMemberValue.getValue()[0];
    if (isNull(tagMemberValue) || StringUtils.isEmpty(tagMemberValue.getValue())) {
        tagMemberValue = new StringMemberValue(info.tag(), constPool);
    }
    tagMemberValue.setValue(info.tag());
    arrayMemberValue.getValue()[0] = tagMemberValue;
    apiAnn.addMemberValue(TAGS, arrayMemberValue);
    attr.addAnnotation(apiAnn);
}
 
Example 4
Source File: JavassistUtilsTest.java    From geowave with Apache License 2.0 6 votes vote down vote up
private void annotateField(
    final CtField ctfield,
    final String annotationName,
    final int annotationValue) {
  final AnnotationsAttribute attr =
      new AnnotationsAttribute(
          ctfield.getFieldInfo().getConstPool(),
          AnnotationsAttribute.visibleTag);
  final Annotation anno =
      new Annotation("java.lang.Integer", ctfield.getFieldInfo().getConstPool());
  anno.addMemberValue(
      annotationName,
      new IntegerMemberValue(ctfield.getFieldInfo().getConstPool(), annotationValue));
  attr.addAnnotation(anno);

  ctfield.getFieldInfo().addAttribute(attr);
}
 
Example 5
Source File: SpringMVCBinder.java    From statefulj with Apache License 2.0 6 votes vote down vote up
@Override
protected void addEndpointMapping(CtMethod ctMethod, String method, String request) {
	MethodInfo methodInfo = ctMethod.getMethodInfo();
	ConstPool constPool = methodInfo.getConstPool();

	AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
	Annotation requestMapping = new Annotation(RequestMapping.class.getName(), constPool);

	ArrayMemberValue valueVals = new ArrayMemberValue(constPool);
	StringMemberValue valueVal = new StringMemberValue(constPool);
	valueVal.setValue(request);
	valueVals.setValue(new MemberValue[]{valueVal});

	requestMapping.addMemberValue("value", valueVals);

	ArrayMemberValue methodVals = new ArrayMemberValue(constPool);
	EnumMemberValue methodVal = new EnumMemberValue(constPool);
	methodVal.setType(RequestMethod.class.getName());
	methodVal.setValue(method);
	methodVals.setValue(new MemberValue[]{methodVal});

	requestMapping.addMemberValue("method", methodVals);
	attr.addAnnotation(requestMapping);
	methodInfo.addAttribute(attr);
}
 
Example 6
Source File: JavassistProxy.java    From gadtry with Apache License 2.0 6 votes vote down vote up
/**
 * 添加方法
 */
private static void addProxyMethod(CtClass proxy, CtMethod parentMethod, String methodBody)
        throws NotFoundException, CannotCompileException
{
    int mod = Modifier.FINAL | parentMethod.getModifiers();
    if (Modifier.isNative(mod)) {
        mod = mod & ~Modifier.NATIVE;
    }

    CtMethod proxyMethod = new CtMethod(parentMethod.getReturnType(), parentMethod.getName(), parentMethod.getParameterTypes(), proxy);
    proxyMethod.setModifiers(mod);
    proxyMethod.setBody(methodBody);

    //add Override
    Annotation annotation = new Annotation(Override.class.getName(), proxyMethod.getMethodInfo().getConstPool());
    AnnotationsAttribute attribute = new AnnotationsAttribute(proxyMethod.getMethodInfo().getConstPool(), AnnotationsAttribute.visibleTag);
    attribute.addAnnotation(annotation);
    proxyMethod.getMethodInfo().addAttribute(attribute);

    try {
        proxy.addMethod(proxyMethod);
    }
    catch (DuplicateMemberException e) {
        //todo: Use a more elegant way
    }
}
 
Example 7
Source File: JavassistProxy.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
/**
 * 代理缓存字段
 * 
 * <pre>
 * private final [clazz.name] _object;
 * private final CacheManager _manager;
 * </pre>
 * 
 * @param clazz
 * @param proxyClass
 * @throws Exception
 */
private void proxyCacheFields(Class<?> clazz, CtClass proxyClass) throws Exception {
    ConstPool constPool = proxyClass.getClassFile2().getConstPool();
    CtField managerField = new CtField(classPool.get(ProxyManager.class.getName()), FIELD_MANAGER, proxyClass);
    CtField informationField = new CtField(classPool.get(CacheInformation.class.getName()), FIELD_INFORMATION, proxyClass);

    List<CtField> fields = Arrays.asList(managerField, informationField);
    List<String> types = Arrays.asList("javax.persistence.Transient", "org.springframework.data.annotation.Transient");
    for (CtField field : fields) {
        field.setModifiers(Modifier.PRIVATE + Modifier.FINAL + Modifier.TRANSIENT);
        FieldInfo fieldInfo = field.getFieldInfo();
        for (String type : types) {
            AnnotationsAttribute annotationsAttribute = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
            Annotation annotation = new Annotation(type, constPool);
            annotationsAttribute.addAnnotation(annotation);
            fieldInfo.addAttribute(annotationsAttribute);
        }
        proxyClass.addField(field);
    }
}
 
Example 8
Source File: ProviderSupplierBrideBuilder.java    From jweb-cms with GNU Affero General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public Class<? extends Supplier<T>> build() {
    ClassPool classPool = ClassPool.getDefault();
    CtClass classBuilder = classPool.makeClass(providerClass.getCanonicalName() + "$Bride" + INDEX.incrementAndGet());
    try {
        classBuilder.addInterface(classPool.get(Supplier.class.getName()));
        ConstPool constPool = classBuilder.getClassFile().getConstPool();
        CtField field = CtField.make(String.format("%s provider;", Types.className(providerClass)), classBuilder);
        Annotation ctAnnotation = new Annotation(Inject.class.getCanonicalName(), constPool);
        AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
        attr.addAnnotation(ctAnnotation);
        field.getFieldInfo().addAttribute(attr);
        classBuilder.addField(field);

        CtMethod ctMethod = CtMethod.make("public Object get() {return provider.get();}", classBuilder);
        classBuilder.addMethod(ctMethod);

        return classBuilder.toClass();
    } catch (CannotCompileException | NotFoundException e) {
        throw new ApplicationException("failed to create provider bride, providerType={}", providerClass, e);
    }
}
 
Example 9
Source File: ServiceDelegateBuilder.java    From jweb-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
private void addDelegateField(CtClass classBuilder) throws CannotCompileException {
    CtField field = CtField.make(String.format("%s service;", serviceClass.getCanonicalName()), classBuilder);
    AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
    attr.addAnnotation(annotation(new InjectImpl()));
    field.getFieldInfo().addAttribute(attr);
    classBuilder.addField(field);
}
 
Example 10
Source File: Enhancer.java    From restcommander with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new annotation to be dynamically inserted in the byte code.
 */
protected static void createAnnotation(AnnotationsAttribute attribute, Class<? extends Annotation> annotationType, Map<String, MemberValue> members) {
    javassist.bytecode.annotation.Annotation annotation = new javassist.bytecode.annotation.Annotation(annotationType.getName(), attribute.getConstPool());
    for (Map.Entry<String, MemberValue> member : members.entrySet()) {
        annotation.addMemberValue(member.getKey(), member.getValue());
    }
    attribute.addAnnotation(annotation);
}
 
Example 11
Source File: JavassistDynamicBean.java    From gecco with MIT License 5 votes vote down vote up
@Override
public JavassistDynamicBean gecco(String[] matchUrl, String downloader, int timeout, String... pipelines) {
	AnnotationsAttribute attr = new AnnotationsAttribute(cpool, AnnotationsAttribute.visibleTag);

	Annotation annot = new Annotation(Gecco.class.getName(), cpool);
	// matchUrl
	//annot.addMemberValue("matchUrl", new StringMemberValue(matchUrl, cpool));
	ArrayMemberValue arrayMemberValueMatchUrl = new ArrayMemberValue(cpool);
	MemberValue[] elementMatchUrls = new StringMemberValue[matchUrl.length];
	for (int i = 0; i < matchUrl.length; i++) {
		elementMatchUrls[i] = new StringMemberValue(matchUrl[i], cpool);
	}
	arrayMemberValueMatchUrl.setValue(elementMatchUrls);
	annot.addMemberValue("matchUrl", arrayMemberValueMatchUrl);
	
	
	// downloader
	annot.addMemberValue("downloader", new StringMemberValue(downloader, cpool));
	// timeout
	annot.addMemberValue("timeout", new IntegerMemberValue(cpool, timeout));
	// pipelines
	ArrayMemberValue arrayMemberValue = new ArrayMemberValue(cpool);
	MemberValue[] elements = new StringMemberValue[pipelines.length];
	for (int i = 0; i < pipelines.length; i++) {
		elements[i] = new StringMemberValue(pipelines[i], cpool);
	}
	arrayMemberValue.setValue(elements);
	annot.addMemberValue("pipelines", arrayMemberValue);

	attr.addAnnotation(annot);
	cfile.addAttribute(attr);
	return this;
}
 
Example 12
Source File: ClassVisitor.java    From steady with Apache License 2.0 5 votes vote down vote up
/**
 * Adds the given annotations to the given field. Can be used to avoid problems with OR mappers by adding
 * an annotation "javax.persistence.Transient".
 * @param _fld
 * @param _annotations
 */
private void addFieldAnnotations(CtField _fld, String[] _annotations) {
	if(_annotations!=null && _annotations.length>0) {
		final ConstPool cpool = this.c.getClassFile().getConstPool();
		final AnnotationsAttribute attr = new AnnotationsAttribute(cpool, AnnotationsAttribute.visibleTag);
		for(String anno: _annotations) {
			final Annotation annot = new Annotation(anno, cpool);
			attr.addAnnotation(annot);
		}
		_fld.getFieldInfo().addAttribute(attr);
	}
}
 
Example 13
Source File: SwaggerMoreDoclet.java    From swagger-more with Apache License 2.0 5 votes vote down vote up
private static void annotateApiMethodAnn(ApiMethodInfo methodInfo, AnnotationsAttribute attr, ConstPool constPool) {
    Annotation apiMethodAnn = attr.getAnnotation(ApiMethod.class.getTypeName());
    MemberValue value;
    if (isNull(apiMethodAnn)) {
        apiMethodAnn = new Annotation(ApiMethod.class.getName(), constPool);
    }
    if (isNull(value = apiMethodAnn.getMemberValue(ApiMethodInfo.VALUE)) || StringUtils.isEmpty(((StringMemberValue) value).getValue())) {
        apiMethodAnn.addMemberValue(ApiMethodInfo.VALUE, new StringMemberValue(methodInfo.value(), constPool));
    }
    if (isNull(value = apiMethodAnn.getMemberValue(HIDDEN)) || !((BooleanMemberValue) value).getValue()) {
        apiMethodAnn.addMemberValue(HIDDEN, new BooleanMemberValue(methodInfo.hidden(), constPool));
    }
    if (isNull(value = apiMethodAnn.getMemberValue(NOTES)) || StringUtils.isEmpty(((StringMemberValue) value).getValue())) {
        apiMethodAnn.addMemberValue(NOTES, new StringMemberValue(methodInfo.notes(), constPool));
    }
    ArrayMemberValue arrayMemberValue = (ArrayMemberValue) apiMethodAnn.getMemberValue("params");
    if (isNull(arrayMemberValue)) {
        arrayMemberValue = new ArrayMemberValue(constPool);
        arrayMemberValue.setValue(new MemberValue[methodInfo.parameterCount()]);
    }
    AnnotationMemberValue annotationMemberValue;
    for (int i = 0; i < methodInfo.parameterCount(); i++) {
        if (isNull(annotationMemberValue = (AnnotationMemberValue) arrayMemberValue.getValue()[i])) {
            annotationMemberValue = new AnnotationMemberValue(new Annotation(ApiParam.class.getName(), constPool), constPool);
        }
        Annotation apiParamAnn = annotationMemberValue.getValue();
        if (isNull(value = apiParamAnn.getMemberValue(NAME)) || StringUtils.isEmpty(((StringMemberValue) value).getValue())) {
            apiParamAnn.addMemberValue(NAME, new StringMemberValue(methodInfo.param(i).name(), constPool));
        }
        if (isNull(value = apiParamAnn.getMemberValue(ApiMethodInfo.VALUE)) || StringUtils.isEmpty(((StringMemberValue) value).getValue())) {
            apiParamAnn.addMemberValue(ApiMethodInfo.VALUE, new StringMemberValue(methodInfo.param(i).value(), constPool));
        }
        arrayMemberValue.getValue()[i] = annotationMemberValue;

    }
    apiMethodAnn.addMemberValue(PARAMS, arrayMemberValue);
    attr.addAnnotation(apiMethodAnn);
}
 
Example 14
Source File: JavassistUtils.java    From statefulj with Apache License 2.0 5 votes vote down vote up
public static void copyTypeAnnotations(Class<?> fromClass, CtClass toClass) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
	for(java.lang.annotation.Annotation annotation :  fromClass.getAnnotations()) {
		if (!StatefulController.class.isAssignableFrom(annotation.annotationType())) {
			ClassFile ccFile = toClass.getClassFile();
			AnnotationsAttribute attr = getAnnotationsAttribute(ccFile);
			Annotation clone = cloneAnnotation(ccFile.getConstPool(), annotation);
			attr.addAnnotation(clone);
		}
	}
}
 
Example 15
Source File: JerseyBinder.java    From statefulj with Apache License 2.0 5 votes vote down vote up
@Override
protected void addEndpointMapping(
		CtMethod ctMethod, 
		String method,
		String request) {
	
	// Add Path Annotation
	//
	MethodInfo methodInfo = ctMethod.getMethodInfo();
	ConstPool constPool = methodInfo.getConstPool();

	AnnotationsAttribute annoAttr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
	Annotation pathMapping = new Annotation(Path.class.getName(), constPool);
	
	StringMemberValue valueVal = new StringMemberValue(constPool);
	valueVal.setValue(request);
	
	pathMapping.addMemberValue("value", valueVal);
	
	annoAttr.addAnnotation(pathMapping);

	// Add Verb Annotation (GET|POST|PUT|DELETE)
	//
	String verbClassName = "javax.ws.rs." + method;
	Annotation verb = new Annotation(verbClassName, constPool);
	annoAttr.addAnnotation(verb);
	
	methodInfo.addAttribute(annoAttr);
}
 
Example 16
Source File: AsmRest.java    From fastquery with Apache License 2.0 4 votes vote down vote up
/**
 * 自动生成Repository接口的实现类并以字节的形式返回.
 * 
 * @param repositoryClazz repository class
 * @return 生成的类字节码
 */
public static byte[] generateBytes(Class<?> repositoryClazz) {

	// 生成类
	ClassPool pool = ClassPool.getDefault();
	// web容器中的repository 需要增加classPath
	ClassClassPath classClassPath = new ClassClassPath(repositoryClazz);
	pool.removeClassPath(classClassPath);
	pool.insertClassPath(classClassPath);
	String className = repositoryClazz.getName() + Placeholder.REST_SUF;
	CtClass ctClass = pool.makeClass(className);

	ClassFile ccFile = ctClass.getClassFile();
	ConstPool constpool = ccFile.getConstPool();

	try {
		// 增加接口
		ctClass.setInterfaces(new CtClass[] { pool.get(repositoryClazz.getName()) });

		// 增加字段
		CtClass executor = pool.get(repositoryClazz.getName());
		CtField field = new CtField(executor, "d", ctClass);
		field.setModifiers(Modifier.PRIVATE);
		FieldInfo fieldInfo = field.getFieldInfo();
		// 标识属性注解
		AnnotationsAttribute fieldAttr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag);
		javassist.bytecode.annotation.Annotation autowired = new javassist.bytecode.annotation.Annotation(
				"javax.inject.Inject", constpool);
		fieldAttr.addAnnotation(autowired);
		fieldInfo.addAttribute(fieldAttr);
		ctClass.addField(field);
		
		AsmRepository.addGetInterfaceClassMethod(repositoryClazz, ctClass);
		
		// 标识类注解
		AnnotationsAttribute classAttr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag);
		javassist.bytecode.annotation.Annotation singAnn = new javassist.bytecode.annotation.Annotation(
				"javax.inject.Singleton", constpool);
		classAttr.addAnnotation(singAnn);
		ccFile.addAttribute(classAttr);

		// 实现抽象方法
		Method[] methods = repositoryClazz.getMethods();
		for (Method method : methods) {
			if (!method.isDefault()) {
				CtMethod cm = CtMethod.make(AsmRepository.getMethodDef(method) + "{return d."+method.getName()+"($$);}", ctClass);
				// 标识方法注解
				AnnotationsAttribute methodAttr = new AnnotationsAttribute(constpool,
						AnnotationsAttribute.visibleTag);
				javassist.bytecode.annotation.Annotation extendsAnn = new javassist.bytecode.annotation.Annotation(
						"org.fastquery.core.Extends", constpool);
				ArrayMemberValue arrayMemberValue = new ArrayMemberValue(constpool);
				Annotation[] mas = method.getAnnotations();
				ClassMemberValue[] cmvs = new ClassMemberValue[mas.length];
				for (int i = 0; i < mas.length; i++) {
					cmvs[i] = new ClassMemberValue(mas[i].annotationType().getName(), constpool);
				}
				arrayMemberValue.setValue(cmvs);
				extendsAnn.addMemberValue("value", arrayMemberValue);
				methodAttr.addAnnotation(extendsAnn);
				MethodInfo info = cm.getMethodInfo();
				info.addAttribute(methodAttr);
				ctClass.addMethod(cm);
			}
		}
		
		return ctClass.toBytecode();

	} catch (Exception e) {
		throw new ExceptionInInitializerError(e);
	}
}
 
Example 17
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 18
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);
    }
  }
}
 
Example 19
Source File: ContractTestUtil.java    From servicecomb-toolkit with Apache License 2.0 3 votes vote down vote up
public Class putAnnotationToClass(String className, Class annotationClass) throws Exception {

    CtClass ctClass = createCtClass(className);

    ConstPool constPool = ctClass.getClassFile().getConstPool();

    AnnotationsAttribute requestMappingAnnotationAttr = new AnnotationsAttribute(constPool,
        AnnotationsAttribute.visibleTag);
    Annotation requestMapping = new Annotation(annotationClass.getName(), constPool);

    requestMappingAnnotationAttr.addAnnotation(requestMapping);
    ctClass.getClassFile().addAttribute(requestMappingAnnotationAttr);

    return ctClass.toClass();
  }
 
Example 20
Source File: TransformationUtil.java    From jpmml-model with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
static
private void updatePropOrder(CtClass ctClass, String name){
	ClassFile classFile = ctClass.getClassFile();

	AnnotationsAttribute annotations = (AnnotationsAttribute)classFile.getAttribute(AnnotationsAttribute.visibleTag);

	Annotation xmlTypeAnnotation = annotations.getAnnotation("javax.xml.bind.annotation.XmlType");

	ArrayMemberValue propOrderValue = (ArrayMemberValue)xmlTypeAnnotation.getMemberValue("propOrder");

	removeValue(propOrderValue, name);

	annotations.addAnnotation(xmlTypeAnnotation);
}