Search in sources :

Example 91 with PackageElement

use of javax.lang.model.element.PackageElement in project graal by oracle.

the class InstrumentableProcessor method generateFactory.

@SuppressWarnings("deprecation")
private static CodeTypeElement generateFactory(ProcessorContext context, Element e, CodeTypeElement wrapper) {
    TypeElement sourceType = (TypeElement) e;
    PackageElement pack = context.getEnvironment().getElementUtils().getPackageOf(sourceType);
    Set<Modifier> typeModifiers = ElementUtils.modifiers(Modifier.PUBLIC, Modifier.FINAL);
    CodeTypeElement factory = new CodeTypeElement(typeModifiers, ElementKind.CLASS, pack, createWrapperClassName(sourceType));
    TypeMirror factoryType = context.reloadType(context.getType(com.oracle.truffle.api.instrumentation.InstrumentableFactory.class));
    factory.getImplements().add(new CodeTypeMirror.DeclaredCodeTypeMirror(ElementUtils.fromTypeMirror(factoryType), Arrays.asList(sourceType.asType())));
    addGeneratedBy(context, factory, sourceType);
    TypeMirror returnType = context.getType(com.oracle.truffle.api.instrumentation.InstrumentableFactory.WrapperNode.class);
    CodeExecutableElement createMethod = new CodeExecutableElement(ElementUtils.modifiers(Modifier.PUBLIC), returnType, "createWrapper");
    createMethod.addParameter(new CodeVariableElement(sourceType.asType(), FIELD_DELEGATE));
    createMethod.addParameter(new CodeVariableElement(context.getType(ProbeNode.class), FIELD_PROBE));
    CodeTreeBuilder builder = createMethod.createBuilder();
    ExecutableElement constructor = ElementFilter.constructorsIn(wrapper.getEnclosedElements()).iterator().next();
    String firstParameterReference = null;
    if (constructor.getParameters().size() > 2) {
        TypeMirror firstParameter = constructor.getParameters().get(0).asType();
        if (ElementUtils.typeEquals(firstParameter, sourceType.asType())) {
            firstParameterReference = FIELD_DELEGATE;
        } else if (ElementUtils.typeEquals(firstParameter, context.getType(SourceSection.class))) {
            firstParameterReference = FIELD_DELEGATE + ".getSourceSection()";
        }
    }
    builder.startReturn().startNew(wrapper.asType());
    if (firstParameterReference != null) {
        builder.string(firstParameterReference);
    }
    builder.string(FIELD_DELEGATE).string(FIELD_PROBE);
    builder.end().end();
    factory.add(createMethod);
    return factory;
}
Also used : CodeTypeMirror(com.oracle.truffle.dsl.processor.java.model.CodeTypeMirror) CodeExecutableElement(com.oracle.truffle.dsl.processor.java.model.CodeExecutableElement) TypeElement(javax.lang.model.element.TypeElement) CodeTypeElement(com.oracle.truffle.dsl.processor.java.model.CodeTypeElement) CodeExecutableElement(com.oracle.truffle.dsl.processor.java.model.CodeExecutableElement) ExecutableElement(javax.lang.model.element.ExecutableElement) CodeTypeElement(com.oracle.truffle.dsl.processor.java.model.CodeTypeElement) CodeTypeMirror(com.oracle.truffle.dsl.processor.java.model.CodeTypeMirror) TypeMirror(javax.lang.model.type.TypeMirror) CodeVariableElement(com.oracle.truffle.dsl.processor.java.model.CodeVariableElement) PackageElement(javax.lang.model.element.PackageElement) Modifier(javax.lang.model.element.Modifier) CodeTreeBuilder(com.oracle.truffle.dsl.processor.java.model.CodeTreeBuilder)

Example 92 with PackageElement

use of javax.lang.model.element.PackageElement in project graal by oracle.

the class PluginGenerator method createPluginFactory.

private static void createPluginFactory(ProcessingEnvironment env, Element topLevelClass, List<GeneratedPlugin> plugins) {
    PackageElement pkg = (PackageElement) topLevelClass.getEnclosingElement();
    String genClassName = "PluginFactory_" + topLevelClass.getSimpleName();
    try {
        JavaFileObject factory = env.getFiler().createSourceFile(pkg.getQualifiedName() + "." + genClassName, topLevelClass);
        try (PrintWriter out = new PrintWriter(factory.openWriter())) {
            out.printf("// CheckStyle: stop header check\n");
            out.printf("// CheckStyle: stop line length check\n");
            out.printf("// GENERATED CONTENT - DO NOT EDIT\n");
            out.printf("// GENERATORS: %s, %s\n", VerifierAnnotationProcessor.class.getName(), PluginGenerator.class.getName());
            out.printf("package %s;\n", pkg.getQualifiedName());
            out.printf("\n");
            createImports(out, plugins);
            out.printf("\n");
            out.printf("@ServiceProvider(NodeIntrinsicPluginFactory.class)\n");
            out.printf("public class %s implements NodeIntrinsicPluginFactory {\n", genClassName);
            for (GeneratedPlugin plugin : plugins) {
                out.printf("\n");
                plugin.generate(env, out);
            }
            out.printf("\n");
            createPluginFactoryMethod(out, plugins);
            out.printf("}\n");
        }
    } catch (IOException e) {
        env.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getMessage());
    }
}
Also used : JavaFileObject(javax.tools.JavaFileObject) PackageElement(javax.lang.model.element.PackageElement) IOException(java.io.IOException) PrintWriter(java.io.PrintWriter)

Example 93 with PackageElement

use of javax.lang.model.element.PackageElement in project kripton by xcesco.

the class BindTypeBuilder method generate.

/**
 * @return typeName of generated class
 *
 * @throws IOException
 */
public static String generate(Filer filer, BindEntity item) throws IOException {
    Elements elementUtils = BaseProcessor.elementUtils;
    String beanClassName = item.getSimpleName().toString();
    boolean needSuffix = true;
    if (beanClassName.endsWith(SUFFIX)) {
        needSuffix = false;
    }
    String className = PREFIX + beanClassName + (needSuffix ? SUFFIX : "");
    PackageElement pkg = elementUtils.getPackageOf(item.getElement());
    String packageName = pkg.isUnnamed() ? "" : pkg.getQualifiedName().toString();
    AnnotationProcessorUtilis.infoOnGeneratedClasses(BindType.class, packageName, className);
    // @formatter:off
    TypeSpec.Builder builder = TypeSpec.classBuilder(className).addAnnotation(AnnotationSpec.builder(BindMap.class).addMember("value", "$T.class", typeName(item.getElement().asType())).build()).addModifiers(Modifier.PUBLIC).superclass(TypeUtility.parameterizedTypeName(className(AbstractMapper.class), typeName(item.getElement().asType())));
    BindTypeContext context = new BindTypeContext(builder, TypeUtility.typeName(packageName, className), Modifier.PRIVATE);
    // @formatter:on
    builder.addJavadoc("This class is binder map for $T\n\n", item.getElement());
    JavadocUtility.generateJavadocGeneratedBy(builder);
    builder.addJavadoc("@see $T\n", item.getElement());
    // order item by order, property typeName
    Collections.sort(item.getCollection(), new Comparator<BindProperty>() {

        @Override
        public int compare(BindProperty lhs, BindProperty rhs) {
            int c1 = lhs.order - rhs.order;
            if (c1 != 0)
                return c1;
            return lhs.getName().compareTo(rhs.getName());
        }
    });
    // generate serializeOnJackson
    generateSerializeOnJackson(context, item);
    // generate serializeOnJacksonAsString
    generateSerializeOnJacksonAsString(context, item);
    // order item by type (attribute, element, value), order, xmlName
    Collections.sort(item.getCollection(), new Comparator<BindProperty>() {

        @Override
        public int compare(BindProperty lhs, BindProperty rhs) {
            int c1 = lhs.xmlInfo.xmlType.ordinal() - rhs.xmlInfo.xmlType.ordinal();
            if (c1 != 0)
                return c1;
            c1 = lhs.order - rhs.order;
            if (c1 != 0)
                return c1;
            return lhs.label.compareTo(rhs.label);
        }
    });
    // generate serializeOnXml
    generateSerializeOnXml(context, item);
    // generate parseOnJackson
    generateParseOnJackson(context, item);
    // generate parseOnJacksonAsString
    generateParseOnJacksonAsString(context, item);
    // generate parseOnXml
    generateParseOnXml(context, item);
    TypeSpec typeSpec = builder.build();
    JavaWriterHelper.writeJava2File(filer, packageName, typeSpec);
    return className;
}
Also used : PackageElement(javax.lang.model.element.PackageElement) BindMap(com.abubusoft.kripton.annotation.BindMap) Elements(javax.lang.model.util.Elements) BindProperty(com.abubusoft.kripton.processor.bind.model.BindProperty) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 94 with PackageElement

use of javax.lang.model.element.PackageElement in project kripton by xcesco.

the class BindContentProviderBuilder method build.

public void build(Elements elementUtils, Filer filer, SQLiteDatabaseSchema schema) throws Exception {
    uriSet.clear();
    String dataSourceName = schema.getName();
    String dataSourceNameClazz = BindDataSourceBuilder.PREFIX + dataSourceName;
    String contentProviderName = PREFIX + dataSourceName.replace(BindDataSourceBuilder.SUFFIX, "") + SUFFIX;
    PackageElement pkg = elementUtils.getPackageOf(schema.getElement());
    String packageName = pkg.isUnnamed() ? null : pkg.getQualifiedName().toString();
    AnnotationProcessorUtilis.infoOnGeneratedClasses(BindContentProvider.class, packageName, contentProviderName);
    classBuilder = TypeSpec.classBuilder(contentProviderName).addModifiers(Modifier.PUBLIC).superclass(ContentProvider.class);
    classBuilder.addJavadoc("<p>This is the content provider generated for {@link $L}</p>\n\n", dataSourceName);
    classBuilder.addJavadoc("<h2>Content provider authority:</h2>\n");
    classBuilder.addJavadoc("<pre>$L</pre>\n\n", schema.contentProvider.authority);
    generateOnCreate(dataSourceNameClazz);
    generateOnShutdown(dataSourceNameClazz);
    // define static fields
    classBuilder.addField(FieldSpec.builder(String.class, "URI", Modifier.STATIC, Modifier.PUBLIC, Modifier.FINAL).initializer("$S", schema.contentProviderUri()).addJavadoc("<p>content provider's URI.</p>\n<pre>$L</pre>\n", schema.contentProviderUri()).build());
    // instance
    classBuilder.addField(FieldSpec.builder(className(dataSourceNameClazz), "dataSource", Modifier.PRIVATE, Modifier.STATIC).addJavadoc("<p>datasource singleton</p>\n").build());
    classBuilder.addField(FieldSpec.builder(String.class, "AUTHORITY", Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL).addJavadoc("<p>Content provider authority</p>\n").initializer("$S", schema.contentProvider.authority).build());
    classBuilder.addField(FieldSpec.builder(UriMatcher.class, "sURIMatcher", Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL).addJavadoc("<p>URI matcher</p>\n").initializer("new $T($T.NO_MATCH)", UriMatcher.class, UriMatcher.class).build());
    Builder staticBuilder = CodeBlock.builder();
    Converter<String, String> daoConstantConverter = CaseFormat.UPPER_CAMEL.converterTo(CaseFormat.UPPER_UNDERSCORE);
    List<FieldSpec> listFieldUri = new ArrayList<>();
    List<FieldSpec> listFieldString = new ArrayList<>();
    List<FieldSpec> listFieldIndex = new ArrayList<>();
    List<FieldSpec> listFieldAlias = new ArrayList<>();
    for (SQLiteDaoDefinition daoDefinition : schema.getCollection()) {
        String pathConstantName = "PATH_" + daoConstantConverter.convert(daoDefinition.getEntitySimplyClassName());
        if (!daoDefinition.contentProviderEnabled)
            continue;
        // define content provider paths
        for (SQLiteModelMethod daoMethod : daoDefinition.getCollection()) {
            if (!daoMethod.contentProviderEntryPathEnabled)
                continue;
            ContentEntry entry = uriSet.get(daoMethod.contentProviderEntryPathTemplate);
            if (entry == null) {
                entry = new ContentEntry(daoMethod.contentProviderEntryPath);
                uriSet.put(daoMethod.contentProviderEntryPathTemplate, entry);
                entry.path = daoMethod.contentProviderEntryPath;
                entry.uriTemplate = daoMethod.contentProviderEntryPathTemplate;
                // we finish later
                entry.pathCostant = pathConstantName;
                entry.pathIndex = pathConstantName;
            }
            switch(daoMethod.jql.operationType) {
                case INSERT:
                    AssertKripton.fail(entry.insert != null, String.format("In DAO %s, there are more than one %s statement associated to content provider path '%s'", daoDefinition.getName().toString(), daoMethod.jql.operationType, entry.path));
                    entry.insert = daoMethod;
                    break;
                case UPDATE:
                    AssertKripton.fail(entry.update != null, String.format("In DAO %s, there are more than one %s statement associated to content provider path '%s'", daoDefinition.getName().toString(), daoMethod.jql.operationType, entry.path));
                    entry.update = daoMethod;
                    break;
                case SELECT:
                    AssertKripton.fail(entry.select != null, String.format("In DAO %s, there are more than one %s statement associated to content provider path '%s'", daoDefinition.getName().toString(), daoMethod.jql.operationType, entry.path));
                    entry.select = daoMethod;
                    break;
                case DELETE:
                    AssertKripton.fail(entry.delete != null, String.format("In DAO %s, there are more than one %s statement associated to content provider path '%s'", daoDefinition.getName().toString(), daoMethod.jql.operationType, entry.path));
                    entry.delete = daoMethod;
                    break;
            }
        }
    }
    // sort uri set by
    List<Pair<String, ContentEntry>> listUriSet = new ArrayList<>();
    Pair<String, ContentEntry> item;
    for (Entry<String, ContentEntry> entry : uriSet.entrySet()) {
        item = new Pair<String, ContentEntry>(entry.getKey(), entry.getValue());
        listUriSet.add(item);
    }
    Comparator<Pair<String, ContentEntry>> c = new Comparator<Pair<String, ContentEntry>>() {

        @Override
        public int compare(Pair<String, ContentEntry> lhs, Pair<String, ContentEntry> rhs) {
            return lhs.value0.compareTo(rhs.value0);
        }
    };
    Collections.sort(listUriSet, c);
    Set<String> alreadyUsedName = new HashSet<String>();
    Converter<String, String> format = CaseFormat.LOWER_CAMEL.converterTo(CaseFormat.UPPER_UNDERSCORE);
    int i = 1;
    for (Pair<String, ContentEntry> entry : listUriSet) {
        // define ordered part of attributes (after sort)
        entry.value1.pathCostant += "_" + i;
        entry.value1.pathIndex += "_" + i + "_INDEX";
        entry.value1.pathValue = i;
        // build class attributes
        listFieldString.add(FieldSpec.builder(String.class, entry.value1.pathCostant, Modifier.STATIC, Modifier.FINAL).initializer(CodeBlock.of("$S", entry.value1.uriTemplate)).build());
        listFieldIndex.add(FieldSpec.builder(Integer.TYPE, entry.value1.pathIndex, Modifier.STATIC, Modifier.FINAL).initializer(CodeBlock.of("$L", entry.value1.pathValue)).build());
        listFieldUri.add(FieldSpec.builder(Uri.class, "URI_" + entry.value1.pathCostant, Modifier.STATIC, Modifier.FINAL, Modifier.PRIVATE).addJavadoc("<p>Uri</p>\n").addJavadoc("<pre>$L/$L</pre>\n", schema.contentProviderUri().replace("*", "[*]"), entry.value1.uriTemplate.replace("*", "[*]")).initializer(CodeBlock.of("Uri.parse(URI+\"/$L\")", entry.value1.uriTemplate)).build());
        generateURIForMethod(schema, listFieldAlias, alreadyUsedName, format, entry, entry.value1.delete);
        generateURIForMethod(schema, listFieldAlias, alreadyUsedName, format, entry, entry.value1.insert);
        generateURIForMethod(schema, listFieldAlias, alreadyUsedName, format, entry, entry.value1.select);
        generateURIForMethod(schema, listFieldAlias, alreadyUsedName, format, entry, entry.value1.update);
        staticBuilder.addStatement("sURIMatcher.addURI(AUTHORITY, $L, $L)", entry.value1.pathCostant, entry.value1.pathIndex);
        i++;
    }
    for (FieldSpec f : listFieldUri) {
        classBuilder.addField(f);
    }
    for (FieldSpec f : listFieldString) {
        classBuilder.addField(f);
    }
    for (FieldSpec f : listFieldIndex) {
        classBuilder.addField(f);
    }
    for (FieldSpec f : listFieldAlias) {
        classBuilder.addField(f);
    }
    classBuilder.addStaticBlock(staticBuilder.build());
    generateQuery(schema);
    generateInsert(schema);
    generateUpdate(schema);
    generateDelete(schema);
    generateGetType(schema);
    TypeSpec typeSpec = classBuilder.build();
    JavaWriterHelper.writeJava2File(filer, packageName, typeSpec);
}
Also used : ContentProvider(android.content.ContentProvider) BindContentProvider(com.abubusoft.kripton.android.annotation.BindContentProvider) Builder(com.squareup.javapoet.CodeBlock.Builder) ArrayList(java.util.ArrayList) Uri(android.net.Uri) FieldSpec(com.squareup.javapoet.FieldSpec) SQLiteDaoDefinition(com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition) Comparator(java.util.Comparator) SQLiteModelMethod(com.abubusoft.kripton.processor.sqlite.model.SQLiteModelMethod) PackageElement(javax.lang.model.element.PackageElement) Pair(com.abubusoft.kripton.common.Pair) HashSet(java.util.HashSet) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 95 with PackageElement

use of javax.lang.model.element.PackageElement in project kripton by xcesco.

the class BindDataSourceBuilder method generateDataSourceName.

/**
 * Generate dataSource name
 *
 * @param schema
 * @return associated class name
 */
public static ClassName generateDataSourceName(SQLiteDatabaseSchema schema) {
    String dataSourceName = schema.getName();
    dataSourceName = PREFIX + dataSourceName;
    PackageElement pkg = BaseProcessor.elementUtils.getPackageOf(schema.getElement());
    String packageName = pkg.isUnnamed() ? "" : pkg.getQualifiedName().toString();
    return ClassName.get(packageName, dataSourceName);
}
Also used : PackageElement(javax.lang.model.element.PackageElement)

Aggregations

PackageElement (javax.lang.model.element.PackageElement)134 TypeElement (javax.lang.model.element.TypeElement)93 Element (javax.lang.model.element.Element)52 ExecutableElement (javax.lang.model.element.ExecutableElement)34 VariableElement (javax.lang.model.element.VariableElement)32 TypeSpec (com.squareup.javapoet.TypeSpec)20 IOException (java.io.IOException)17 HashSet (java.util.HashSet)13 TypeMirror (javax.lang.model.type.TypeMirror)13 AnnotationMirror (javax.lang.model.element.AnnotationMirror)12 JavaFileObject (javax.tools.JavaFileObject)12 ClassName (com.squareup.javapoet.ClassName)11 ArrayList (java.util.ArrayList)11 Set (java.util.Set)10 Elements (javax.lang.model.util.Elements)10 PrintWriter (java.io.PrintWriter)9 HashMap (java.util.HashMap)9 ParameterizedTypeName (com.squareup.javapoet.ParameterizedTypeName)8 Map (java.util.Map)8 Messager (javax.annotation.processing.Messager)8