javassist.bytecode.ConstPool Java Examples

The following examples show how to use javassist.bytecode.ConstPool. 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: JavassistUtils.java    From statefulj with Apache License 2.0 6 votes vote down vote up
public static void addMethodAnnotations(CtMethod ctMethod, Method method) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
	if (method != null) {
		MethodInfo methodInfo = ctMethod.getMethodInfo();
		ConstPool constPool = methodInfo.getConstPool();
		AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
		methodInfo.addAttribute(attr);
		for(java.lang.annotation.Annotation anno : method.getAnnotations()) {

			// If it's a Transition skip
			// TODO : Make this a parameterized set of Filters instead of hardcoding
			//
			Annotation clone = null;
			if (anno instanceof Transitions || anno instanceof Transition) {
				// skip
			} else {
				clone = cloneAnnotation(constPool, anno);
				attr.addAnnotation(clone);
			}
		}
	}
}
 
Example #2
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 #3
Source File: CtMethodBuilder.java    From japicmp with Apache License 2.0 6 votes vote down vote up
public CtMethod addToClass(CtClass declaringClass) throws CannotCompileException {
	if (this.returnType == null) {
		this.returnType = declaringClass;
	}
	CtMethod ctMethod = CtNewMethod.make(this.modifier, this.returnType, this.name, this.parameters, this.exceptions, this.body, declaringClass);
	ctMethod.setModifiers(this.modifier);
	declaringClass.addMethod(ctMethod);
	for (String annotation : annotations) {
		ClassFile classFile = declaringClass.getClassFile();
		ConstPool constPool = classFile.getConstPool();
		AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
		Annotation annot = new Annotation(annotation, constPool);
		attr.setAnnotation(annot);
		ctMethod.getMethodInfo().addAttribute(attr);
	}
	return ctMethod;
}
 
Example #4
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 #5
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 #6
Source File: BulkAccessorFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Declares a constructor that takes no parameter.
 *
 * @param classfile The class descriptor
 *
 * @throws CannotCompileException Indicates trouble with the underlying Javassist calls
 */
private void addDefaultConstructor(ClassFile classfile) throws CannotCompileException {
	final ConstPool constPool = classfile.getConstPool();
	final String constructorSignature = "()V";
	final MethodInfo constructorMethodInfo = new MethodInfo( constPool, MethodInfo.nameInit, constructorSignature );

	final Bytecode code = new Bytecode( constPool, 0, 1 );
	// aload_0
	code.addAload( 0 );
	// invokespecial
	code.addInvokespecial( BulkAccessor.class.getName(), MethodInfo.nameInit, constructorSignature );
	// return
	code.addOpcode( Opcode.RETURN );

	constructorMethodInfo.setCodeAttribute( code.toCodeAttribute() );
	constructorMethodInfo.setAccessFlags( AccessFlag.PUBLIC );
	classfile.addMethod( constructorMethodInfo );
}
 
Example #7
Source File: Proxy.java    From hsweb-framework with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("all")
public static MemberValue createMemberValue(Object value, ConstPool constPool) {
    MemberValue memberValue = null;
    if (value instanceof Integer) {
        memberValue = new IntegerMemberValue(constPool, ((Integer) value));
    } else if (value instanceof Boolean) {
        memberValue = new BooleanMemberValue((Boolean) value, constPool);
    } else if (value instanceof Long) {
        memberValue = new LongMemberValue((Long) value, constPool);
    } else if (value instanceof String) {
        memberValue = new StringMemberValue((String) value, constPool);
    } else if (value instanceof Class) {
        memberValue = new ClassMemberValue(((Class) value).getName(), constPool);
    } else if (value instanceof Object[]) {
        Object[] arr = ((Object[]) value);
        ArrayMemberValue arrayMemberValue = new ArrayMemberValue(new ClassMemberValue(arr[0].getClass().getName(), constPool), constPool);
        arrayMemberValue.setValue(Arrays.stream(arr)
                .map(o -> createMemberValue(o, constPool))
                .toArray(MemberValue[]::new));
        memberValue = arrayMemberValue;

    }
    return memberValue;
}
 
Example #8
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 #9
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 #10
Source File: FieldTransformer.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void addSetFieldHandlerMethod(ClassFile classfile)
		throws CannotCompileException {
	ConstPool cp = classfile.getConstPool();
	int this_class_index = cp.getThisClassInfo();
	MethodInfo minfo = new MethodInfo(cp, SETFIELDHANDLER_METHOD_NAME,
	                                  SETFIELDHANDLER_METHOD_DESCRIPTOR);
	/* local variables | this | callback | */
	Bytecode code = new Bytecode(cp, 3, 3);
	// aload_0 // load this
	code.addAload(0);
	// aload_1 // load callback
	code.addAload(1);
	// putfield // put field "$JAVASSIST_CALLBACK" defined already
	code.addOpcode(Opcode.PUTFIELD);
	int field_index = cp.addFieldrefInfo(this_class_index,
	                                     HANDLER_FIELD_NAME, HANDLER_FIELD_DESCRIPTOR);
	code.addIndex(field_index);
	// return
	code.addOpcode(Opcode.RETURN);
	minfo.setCodeAttribute(code.toCodeAttribute());
	minfo.setAccessFlags(AccessFlag.PUBLIC);
	classfile.addMethod(minfo);
}
 
Example #11
Source File: FieldTransformer.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private int transformInvokevirtualsIntoGetfields(ClassFile classfile,
                                                 CodeIterator iter, int pos) {
	ConstPool cp = classfile.getConstPool();
	int c = iter.byteAt(pos);
	if (c != Opcode.GETFIELD) {
		return pos;
	}
	int index = iter.u16bitAt(pos + 1);
	String fieldName = cp.getFieldrefName(index);
	String className = cp.getFieldrefClassName(index);
	if ((!classfile.getName().equals(className))
	    || (!readableFields.containsKey(fieldName))) {
		return pos;
	}
	String desc = "()" + (String) readableFields.get(fieldName);
	int read_method_index = cp.addMethodrefInfo(cp.getThisClassInfo(),
	                                            EACH_READ_METHOD_PREFIX + fieldName, desc);
	iter.writeByte(Opcode.INVOKEVIRTUAL, pos);
	iter.write16bit(read_method_index, pos + 1);
	return pos;
}
 
Example #12
Source File: FieldTransformer.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private int transformInvokevirtualsIntoPutfields(ClassFile classfile,
                                                 CodeIterator iter, int pos) {
	ConstPool cp = classfile.getConstPool();
	int c = iter.byteAt(pos);
	if (c != Opcode.PUTFIELD) {
		return pos;
	}
	int index = iter.u16bitAt(pos + 1);
	String fieldName = cp.getFieldrefName(index);
	String className = cp.getFieldrefClassName(index);
	if ((!classfile.getName().equals(className))
	    || (!writableFields.containsKey(fieldName))) {
		return pos;
	}
	String desc = "(" + (String) writableFields.get(fieldName) + ")V";
	int write_method_index = cp.addMethodrefInfo(cp.getThisClassInfo(),
	                                             EACH_WRITE_METHOD_PREFIX + fieldName, desc);
	iter.writeByte(Opcode.INVOKEVIRTUAL, pos);
	iter.write16bit(write_method_index, pos + 1);
	return pos;
}
 
Example #13
Source File: CtMethodBuilder.java    From japicmp with Apache License 2.0 6 votes vote down vote up
public CtMethod addToClass(CtClass declaringClass) throws CannotCompileException {
	if (this.returnType == null) {
		this.returnType = declaringClass;
	}
	CtMethod ctMethod = CtNewMethod.make(this.modifier, this.returnType, this.name, this.parameters, this.exceptions, this.body, declaringClass);
	ctMethod.setModifiers(this.modifier);
	declaringClass.addMethod(ctMethod);
	for (String annotation : annotations) {
		ClassFile classFile = declaringClass.getClassFile();
		ConstPool constPool = classFile.getConstPool();
		AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
		Annotation annot = new Annotation(annotation, constPool);
		attr.setAnnotation(annot);
		ctMethod.getMethodInfo().addAttribute(attr);
	}
	return ctMethod;
}
 
Example #14
Source File: DefaultRepositoryGenerator.java    From business with Mozilla Public License 2.0 6 votes vote down vote up
private CtConstructor createConstructor(ConstPool constPool, CtClass declaringClass) throws NotFoundException,
        CannotCompileException {
    CtConstructor cc = new CtConstructor(new CtClass[]{
            declaringClass.getClassPool().getCtClass(Object.class.getName() + "[]")
    }, declaringClass);

    // Define the constructor behavior
    cc.setBody("super($1);");
    cc.setModifiers(Modifier.PUBLIC);

    // Add the @Inject annotation to the constructor
    addInjectAnnotation(constPool, cc);

    // Add the @Assisted annotation to the constructor parameter
    addAssistedAnnotation(constPool, cc);

    return cc;
}
 
Example #15
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 #16
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 #17
Source File: FieldTransformer.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void addGetFieldHandlerMethod(ClassFile classfile)
		throws CannotCompileException {
	ConstPool cp = classfile.getConstPool();
	int this_class_index = cp.getThisClassInfo();
	MethodInfo minfo = new MethodInfo(cp, GETFIELDHANDLER_METHOD_NAME,
	                                  GETFIELDHANDLER_METHOD_DESCRIPTOR);
	/* local variable | this | */
	Bytecode code = new Bytecode(cp, 2, 1);
	// aload_0 // load this
	code.addAload(0);
	// getfield // get field "$JAVASSIST_CALLBACK" defined already
	code.addOpcode(Opcode.GETFIELD);
	int field_index = cp.addFieldrefInfo(this_class_index,
	                                     HANDLER_FIELD_NAME, HANDLER_FIELD_DESCRIPTOR);
	code.addIndex(field_index);
	// areturn // return the value of the field
	code.addOpcode(Opcode.ARETURN);
	minfo.setCodeAttribute(code.toCodeAttribute());
	minfo.setAccessFlags(AccessFlag.PUBLIC);
	classfile.addMethod(minfo);
}
 
Example #18
Source File: CtClassBuilder.java    From japicmp with Apache License 2.0 6 votes vote down vote up
public CtClass addToClassPool(ClassPool classPool) {
	CtClass ctClass;
	if (this.superclass.isPresent()) {
		ctClass = classPool.makeClass(this.name, this.superclass.get());
	} else {
		ctClass = classPool.makeClass(this.name);
	}
	ctClass.setModifiers(this.modifier);
	for (String annotation : annotations) {
		ClassFile classFile = ctClass.getClassFile();
		ConstPool constPool = classFile.getConstPool();
		AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
		Annotation annot = new Annotation(annotation, constPool);
		attr.setAnnotation(annot);
		ctClass.getClassFile2().addAttribute(attr);
	}
	for (CtClass interfaceCtClass : interfaces) {
		ctClass.addInterface(interfaceCtClass);
	}
	return ctClass;
}
 
Example #19
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 #20
Source File: ActionMethodCreator.java    From minnal with Apache License 2.0 5 votes vote down vote up
@Override
protected Annotation getApiOperationAnnotation() {
	ConstPool constPool = getCtClass().getClassFile().getConstPool();
	Annotation annotation = new Annotation(ApiOperation.class.getCanonicalName(), constPool);
	annotation.addMemberValue("value", new StringMemberValue("Performs action on " + getResourcePath().getNodePath().getName(), constPool));
	return annotation;
}
 
Example #21
Source File: JavassistDynamicField.java    From gecco with MIT License 5 votes vote down vote up
public JavassistDynamicField(DynamicBean dynamicBean, CtClass clazz, ConstPool cpool, String fieldName) {
	try {
		this.dynamicBean = dynamicBean;
		this.cpool = cpool;
		this.cfield  = clazz.getField(fieldName);
		attr = new AnnotationsAttribute(cpool, AnnotationsAttribute.visibleTag);
	} catch (NotFoundException e) {
		log.error(fieldName + " not found");
	}
}
 
Example #22
Source File: JValidator.java    From dubbox with Apache License 2.0 5 votes vote down vote up
private static MemberValue createMemberValue(ConstPool cp, CtClass type, Object value) throws NotFoundException {
    MemberValue memberValue = javassist.bytecode.annotation.Annotation.createMemberValue(cp, type);
    if (memberValue instanceof BooleanMemberValue)
        ((BooleanMemberValue) memberValue).setValue((Boolean) value);
    else if (memberValue instanceof ByteMemberValue)
        ((ByteMemberValue) memberValue).setValue((Byte) value);
    else if (memberValue instanceof CharMemberValue)
        ((CharMemberValue) memberValue).setValue((Character) value);
    else if (memberValue instanceof ShortMemberValue)
        ((ShortMemberValue) memberValue).setValue((Short) value);
    else if (memberValue instanceof IntegerMemberValue)
        ((IntegerMemberValue) memberValue).setValue((Integer) value);
    else if (memberValue instanceof LongMemberValue)
        ((LongMemberValue) memberValue).setValue((Long) value);
    else if (memberValue instanceof FloatMemberValue)
        ((FloatMemberValue) memberValue).setValue((Float) value);
    else if (memberValue instanceof DoubleMemberValue)
        ((DoubleMemberValue) memberValue).setValue((Double) value);
    else if (memberValue instanceof ClassMemberValue)
        ((ClassMemberValue) memberValue).setValue(((Class<?>)value).getName());
    else if (memberValue instanceof StringMemberValue)
        ((StringMemberValue) memberValue).setValue((String) value);
    else if (memberValue instanceof EnumMemberValue) 
        ((EnumMemberValue) memberValue).setValue(((Enum<?>) value).name());
    /* else if (memberValue instanceof AnnotationMemberValue) */
    else if (memberValue instanceof ArrayMemberValue) {
        CtClass arrayType = type.getComponentType();
        int len = Array.getLength(value);
        MemberValue[] members = new MemberValue[len];
        for (int i = 0; i < len; i ++) {
            members[i] = createMemberValue(cp, arrayType, Array.get(value, i));
        }
        ((ArrayMemberValue) memberValue).setValue(members);
    }
    return memberValue;
}
 
Example #23
Source File: IgniteExamplesMLTestSuite.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Creates test class for given example.
 *
 * @param exampleCls Class of the example to be tested.
 * @return Test class.
 */
private static Class<?> makeTestClass(Class<?> exampleCls) {
    ClassPool cp = ClassPool.getDefault();
    cp.insertClassPath(new ClassClassPath(IgniteExamplesMLTestSuite.class));

    CtClass cl = cp.makeClass(basePkgForTests + "." + exampleCls.getSimpleName() + "SelfTest");

    try {
        cl.setSuperclass(cp.get(GridAbstractExamplesTest.class.getName()));

        CtMethod mtd = CtNewMethod.make("public void testExample() { "
            + exampleCls.getCanonicalName()
            + ".main("
            + MLExamplesCommonArgs.class.getName()
            + ".EMPTY_ARGS_ML); }", cl);

        // Create and add annotation.
        ClassFile ccFile = cl.getClassFile();
        ConstPool constpool = ccFile.getConstPool();

        AnnotationsAttribute attr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag);
        Annotation annot = new Annotation("org.junit.Test", constpool);

        attr.addAnnotation(annot);
        mtd.getMethodInfo().addAttribute(attr);

        cl.addMethod(mtd);

        return cl.toClass();
    }
    catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #24
Source File: SwaggerMoreDoclet.java    From swagger-more with Apache License 2.0 5 votes vote down vote up
private static void annotateMethodAnn(CtClass ctClass,
                                      ApiMethodInfo methodInfo) throws NotFoundException {
    ConstPool constPool = ctClass.getClassFile().getConstPool();
    for (CtMethod ctMethod : ctClass.getDeclaredMethods(methodInfo.methodName())) {
        if (Stream.of(ctMethod.getParameterTypes()).map(CtClass::getSimpleName).collect(joining(", ")).equals(methodInfo.parameterNames())) {
            AnnotationsAttribute attr = getAnnotationAttr(ctMethod);
            annotateDeprecatedAnn(methodInfo, attr, constPool);
            annotateApiMethodAnn(methodInfo, attr, constPool);
            ctMethod.getMethodInfo().addAttribute(attr);
        }
    }
}
 
Example #25
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 #26
Source File: JavassistAnnParam.java    From CrossMobile with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static JavassistAnnParam toParam(String name, byte value) {
    return new JavassistAnnParam(name) {

        @Override
        public MemberValue getValue(ConstPool cp) {
            return new ByteMemberValue(value, cp);
        }
    };
}
 
Example #27
Source File: MapperAnnotationEnhancer.java    From tsharding with MIT License 5 votes vote down vote up
private static MemberValue createMemberValue(Class<?> type, Object val, ConstPool cp) {
    if (type == String.class) {
        return new StringMemberValue((String) val, cp);
    } else {
        throw new RuntimeException("Only support string param value! Invalid param value type:" + type + " and value: " + val);
    }
}
 
Example #28
Source File: MapperAnnotationEnhancer.java    From tsharding with MIT License 5 votes vote down vote up
public static ParameterAnnotationsAttribute duplicateParameterAnnotationsAttribute(ConstPool cp, Method method) {
    ParameterAnnotationsAttribute oldAns = new ParameterAnnotationsAttribute(cp, ParameterAnnotationsAttribute.visibleTag);
    javassist.bytecode.annotation.Annotation[][] anAr = new javassist.bytecode.annotation.Annotation[method.getParameterAnnotations().length][];
    for (int i = 0; i < anAr.length; ++i) {
        anAr[i] = new javassist.bytecode.annotation.Annotation[method.getParameterAnnotations()[i].length];
        for (int j = 0; j < anAr[i].length; ++j) {
            anAr[i][j] = createJavassistAnnotation(method.getParameterAnnotations()[i][j], cp);
        }
    }
    oldAns.setAnnotations(anAr);
    return oldAns;
}
 
Example #29
Source File: ResourceClassCreator.java    From minnal with Apache License 2.0 5 votes vote down vote up
public CtClass create() {
	CtClass ctClass = null;
	if (resource != null) {
		logger.debug("Creating the generated class for the resource {}", resource.getResourceClass());
		
		try {
			CtClass superClass = classPool.get(resource.getResourceClass().getName());
			superClass.defrost();
			ctClass = classPool.makeClass(namingStrategy.getResourceWrapperClassName(resource.getResourceClass()), superClass);
		} catch (Exception e) {
			logger.error("Failed while creating the generated class for the resource - " + resource.getResourceClass(), e);
			throw new MinnalInstrumentationException("Failed while creating the generated class", e);
		}
	} else {
		if (entityClass == null) {
			logger.error("Entity Class not defined in the resource wrapper");
			throw new MinnalInstrumentationException("Entity Class not defined in the resource class");
		}
		
		logger.debug("Creating the generated class for the entity {}", entityClass);
		ctClass = classPool.makeClass(namingStrategy.getResourceClassName(entityClass));
	}
	
	ConstPool constPool = ctClass.getClassFile().getConstPool();
	JavassistUtils.addClassAnnotations(ctClass, getApiAnnotation(constPool), getPathAnnotation(constPool));
	return ctClass;
}
 
Example #30
Source File: LocalBeanServiceInvoker.java    From jsongood with Apache License 2.0 5 votes vote down vote up
private static MemberValue createMemberValue(ConstPool cp, CtClass type, Object value) throws NotFoundException {
    MemberValue memberValue = javassist.bytecode.annotation.Annotation.createMemberValue(cp, type);
    if (memberValue instanceof BooleanMemberValue)
        ((BooleanMemberValue) memberValue).setValue((Boolean) value);
    else if (memberValue instanceof ByteMemberValue)
        ((ByteMemberValue) memberValue).setValue((Byte) value);
    else if (memberValue instanceof CharMemberValue)
        ((CharMemberValue) memberValue).setValue((Character) value);
    else if (memberValue instanceof ShortMemberValue)
        ((ShortMemberValue) memberValue).setValue((Short) value);
    else if (memberValue instanceof IntegerMemberValue)
        ((IntegerMemberValue) memberValue).setValue((Integer) value);
    else if (memberValue instanceof LongMemberValue)
        ((LongMemberValue) memberValue).setValue((Long) value);
    else if (memberValue instanceof FloatMemberValue)
        ((FloatMemberValue) memberValue).setValue((Float) value);
    else if (memberValue instanceof DoubleMemberValue)
        ((DoubleMemberValue) memberValue).setValue((Double) value);
    else if (memberValue instanceof ClassMemberValue)
        ((ClassMemberValue) memberValue).setValue(((Class<?>) value).getName());
    else if (memberValue instanceof StringMemberValue)
        ((StringMemberValue) memberValue).setValue((String) value);
    else if (memberValue instanceof EnumMemberValue)
        ((EnumMemberValue) memberValue).setValue(((Enum<?>) value).name());
    /* else if (memberValue instanceof AnnotationMemberValue) */
    else if (memberValue instanceof ArrayMemberValue) {
        CtClass arrayType = type.getComponentType();
        int len = Array.getLength(value);
        MemberValue[] members = new MemberValue[len];
        for (int i = 0; i < len; i++) {
            members[i] = createMemberValue(cp, arrayType, Array.get(value, i));
        }
        ((ArrayMemberValue) memberValue).setValue(members);
    }
    return memberValue;
}