Search in sources :

Example 1 with Generated

use of javax.annotation.processing.Generated in project tritium by palantir.

the class TritiumAnnotationProcessor method generate.

@SuppressWarnings("checkstyle:CyclomaticComplexity")
private JavaFile generate(TypeElement typeElement, List<DeclaredType> allInterfaces, List<DeclaredType> minimalInterfaces) {
    TypeName annotatedType = TypeName.get(typeElement.asType());
    TypeName delegateType = TypeElements.unwrapEmptyInterface(elements, typeElement).orElse(annotatedType);
    String packageName = elements.getPackageOf(typeElement).getQualifiedName().toString();
    String className = "Instrumented" + typeElement.getSimpleName();
    List<TypeName> interfaceNames = new ArrayList<>(minimalInterfaces.size());
    List<TypeVariableName> typeVarNames = new ArrayList<>();
    for (DeclaredType type : minimalInterfaces) {
        interfaceNames.add(TypeName.get(type));
        for (TypeMirror typeArg : type.getTypeArguments()) {
            if (typeArg instanceof TypeVariable) {
                typeVarNames.add(TypeVariableName.get((TypeVariable) typeArg));
            }
        }
    }
    TypeSpec.Builder specBuilder = TypeSpec.classBuilder(className).addModifiers(Modifier.PUBLIC, Modifier.FINAL).addOriginatingElement(typeElement).addAnnotation(AnnotationSpec.builder(Generated.class).addMember("value", "$S", getClass().getName()).build());
    if (typeElement.getAnnotation(Deprecated.class) != null) {
        specBuilder.addAnnotation(Deprecated.class);
    }
    specBuilder.addSuperinterfaces(interfaceNames).addTypeVariables(typeVarNames).addField(FieldSpec.builder(delegateType, DELEGATE_NAME, Modifier.PRIVATE, Modifier.FINAL).build()).addField(FieldSpec.builder(ParameterizedTypeName.get(InvocationEventHandler.class, InvocationContext.class), HANDLER_NAME, Modifier.PRIVATE, Modifier.FINAL).build()).addField(FieldSpec.builder(InstrumentationFilter.class, FILTER_NAME, Modifier.PRIVATE, Modifier.FINAL).build()).addMethod(MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE).addParameter(ParameterSpec.builder(delegateType, DELEGATE_NAME).build()).addParameter(ParameterSpec.builder(ParameterizedTypeName.get(InvocationEventHandler.class, InvocationContext.class), HANDLER_NAME).build()).addParameter(ParameterSpec.builder(InstrumentationFilter.class, FILTER_NAME).build()).addStatement("this.$1N = $1N", DELEGATE_NAME).addStatement("this.$1N = $1N", HANDLER_NAME).addStatement("this.$1N = $1N", FILTER_NAME).build());
    Map<String, List<MethodElements>> methodsByName = new HashMap<>();
    for (DeclaredType mirror : allInterfaces) {
        // noisy
        @SuppressWarnings("VoidMissingNullable") SimpleElementVisitor8<Void, Void> visitor = createVisitor(typeElement, methodsByName, mirror);
        for (Element methodElement : types.asElement(mirror).getEnclosedElements()) {
            if (!methodElement.getModifiers().contains(Modifier.STATIC) && !methodElement.getModifiers().contains(Modifier.PRIVATE)) {
                methodElement.accept(visitor, null);
            }
        }
    }
    List<MethodElements> instrumentedMethods = new ArrayList<>();
    for (List<MethodElements> methods : methodsByName.values()) {
        for (int i = 0; i < methods.size(); i++) {
            if (isMostSpecific(i, methods)) {
                instrumentedMethods.add(methods.get(i));
            }
        }
    }
    if (instrumentedMethods.isEmpty()) {
        messager.printMessage(Kind.ERROR, "Cannot generate an instrumented implementation. The annotated interface has no methods", typeElement);
    }
    IdentityHashMap<MethodElements, String> methodStaticFields = Methods.methodStaticFieldName(instrumentedMethods, specBuilder, annotatedType);
    for (MethodElements method : instrumentedMethods) {
        createMethod(method, specBuilder, methodStaticFields);
    }
    specBuilder.addMethod(MethodSpec.methodBuilder("toString").addAnnotation(Override.class).returns(String.class).addModifiers(Modifier.PUBLIC).addStatement("return $S + $N + '}'", className + "{", DELEGATE_NAME).build()).addMethod(MethodSpec.methodBuilder("builder").addTypeVariables(typeVarNames).addModifiers(Modifier.PUBLIC, Modifier.STATIC).returns(ParameterizedTypeName.get(ClassName.get(InstrumentationBuilder.class), delegateType, annotatedType)).addParameter(ParameterSpec.builder(delegateType, DELEGATE_NAME).build()).addStatement("return new $T<$T, $T>($T.class, delegate, $N::new)", InstrumentationBuilder.class, delegateType, annotatedType, TypeNames.erased(delegateType), className).build()).addMethod(MethodSpec.methodBuilder("instrument").addTypeVariables(typeVarNames).addModifiers(Modifier.PUBLIC, Modifier.STATIC).returns(annotatedType).addParameter(ParameterSpec.builder(delegateType, DELEGATE_NAME).build()).addParameter(ParameterSpec.builder(TaggedMetricRegistry.class, "registry").build()).addStatement("return builder(delegate).withTaggedMetrics(registry).withTracing().build()").build());
    if (specBuilder.originatingElements.size() != 1) {
        messager.printMessage(Kind.ERROR, "The generated type must have exactly one originating element: " + specBuilder.originatingElements, typeElement);
    }
    return JavaFile.builder(packageName, specBuilder.build()).skipJavaLangImports(true).indent("    ").build();
}
Also used : TypeName(com.squareup.javapoet.TypeName) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) InstrumentationBuilder(com.palantir.tritium.annotations.internal.InstrumentationBuilder) InvocationEventHandler(com.palantir.tritium.event.InvocationEventHandler) IdentityHashMap(java.util.IdentityHashMap) HashMap(java.util.HashMap) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) ExecutableElement(javax.lang.model.element.ExecutableElement) ArrayList(java.util.ArrayList) TypeMirror(javax.lang.model.type.TypeMirror) TypeVariable(javax.lang.model.type.TypeVariable) List(java.util.List) ArrayList(java.util.ArrayList) InvocationContext(com.palantir.tritium.event.InvocationContext) Generated(javax.annotation.processing.Generated) InstrumentationFilter(com.palantir.tritium.api.event.InstrumentationFilter) TaggedMetricRegistry(com.palantir.tritium.metrics.registry.TaggedMetricRegistry) TypeVariableName(com.squareup.javapoet.TypeVariableName) DeclaredType(javax.lang.model.type.DeclaredType) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 2 with Generated

use of javax.annotation.processing.Generated in project ignite-3 by apache.

the class AsmMarshallerGenerator method generateMarshallerClass.

/**
 * Generates marshaller class definition.
 *
 * @param className Marshaller class name.
 * @param schema    Schema descriptor.
 * @param keyClass  Key class.
 * @param valClass  Value class.
 * @return Generated java class definition.
 */
private ClassDefinition generateMarshallerClass(String className, SchemaDescriptor schema, Class<?> keyClass, Class<?> valClass) {
    MarshallerCodeGenerator keyMarsh = createMarshaller(keyClass, schema.keyColumns(), 0);
    MarshallerCodeGenerator valMarsh = createMarshaller(valClass, schema.valueColumns(), schema.keyColumns().length());
    final ClassDefinition classDef = new ClassDefinition(EnumSet.of(Access.PUBLIC), MARSHALLER_PACKAGE_NAME.replace('.', '/') + '/' + className, ParameterizedType.type(Object.class), ParameterizedType.type(KvMarshaller.class));
    classDef.declareAnnotation(Generated.class).setValue("value", getClass().getCanonicalName());
    final FieldDefinition keyClassField = classDef.declareField(EnumSet.of(Access.PRIVATE, Access.STATIC, Access.FINAL), "KEY_CLASS", Class.class);
    final FieldDefinition valueClassField = classDef.declareField(EnumSet.of(Access.PRIVATE, Access.STATIC, Access.FINAL), "VALUE_CLASS", Class.class);
    keyMarsh.initStaticHandlers(classDef, keyClassField);
    valMarsh.initStaticHandlers(classDef, valueClassField);
    generateFieldsAndConstructor(classDef);
    generateAssemblerFactoryMethod(classDef, schema, keyMarsh, valMarsh);
    generateSchemaVersionMethod(classDef, schema);
    generateMarshalMethod(classDef, keyMarsh, valMarsh);
    generateUnmarshalKeyMethod(classDef, keyMarsh);
    generateUnmarshalValueMethod(classDef, valMarsh);
    return classDef;
}
Also used : Generated(javax.annotation.processing.Generated) FieldDefinition(com.facebook.presto.bytecode.FieldDefinition) KvMarshaller(org.apache.ignite.internal.schema.marshaller.KvMarshaller) ClassDefinition(com.facebook.presto.bytecode.ClassDefinition)

Example 3 with Generated

use of javax.annotation.processing.Generated in project ignite-3 by apache.

the class KvMarshallerTest method createGeneratedObjectClass.

/**
 * Generate class for test objects.
 *
 * @return Generated test object class.
 */
private Class<?> createGeneratedObjectClass() {
    final String packageName = getClass().getPackageName();
    final String className = "GeneratedTestObject";
    final ClassDefinition classDef = new ClassDefinition(EnumSet.of(Access.PUBLIC), packageName.replace('.', '/') + '/' + className, ParameterizedType.type(Object.class));
    classDef.declareAnnotation(Generated.class).setValue("value", getClass().getCanonicalName());
    for (int i = 0; i < 3; i++) {
        classDef.declareField(EnumSet.of(Access.PRIVATE), "col" + i, ParameterizedType.type(long.class));
    }
    // Build constructor.
    final MethodDefinition methodDef = classDef.declareConstructor(EnumSet.of(Access.PUBLIC));
    final Variable rnd = methodDef.getScope().declareVariable(Random.class, "rnd");
    BytecodeBlock body = methodDef.getBody().append(methodDef.getThis()).invokeConstructor(classDef.getSuperClass()).append(rnd.set(BytecodeExpressions.newInstance(Random.class)));
    for (int i = 0; i < 3; i++) {
        body.append(methodDef.getThis().setField("col" + i, rnd.invoke("nextLong", long.class).cast(long.class)));
    }
    body.ret();
    return ClassGenerator.classGenerator(Thread.currentThread().getContextClassLoader()).fakeLineNumbers(true).runAsmVerifier(true).dumpRawBytecode(true).defineClass(classDef, Object.class);
}
Also used : Generated(javax.annotation.processing.Generated) Variable(com.facebook.presto.bytecode.Variable) MethodDefinition(com.facebook.presto.bytecode.MethodDefinition) BytecodeBlock(com.facebook.presto.bytecode.BytecodeBlock) ClassDefinition(com.facebook.presto.bytecode.ClassDefinition)

Example 4 with Generated

use of javax.annotation.processing.Generated in project ignite-3 by apache.

the class RecordMarshallerTest method createGeneratedObjectClass.

/**
 * Generate class for test objects.
 *
 * @return Generated test object class.
 */
private Class<?> createGeneratedObjectClass() {
    final String packageName = getClass().getPackageName();
    final String className = "GeneratedTestObject";
    final ClassDefinition classDef = new ClassDefinition(EnumSet.of(Access.PUBLIC), packageName.replace('.', '/') + '/' + className, ParameterizedType.type(Object.class));
    classDef.declareAnnotation(Generated.class).setValue("value", getClass().getCanonicalName());
    classDef.declareField(EnumSet.of(Access.PRIVATE), "key", ParameterizedType.type(long.class));
    for (int i = 0; i < 3; i++) {
        classDef.declareField(EnumSet.of(Access.PRIVATE), "col" + i, ParameterizedType.type(long.class));
    }
    // Build constructor.
    final MethodDefinition methodDef = classDef.declareConstructor(EnumSet.of(Access.PUBLIC));
    final Variable rnd = methodDef.getScope().declareVariable(Random.class, "rnd");
    BytecodeBlock body = methodDef.getBody().append(methodDef.getThis()).invokeConstructor(classDef.getSuperClass()).append(rnd.set(BytecodeExpressions.newInstance(Random.class)));
    body.append(methodDef.getThis().setField("key", rnd.invoke("nextLong", long.class).cast(long.class)));
    for (int i = 0; i < 3; i++) {
        body.append(methodDef.getThis().setField("col" + i, rnd.invoke("nextLong", long.class).cast(long.class)));
    }
    body.ret();
    return ClassGenerator.classGenerator(Thread.currentThread().getContextClassLoader()).fakeLineNumbers(true).runAsmVerifier(true).dumpRawBytecode(true).defineClass(classDef, Object.class);
}
Also used : Generated(javax.annotation.processing.Generated) Variable(com.facebook.presto.bytecode.Variable) MethodDefinition(com.facebook.presto.bytecode.MethodDefinition) BytecodeBlock(com.facebook.presto.bytecode.BytecodeBlock) ClassDefinition(com.facebook.presto.bytecode.ClassDefinition)

Example 5 with Generated

use of javax.annotation.processing.Generated in project ignite-3 by apache.

the class SerializerBenchmarkTest method createGeneratedObjectClass.

/**
 * Generate class for test objects.
 *
 * @param maxFields Max class member fields.
 * @param fieldType Field type.
 * @return Generated test object class.
 */
private Class<?> createGeneratedObjectClass(int maxFields, Class<?> fieldType) {
    final String packageName = "org.apache.ignite.internal.benchmarks";
    final String className = "TestObject";
    final ClassDefinition classDef = new ClassDefinition(EnumSet.of(Access.PUBLIC), packageName.replace('.', '/') + '/' + className, ParameterizedType.type(Object.class));
    classDef.declareAnnotation(Generated.class).setValue("value", getClass().getCanonicalName());
    for (int i = 0; i < maxFields; i++) {
        classDef.declareField(EnumSet.of(Access.PRIVATE), "col" + i, ParameterizedType.type(fieldType));
    }
    // Build constructor.
    final MethodDefinition methodDef = classDef.declareConstructor(EnumSet.of(Access.PUBLIC));
    final Variable rnd = methodDef.getScope().declareVariable(Random.class, "rnd");
    final BytecodeBlock body = methodDef.getBody().append(methodDef.getThis()).invokeConstructor(classDef.getSuperClass()).append(rnd.set(BytecodeExpressions.newInstance(Random.class)));
    for (int i = 0; i < maxFields; i++) {
        body.append(methodDef.getThis().setField("col" + i, rnd.invoke("nextLong", long.class).cast(fieldType)));
    }
    body.ret();
    return ClassGenerator.classGenerator(AsmMarshallerGenerator.getClassLoader()).defineClass(classDef, Object.class);
}
Also used : Generated(javax.annotation.processing.Generated) Variable(com.facebook.presto.bytecode.Variable) MethodDefinition(com.facebook.presto.bytecode.MethodDefinition) BytecodeBlock(com.facebook.presto.bytecode.BytecodeBlock) ClassDefinition(com.facebook.presto.bytecode.ClassDefinition)

Aggregations

Generated (javax.annotation.processing.Generated)5 ClassDefinition (com.facebook.presto.bytecode.ClassDefinition)4 BytecodeBlock (com.facebook.presto.bytecode.BytecodeBlock)3 MethodDefinition (com.facebook.presto.bytecode.MethodDefinition)3 Variable (com.facebook.presto.bytecode.Variable)3 FieldDefinition (com.facebook.presto.bytecode.FieldDefinition)1 InstrumentationBuilder (com.palantir.tritium.annotations.internal.InstrumentationBuilder)1 InstrumentationFilter (com.palantir.tritium.api.event.InstrumentationFilter)1 InvocationContext (com.palantir.tritium.event.InvocationContext)1 InvocationEventHandler (com.palantir.tritium.event.InvocationEventHandler)1 TaggedMetricRegistry (com.palantir.tritium.metrics.registry.TaggedMetricRegistry)1 ParameterizedTypeName (com.squareup.javapoet.ParameterizedTypeName)1 TypeName (com.squareup.javapoet.TypeName)1 TypeSpec (com.squareup.javapoet.TypeSpec)1 TypeVariableName (com.squareup.javapoet.TypeVariableName)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 IdentityHashMap (java.util.IdentityHashMap)1 List (java.util.List)1 Element (javax.lang.model.element.Element)1