Java Code Examples for javassist.bytecode.annotation.Annotation#addMemberValue()

The following examples show how to use javassist.bytecode.annotation.Annotation#addMemberValue() . 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: AbstractMethodCreator.java    From minnal with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the security annotation
 * 
 * @return
 */
protected Annotation getSecurityAnnotation() {
	Set<String> permissions = getPermissions();
	if (permissions == null || permissions.isEmpty()) {
		return null;
	}
	
	Annotation rolesAllowed = new Annotation(RolesAllowed.class.getCanonicalName(), ctClass.getClassFile().getConstPool());
	ArrayMemberValue values = new ArrayMemberValue(ctClass.getClassFile().getConstPool());
	List<StringMemberValue> memberValues = new ArrayList<StringMemberValue>();
	for (String permission : permissions) {
		memberValues.add(new StringMemberValue(permission, ctClass.getClassFile().getConstPool()));
	}
	values.setValue(memberValues.toArray(new StringMemberValue[0]));
	rolesAllowed.addMemberValue("value", values);
	return rolesAllowed;
}
 
Example 2
Source File: AbstractRestfulBinder.java    From statefulj with Apache License 2.0 6 votes vote down vote up
protected Annotation[] addIdParameter(
		CtMethod ctMethod, 
		Class<?> idType,
		ClassPool cp) throws NotFoundException, CannotCompileException {
	// Clone the parameter Class
	//
	CtClass ctParm = cp.get(idType.getName());
	
	// Add the parameter to the method
	//
	ctMethod.addParameter(ctParm);
	
	// Add the Parameter Annotations to the Method
	//
	MethodInfo methodInfo = ctMethod.getMethodInfo();
	ConstPool constPool = methodInfo.getConstPool();
	Annotation annot = new Annotation(getPathAnnotationClass().getName(), constPool);
	
	StringMemberValue valueVal = new StringMemberValue("id", constPool); 
	annot.addMemberValue("value", valueVal);
	
	return new Annotation[]{ annot };
}
 
Example 3
Source File: CreateMethodCreator.java    From minnal with Apache License 2.0 6 votes vote down vote up
@Override
protected void addParamAnnotations(CtMethod ctMethod) {
	Annotation[][] annotations = new Annotation[4][1];
	Annotation headersParam = new Annotation(Context.class.getCanonicalName(), ctMethod.getMethodInfo().getConstPool());
	annotations[0][0] = headersParam;
	Annotation uriInfoParam = new Annotation(Context.class.getCanonicalName(), ctMethod.getMethodInfo().getConstPool());
	annotations[1][0] = uriInfoParam;
	Annotation providersParam = new Annotation(Context.class.getCanonicalName(), ctMethod.getMethodInfo().getConstPool());
	annotations[2][0] = providersParam;
	Annotation apiParam = new Annotation(ApiParam.class.getCanonicalName(), ctMethod.getMethodInfo().getConstPool());
	apiParam.addMemberValue("name", new StringMemberValue("body", ctMethod.getMethodInfo().getConstPool()));
	apiParam.addMemberValue("access", new StringMemberValue("internal", ctMethod.getMethodInfo().getConstPool()));
	apiParam.addMemberValue("paramType", new StringMemberValue("body", ctMethod.getMethodInfo().getConstPool()));
	annotations[3][0] = apiParam;
	JavassistUtils.addParameterAnnotation(ctMethod, annotations);
}
 
Example 4
Source File: AbstractMethodCreator.java    From minnal with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the api path parameter annotations
 * 
 * @return
 */
protected List<Annotation> getApiPathParamAnnotations() {
	List<Annotation> annotations = new ArrayList<Annotation>();
	List<String> parameters = getRoutePattern().getParameterNames();
	for (int i = 0; i < parameters.size(); i++) {
		Annotation annotation = new Annotation(ApiImplicitParam.class.getCanonicalName(), ctClass.getClassFile().getConstPool());
		annotation.addMemberValue("name", new StringMemberValue(parameters.get(i), ctClass.getClassFile().getConstPool()));
		annotation.addMemberValue("paramType", new StringMemberValue("path", ctClass.getClassFile().getConstPool()));
		annotation.addMemberValue("dataType", new StringMemberValue(String.class.getCanonicalName(), ctClass.getClassFile().getConstPool()));
		annotation.addMemberValue("value", new StringMemberValue("The " + getResourcePath().getNodePath().get(i).getEntityMetaData().getName() + " identifier", ctClass.getClassFile().getConstPool()));
		annotation.addMemberValue("required", new BooleanMemberValue(true, ctClass.getClassFile().getConstPool()));
		if (i == parameters.size() - 1) {
			annotation.addMemberValue("allowMultiple", new BooleanMemberValue(true, ctClass.getClassFile().getConstPool()));
		}
		annotations.add(annotation);
	}
	return annotations;
}
 
Example 5
Source File: EnhanceMojo.java    From uima-uimafit with Apache License 2.0 6 votes vote down vote up
/**
 * Set a annotation member value if no value is present, if the present value is the default
 * generated by uimaFIT or if a override is active.
 * 
 * @param aAnnotation
 *          an annotation
 * @param aName
 *          the name of the member value
 * @param aNewValue
 *          the value to set
 * @param aOverride
 *          set value even if it is already set
 * @param aDefault
 *          default value set by uimaFIT - if the member has this value, it is considered unset
 */
private void enhanceMemberValue(Annotation aAnnotation, String aName, String aNewValue,
        boolean aOverride, String aDefault, ConstPool aConstPool,
        Multimap<String, String> aReportData, Class<?> aClazz) {
  String value = getStringMemberValue(aAnnotation, aName);
  boolean isEmpty = value.length() == 0;
  boolean isDefault = value.equals(aDefault);

  if (isEmpty || isDefault || aOverride) {
    if (aNewValue != null) {
      aAnnotation.addMemberValue(aName, new StringMemberValue(aNewValue, aConstPool));
      getLog().debug("Enhanced component meta data [" + aName + "]");
    } else {
      getLog().debug("No meta data [" + aName + "] found");
      aReportData.put(aClazz.getName(), "No meta data [" + aName + "] found");
    }
  } else {
    getLog().debug("Not overwriting component meta data [" + aName + "]");
  }
}
 
Example 6
Source File: JavassistDynamicField.java    From gecco with MIT License 6 votes vote down vote up
@Override
public DynamicField href(boolean click, String... value) {
	Annotation annot = new Annotation(Href.class.getName(), cpool);
       annot.addMemberValue("click", new BooleanMemberValue(click, cpool));
       
       ArrayMemberValue arrayMemberValue = new ArrayMemberValue(cpool);
       MemberValue[] memberValues = new StringMemberValue[value.length];
       for(int i = 0; i < value.length; i++) {
       	memberValues[i] = new StringMemberValue(value[i], cpool);
       }
       arrayMemberValue.setValue(memberValues);
       annot.addMemberValue("value", arrayMemberValue);
       
       attr.addAnnotation(annot);
	return this;
}
 
Example 7
Source File: JavassistDynamicField.java    From gecco with MIT License 5 votes vote down vote up
@Override
public DynamicField html(boolean outer) {
	Annotation annot = new Annotation(Html.class.getName(), cpool);
       annot.addMemberValue("outer", new BooleanMemberValue(outer, cpool));
       attr.addAnnotation(annot);
	return this;
}
 
Example 8
Source File: CreateMethodCreator.java    From minnal with Apache License 2.0 5 votes vote down vote up
@Override
protected Annotation getApiOperationAnnotation() {
	ConstPool constPool = getCtClass().getClassFile().getConstPool();
	EntityNodePath path = getResourcePath().getNodePath();
	EntityMetaData metaData = path.get(path.size() - 1).getEntityMetaData();
	Annotation annotation = new Annotation(ApiOperation.class.getCanonicalName(), constPool);
	annotation.addMemberValue("value", new StringMemberValue("Create " + metaData.getName(), constPool));
	annotation.addMemberValue("response", new ClassMemberValue(metaData.getEntityClass().getCanonicalName(), constPool));
	annotation.addMemberValue("responseContainer", new StringMemberValue("List", constPool));
	return annotation;
}
 
Example 9
Source File: AbstractMethodCreator.java    From minnal with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the 404 not found response annotation
 * 
 * @param responseClass
 * @return
 */
protected Annotation getNotFoundResponseAnnotation() {
	ConstPool constPool = ctClass.getClassFile().getConstPool();
	Annotation annotation = new Annotation(ApiResponse.class.getCanonicalName(), constPool);
	IntegerMemberValue code = new IntegerMemberValue(constPool);
	code.setValue(Response.Status.NOT_FOUND.getStatusCode());
	annotation.addMemberValue("code", code);
	annotation.addMemberValue("message", new StringMemberValue(Response.Status.NOT_FOUND.getReasonPhrase(), constPool));
	return annotation;
}
 
Example 10
Source File: AbstractMethodCreator.java    From minnal with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the #{@link Path} annotation
 * 
 * @return
 */
protected Annotation getPathAnnotation() {
	String relativePath = getRelativePath();
	if (Strings.isNullOrEmpty(relativePath)) {
		return null;
	}
	ConstPool constPool = ctClass.getClassFile().getConstPool();
	Annotation pathAnnotation = new Annotation(Path.class.getCanonicalName(), constPool);
	pathAnnotation.addMemberValue("value", new StringMemberValue(relativePath, constPool));
	return pathAnnotation;
}
 
Example 11
Source File: AbstractMethodCreator.java    From minnal with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the 200 ok response annotation
 * 
 * @param responseClass
 * @return
 */
protected Annotation getOkResponseAnnotation(Class<?> responseClass) {
	ConstPool constPool = ctClass.getClassFile().getConstPool();
	Annotation annotation = new Annotation(ApiResponse.class.getCanonicalName(), constPool);
	IntegerMemberValue code = new IntegerMemberValue(constPool);
	code.setValue(Response.Status.OK.getStatusCode());
	annotation.addMemberValue("code", code);
	annotation.addMemberValue("message", new StringMemberValue(Response.Status.OK.getReasonPhrase(), constPool));
	annotation.addMemberValue("response", new ClassMemberValue(responseClass.getCanonicalName(), constPool));
	return annotation;
}
 
Example 12
Source File: JavassistDynamicField.java    From gecco with MIT License 5 votes vote down vote up
@Override
public DynamicField jsvar(String var, String jsonpath) {
	Annotation annot = new Annotation(JSVar.class.getName(), cpool);
       annot.addMemberValue("var", new StringMemberValue(var, cpool));
       annot.addMemberValue("jsonpath", new StringMemberValue(jsonpath, cpool));
       attr.addAnnotation(annot);
	return this;
}
 
Example 13
Source File: AbstractMethodCreator.java    From minnal with Apache License 2.0 5 votes vote down vote up
protected Annotation getProducesAnnotation() {
	Annotation annotation = new Annotation(Produces.class.getCanonicalName(), getCtClass().getClassFile().getConstPool());
	ArrayMemberValue values = new ArrayMemberValue(getCtClass().getClassFile().getConstPool());
	StringMemberValue json = new StringMemberValue(MediaType.APPLICATION_JSON, getCtClass().getClassFile().getConstPool());
	StringMemberValue xml = new StringMemberValue(MediaType.APPLICATION_XML, getCtClass().getClassFile().getConstPool());
	values.setValue(new StringMemberValue[]{json, xml});
	annotation.addMemberValue("value", values);
	return annotation;
}
 
Example 14
Source File: DefaultRepositoryGenerator.java    From business with Mozilla Public License 2.0 5 votes vote down vote up
private Annotation copyAnnotation(ConstPool constPool,
        java.lang.annotation.Annotation annotation) throws NotFoundException {
    // Create annotation from specified type
    Annotation byteCodeAnnotation = createAnnotation(
            constPool,
            annotation.annotationType()
    );

    // Copy annotation methods
    for (Method m : annotation.annotationType().getDeclaredMethods()) {
        Object value = invoke(m, annotation);
        MemberValue memberValue = createMemberValue(
                constPool,
                classPool.get(value.getClass().getName())
        );

        invoke(from(memberValue.getClass())
                        .method("setValue", new Class[]{value.getClass()})
                        .orElseThrow(() -> new NotFoundException("Cannot copy value of qualifier parameter "
                                + m.getName())),
                memberValue,
                value);

        byteCodeAnnotation.addMemberValue(
                m.getName(),
                memberValue
        );
    }

    return byteCodeAnnotation;
}
 
Example 15
Source File: CreateMethodCreator.java    From minnal with Apache License 2.0 5 votes vote down vote up
protected Annotation getBodyParamAnnotation() {
	EntityNodePath path = getResourcePath().getNodePath();
	EntityMetaData metaData = path.get(path.size() - 1).getEntityMetaData();
	Annotation annotation = new Annotation(ApiImplicitParam.class.getCanonicalName(), getCtClass().getClassFile().getConstPool());
	annotation.addMemberValue("name", new StringMemberValue("body", getCtClass().getClassFile().getConstPool()));
	annotation.addMemberValue("paramType", new StringMemberValue("body", getCtClass().getClassFile().getConstPool()));
	annotation.addMemberValue("dataType", new StringMemberValue("Array[" + metaData.getEntityClass().getCanonicalName() + "]", getCtClass().getClassFile().getConstPool()));
	annotation.addMemberValue("value", new StringMemberValue(metaData.getName() + " payload", getCtClass().getClassFile().getConstPool()));
	return annotation;
}
 
Example 16
Source File: ReadMethodCreator.java    From minnal with Apache License 2.0 5 votes vote down vote up
@Override
protected Annotation getApiOperationAnnotation() {
	ConstPool constPool = getCtClass().getClassFile().getConstPool();
	EntityNodePath path = getResourcePath().getNodePath();
	EntityMetaData metaData = path.get(path.size() - 1).getEntityMetaData();
	Annotation annotation = new Annotation(ApiOperation.class.getCanonicalName(), constPool);
	annotation.addMemberValue("value", new StringMemberValue("Find " + getResourcePath().getNodePath().getName() + " by id", constPool));
	annotation.addMemberValue("response", new ClassMemberValue(metaData.getEntityClass().getCanonicalName(), constPool));
	return annotation;
}
 
Example 17
Source File: JavassistUtils.java    From statefulj with Apache License 2.0 5 votes vote down vote up
public static void addResourceAnnotation(CtField field, String beanName) {
	FieldInfo fi = field.getFieldInfo();
	
	AnnotationsAttribute attr = new AnnotationsAttribute(
			field.getFieldInfo().getConstPool(), 
			AnnotationsAttribute.visibleTag);
	Annotation annot = new Annotation(Resource.class.getName(), fi.getConstPool());
	
	StringMemberValue nameValue = new StringMemberValue(fi.getConstPool());
	nameValue.setValue(beanName);
	annot.addMemberValue("name", nameValue);
	
	attr.addAnnotation(annot);
	fi.addAttribute(attr);
}
 
Example 18
Source File: JavassistUtils.java    From CrossMobile with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static Annotation constructAnnotation(ConstPool cp, String annotationName, JavassistAnnParam... params) {
    Annotation ann = new Annotation(annotationName, cp);
    for (JavassistAnnParam p : params)
        if (p != null)
            ann.addMemberValue(p.getName(), p.getValue(cp));
    return ann;
}
 
Example 19
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 20
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);
    }
  }
}