Java Code Examples for javax.annotation.processing.Filer

The following are top voted examples for showing how to use javax.annotation.processing.Filer. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: incubator-netbeans   File: AbstractServiceProviderProcessor.java   View source code 6 votes vote down vote up
private void writeServices() {
    for (Map.Entry<Filer,Map<String,SortedSet<ServiceLoaderLine>>> outputFiles : outputFilesByProcessor.entrySet()) {
        Filer filer = outputFiles.getKey();
        for (Map.Entry<String,SortedSet<ServiceLoaderLine>> entry : outputFiles.getValue().entrySet()) {
            try {
                FileObject out = filer.createResource(StandardLocation.CLASS_OUTPUT, "", entry.getKey(),
                        originatingElementsByProcessor.get(filer).get(entry.getKey()).toArray(new Element[0]));
                OutputStream os = out.openOutputStream();
                try {
                    PrintWriter w = new PrintWriter(new OutputStreamWriter(os, "UTF-8"));
                    for (ServiceLoaderLine line : entry.getValue()) {
                        line.write(w);
                    }
                    w.flush();
                    w.close();
                } finally {
                    os.close();
                }
            } catch (IOException x) {
                processingEnv.getMessager().printMessage(Kind.ERROR, "Failed to write to " + entry.getKey() + ": " + x.toString());
            }
        }
    }
}
 
Example 2
Project: Moco   File: MocoProcessor.java   View source code 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> typeElements, RoundEnvironment roundEnv) {
    if (typeElements.size() == 0) {
        return true;
    }

    for (TypeElement typeElement : typeElements) {
        for (Element element : roundEnv.getElementsAnnotatedWith(typeElement)) {
            T entity = element.getAnnotation(targetAnnotation());
            SourceGenerator generator = createGenerator(element, entity, roundEnv);
            Filer filer = super.processingEnv.getFiler();
            try {
                List<JavaFile> javaFile = generator.createJavaFile(element);
                for (JavaFile file : javaFile) {
                    file.writeTo(filer);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return false;
}
 
Example 3
Project: AnnotationProcessorStarter   File: AnnotatedClass.java   View source code 6 votes vote down vote up
public void writeInto(final Filer pFiler, final Messager pMessager) {
    // prepare generated class
    final GeneratedClass lGeneratedClass = new GeneratedClass(mEnclosingClass, mMethods);

    final TypeSpec lTypeSpecGeneratedClass = lGeneratedClass.buildTypeSpec();
    final String lPackageName = lGeneratedClass.packageName();

    // create generated class to a file
    try {
        JavaFile.builder(lPackageName, lTypeSpecGeneratedClass)
                .build()
                .writeTo(pFiler);
    } catch (IOException pE) {
        logError(pMessager, mEnclosingClass, "error while writing generated class");
    }
}
 
Example 4
Project: D-Router   File: RouterTableGenerator.java   View source code 6 votes vote down vote up
public void generateMappingTable(Filer filer) throws IOException {
    if (routerTable.isEmpty()) {
        return;
    }
    FieldSpec tableFieldSpec = FieldSpec.builder(Map.class, "routerTable")
            .addModifiers(Modifier.PRIVATE)
            .build();
    MethodSpec initTableMethodSpec = getInitTableMethodSpec();
    MethodSpec queryTableMethodSpec = getqueryTableMethodSpec();
    MethodSpec constructorMethodSpec = getconstructorMethodSpec(tableFieldSpec, initTableMethodSpec);
    MethodSpec addRouterMethodSpec = getAddRouterMethodSpec();
    TypeSpec routerTableClassTypeSpec = getRouterTableClassTypeSpec(tableFieldSpec, initTableMethodSpec, queryTableMethodSpec, constructorMethodSpec, addRouterMethodSpec);
    String packageName = Constants.GENERATED_PACKAGE_NAME;
    JavaFile javaFile = JavaFile.builder(packageName, routerTableClassTypeSpec).build();
    javaFile.writeTo(filer);
}
 
Example 5
Project: immu   File: ImmuCompilerTest.java   View source code 6 votes vote down vote up
@Test
public void write_withIOException() throws Exception {
  final ProcessingEnvironment env = mock(ProcessingEnvironment.class);
  final Messager messager = mock(Messager.class);
  final Filer filer = mock(Filer.class);

  when(env.getMessager()).thenReturn(messager);
  when(env.getFiler()).thenReturn(filer);

  compiler.init(env);

  final JavaFile javaFile = mock(JavaFile.class);
  doThrow(IOException.class).when(javaFile).writeTo(any(Filer.class));

  compiler.writeSource(javaFile);

  verify(messager, times(1)).printMessage(eq(Diagnostic.Kind.ERROR), any());
}
 
Example 6
Project: data-mediator   File: StaticLoaderGenerator.java   View source code 6 votes vote down vote up
public static boolean generateStaticCodeLoader(Filer filer, ProcessorPrinter pp){
    CodeBlock.Builder staticBuilder = CodeBlock.builder()
            //GlobalSetting.getgetDefault().setGsonVersion(xxx)
            .add("$T.getDefault().setGsonVersion($L);\n", ClassName.get(PKG_PROP, SN_GLOBAL_SETTING),
                    GlobalConfig.getInstance().getVersion());

    TypeSpec typeSpec = TypeSpec.classBuilder(SN_STATIC_LOADER)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addStaticBlock(staticBuilder.build())
            .addJavadoc(CodeBlock.of(DOC))
            .build();
    try {
        JavaFile javaFile = JavaFile.builder(PKG_DM_INTERNAL, typeSpec)
                .build();
       // System.out.println(javaFile.toString());
        javaFile.writeTo(filer);
    } catch (IOException e) {
        pp.error(TAG, "generateSharedProperties", Util.toString(e));
        return false;
    }
    return true;
}
 
Example 7
Project: data-mediator   File: SharedPropertiesNGenerator.java   View source code 6 votes vote down vote up
public static boolean generateSharedProperties(Collection<FieldData> fields,
                                               Elements elements, Filer filer, ProcessorPrinter pp){
    final ClassName cn_sp = ClassName.get(PKG_DM_INTERNAL, SIMPLE_NAME_SHARED_PROP);
    CodeBlock.Builder staticBuilder = CodeBlock.builder();
    for(FieldData fd : fields){
        staticBuilder.add("$T.putToCache($S, $S, $L);\n", cn_sp, fd.getTypeCompat().toString(),
                fd.getPropertyName(), fd.getComplexType());
    }
    String classSimpleName = SIMPLE_NAME_SHARED_PROP + "_" + findBestIndex(elements);
    TypeSpec typeSpec = TypeSpec.classBuilder(classSimpleName)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addStaticBlock(staticBuilder.build())
            .addJavadoc(CodeBlock.of(DOC))
            .build();

    try {
        JavaFile javaFile = JavaFile.builder(PKG_DM_INTERNAL, typeSpec)
                .build();
       // System.out.println(javaFile.toString());
        javaFile.writeTo(filer);
    } catch (IOException e) {
        pp.error(TAG, "generateSharedProperties", Util.toString(e));
        return false;
    }
    return true;
}
 
Example 8
Project: remoter   File: BindingManager.java   View source code 6 votes vote down vote up
/**
 * Initialize with the given details from the annotation processing enviornment
 */
public BindingManager(Elements elementUtils, Filer filer, Messager messager, Types typeUtils) {
    this.elementUtils = elementUtils;
    this.filer = filer;
    this.messager = messager;
    this.typeUtils = typeUtils;
    this.typeBuilderMap = new HashMap<>();

    stringTypeMirror = getType("java.lang.String");
    listTypeMirror = getType("java.util.List");
    mapTypeMirror = getType("java.util.Map");
    charSequenceTypeMirror = getType("java.lang.CharSequence");
    parcellableTypeMirror = getType("android.os.Parcelable");
    try {
        parcelClass = Class.forName("org.parceler.Parcel");
    } catch (ClassNotFoundException ignored) {
    }
}
 
Example 9
Project: fragment-creator   File: FragmentCreatorWriter.java   View source code 6 votes vote down vote up
public void write(Filer filer) throws IOException {
    FragmentCreatorBuilderGenerator fragmentCreatorBuilderGenerator =
            new FragmentCreatorBuilderGenerator(environment);
    FragmentCreatorReadGenerator fragmentCreatorReadGenerator = new FragmentCreatorReadGenerator(environment);

    TypeSpec.Builder classBuilder = createClassBuilder();

    classBuilder.addType(fragmentCreatorBuilderGenerator.create(model));
    classBuilder.addMethod(fragmentCreatorReadGenerator.createReadMethod(model));
    classBuilder.addMethod(fragmentCreatorBuilderGenerator.createBuilderNewBuilder(model, model.getArgsList()));

    TypeSpec outClass = classBuilder.build();
    JavaFile.builder(model.getPackageName(), outClass)
            .addFileComment("This file was generated by fragment-creator. Do not modify!")
            .build()
            .writeTo(filer);
}
 
Example 10
Project: vue-gwt   File: GenerationUtil.java   View source code 6 votes vote down vote up
public static void toJavaFile(Filer filer, Builder classBuilder, ClassName className,
    TypeElement... originatingElement)
{
    try
    {
        JavaFile javaFile =
            JavaFile.builder(className.packageName(), classBuilder.build()).build();

        JavaFileObject javaFileObject =
            filer.createSourceFile(className.reflectionName(), originatingElement);

        Writer writer = javaFileObject.openWriter();
        javaFile.writeTo(writer);
        writer.close();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}
 
Example 11
Project: pndaox   File: ResourceHelper.java   View source code 6 votes vote down vote up
public static void doWithOriAndPrintWriter(Filer filer, JavaFileManager.Location location, String relativePath, String filename, BiConsumer<String, PrintWriter> consumer){
    try {
        FileObject resource = filer.getResource(location, relativePath, filename);
        String data;
        try{
            CharSequence cs = resource.getCharContent(false);
            data = cs.toString();
            resource.delete();
        }catch (FileNotFoundException ignored){
            data = "";
        }
        resource = filer.createResource(location, relativePath, filename);

        try(OutputStream outputStream = resource.openOutputStream()){
            consumer.accept(data,new PrintWriter(outputStream));
        }
    } catch (IOException e) {
        note("do with resource file failed"+relativePath+filename+" Exception: " + e.toString());
    }
}
 
Example 12
Project: alchemy   File: SchemaSpec.java   View source code 6 votes vote down vote up
void brewJava(Filer filer) throws Exception {
    final TypeSpec.Builder spec = TypeSpec.classBuilder(mClassName)
            .addAnnotation(AnnotationSpec.builder(SuppressWarnings.class)
                    .addMember("value", "$S", "unchecked")
                    .build())
            .addSuperinterface(ClassName.get(SQLiteSchema.class))
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addField(makeTablesField())
            .addField(makeMigrationsField())
            .addField(makeVersionField())
            .addStaticBlock(makeStaticInit())
            .addMethod(makeInit())
            .addMethod(makeGetVersion())
            .addMethod(makeGetTable())
            .addMethod(makeGetAllTables())
            .addMethod(makeAddMigration())
            .addMethod(makeGetAllMigrations());
    JavaFile.builder(mClassName.packageName(), spec.build())
            .addFileComment("Generated code from Alchemy. Do not modify!")
            .skipJavaLangImports(true)
            .build()
            .writeTo(filer);
}
 
Example 13
Project: alchemy   File: TableSpec.java   View source code 6 votes vote down vote up
ClassName brewJava(Filer filer) throws Exception {
    final ClassName modelName = ClassName.get(mElement);
    final TypeSpec.Builder spec = TypeSpec.classBuilder(mClassName.simpleName())
            .addAnnotation(AnnotationSpec.builder(SuppressWarnings.class)
                    .addMember("value", "$S", "TryFinallyCanBeTryWithResources")
                    .build())
            .addModifiers(Modifier.FINAL)
            .superclass(ParameterizedTypeName.get(ClassName.bestGuess("alchemy.sqlite.AbstractTable"), modelName))
            .addField(makeEntryField())
            .addMethod(makeInit())
            .addMethod(makeGetEntry())
            .addMethod(makeCreate());
    if (!mEntrySpec.getRelationSpecs().isEmpty()) {
        spec.addMethod(makeOnInsert());
    }
    JavaFile.builder(mClassName.packageName(), spec.build())
            .addFileComment("Generated code from Alchemy. Do not modify!")
            .skipJavaLangImports(true)
            .build()
            .writeTo(filer);
    return mClassName;
}
 
Example 14
Project: alchemy   File: CompileGraph.java   View source code 6 votes vote down vote up
void brewJava(Filer filer) throws Exception {
    for (final EntrySpec entrySpec : mEntries.values()) {
        for (final RelationSpec relationSpec : entrySpec.getRelationSpecs()) {
            relationSpec.brewJava(filer);
        }
        entrySpec.brewJava(filer);
        entrySpec.getContractSpec().brewJava(filer);
    }
    for (final Map.Entry<String, Map<Element, TableSpec>> entry : mSchemas.entrySet()) {
        final SchemaSpec schemaSpec = new SchemaSpec(entry.getKey());
        for (final TableSpec tableSpec : entry.getValue().values()) {
            schemaSpec.putTable(tableSpec.getElement(), tableSpec.brewJava(filer));
        }
        schemaSpec.brewJava(filer);
    }
}
 
Example 15
Project: alchemy   File: ContractSpec.java   View source code 6 votes vote down vote up
void brewJava(Filer filer) throws Exception {
    final TypeSpec.Builder spec = TypeSpec.classBuilder(mClassName.simpleName())
            .addOriginatingElement(mElement)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL);
    for (final ColumnSpec columnSpec : mColumnSpecs) {
        final String columnName = CaseFormat.LOWER_UNDERSCORE
                .to(CaseFormat.UPPER_UNDERSCORE, columnSpec.getColumnName());
        spec.addField(FieldSpec.builder(String.class, columnName, Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
                .initializer("$S", columnSpec.getColumnName())
                .build());
    }
    spec.addMethod(MethodSpec.constructorBuilder()
            .addModifiers(Modifier.PRIVATE)
            .build());
    JavaFile.builder(mClassName.packageName(), spec.build())
            .addFileComment("Generated code from Alchemy. Do not modify!")
            .skipJavaLangImports(true)
            .build()
            .writeTo(filer);
}
 
Example 16
Project: alchemy   File: EntrySpec.java   View source code 6 votes vote down vote up
void brewJava(Filer filer) throws Exception {
    if (mPrimaryKey == null) {
        throw new IllegalStateException("No such field annotated with @PrimaryKey");
    }
    final ClassName modelName = ClassName.get(mElement);
    final TypeSpec.Builder spec = TypeSpec.classBuilder(mClassName.simpleName())
            .addOriginatingElement(mElement)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addSuperinterface(ParameterizedTypeName.get(ClassName.get(SQLiteEntry.class), modelName));
    for (final RelationSpec relationSpec : mRelationSpecs) {
        spec.addField(makeRelationField(relationSpec));
    }
    spec.addMethod(makeGetId());
    spec.addMethod(makeGetRelations());
    spec.addMethod(makeBind());
    spec.addMethod(makeMap());
    JavaFile.builder(mClassName.packageName(), spec.build())
            .addFileComment("Generated code from Alchemy. Do not modify!")
            .skipJavaLangImports(true)
            .build()
            .writeTo(filer);
}
 
Example 17
Project: wava   File: JavaFile.java   View source code 6 votes vote down vote up
/**
 * Writes this to {@code filer}.
 */
public void writeTo(Filer filer)
        throws IOException
{
    String fileName = packageName.isEmpty()
            ? typeSpec.name
            : packageName + "." + typeSpec.name;
    List<Element> originatingElements = typeSpec.originatingElements;
    JavaFileObject filerSourceFile = filer.createSourceFile(fileName,
            originatingElements.toArray(new Element[originatingElements.size()]));
    try (Writer writer = filerSourceFile.openWriter()) {
        writeTo(writer);
    }
    catch (Exception e) {
        try {
            filerSourceFile.delete();
        }
        catch (Exception ignored) {
        }
        throw e;
    }
}
 
Example 18
Project: AutoHttp   File: AutoHttpProcessor.java   View source code 6 votes vote down vote up
@Override protected Iterable<? extends ProcessingStep> initSteps() {
  Messager messager = processingEnv.getMessager();
  Types types = processingEnv.getTypeUtils();
  Elements elements = processingEnv.getElementUtils();
  Filer filer = processingEnv.getFiler();

  AutoHttpGenerator autoHttpGenerator =
      new AutoHttpGenerator(filer, elements, messager);
  AutoHttpValidator autoHttpValidator =
      new AutoHttpValidator();
  MethodValidator methodValidator =
      new MethodValidator();

  return ImmutableList.of(
      new AutoHttpProcessingStep(
          messager,
          autoHttpGenerator,
          autoHttpValidator,
          methodValidator)
  );
}
 
Example 19
Project: FastLayout   File: LayoutProcessor.java   View source code 6 votes vote down vote up
private File getProjectRoot() throws Exception {
    if (projectRoot == null) {
        Filer filer = processingEnv.getFiler();

        JavaFileObject dummySourceFile = filer.createSourceFile("dummy" + System.currentTimeMillis());

        String dummySourceFilePath = dummySourceFile.toUri().toString();

        if (dummySourceFilePath.startsWith("file:")) {
            if (!dummySourceFilePath.startsWith("file://")) {
                dummySourceFilePath = "file://" + dummySourceFilePath.substring("file:".length());
            }
        } else {
            dummySourceFilePath = "file://" + dummySourceFilePath;
        }

        URI cleanURI = new URI(dummySourceFilePath);

        File dummyFile = new File(cleanURI);

        projectRoot = dummyFile.getParentFile();
    }

    return projectRoot;
}
 
Example 20
Project: AndroidMVPHelper   File: JavaFile.java   View source code 6 votes vote down vote up
/** Writes this to {@code filer}. */
public void writeTo(Filer filer) throws IOException {
  String fileName = packageName.isEmpty()
      ? typeSpec.name
      : packageName + "." + typeSpec.name;
  List<Element> originatingElements = typeSpec.originatingElements;
  JavaFileObject filerSourceFile = filer.createSourceFile(fileName,
      originatingElements.toArray(new Element[originatingElements.size()]));
  try (Writer writer = filerSourceFile.openWriter()) {
    writeTo(writer);
  } catch (Exception e) {
    try {
      filerSourceFile.delete();
    } catch (Exception ignored) {
    }
    throw e;
  }
}
 
Example 21
Project: AndroidMVPHelper   File: JavaFile.java   View source code 6 votes vote down vote up
/** Writes this to {@code filer}. */
public void writeTo(Filer filer) throws IOException {
  String fileName = packageName.isEmpty()
      ? typeSpec.name
      : packageName + "." + typeSpec.name;
  List<Element> originatingElements = typeSpec.originatingElements;
  JavaFileObject filerSourceFile = filer.createSourceFile(fileName,
      originatingElements.toArray(new Element[originatingElements.size()]));
  try (Writer writer = filerSourceFile.openWriter()) {
    writeTo(writer);
  } catch (Exception e) {
    try {
      filerSourceFile.delete();
    } catch (Exception ignored) {
    }
    throw e;
  }
}
 
Example 22
Project: Etil   File: EtilMapperGenerator.java   View source code 6 votes vote down vote up
public void generateCode(Filer _filer) throws IOException {
    if (mSingleTableClasses.size() == 0) {
        return;
    }

    TypeSpec helloWorld = TypeSpec.classBuilder(CLASS_NAME)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addMethod(generateMapCursorToModelMethod())
            .addMethod(generateMapModelToContentValuesMethod())
            .addMethod(generateGetTableFromModelMethod())
            .addMethod(generateGetTableFromModelClassMethod())
            .addMethods(generateCursorToModelMethods())
            .addMethods(generateModelToContentValuesMethods())
            .build();

    JavaFile javaFile = JavaFile.builder("com.tractive.android.etil", helloWorld)
            .build();

    javaFile.writeTo(_filer);
}
 
Example 23
Project: sqlitemagic   File: StructureWriter.java   View source code 6 votes vote down vote up
public void write(@NonNull Filer filer) throws IOException {
  final TypeSpec.Builder classBuilder = classBuilder(className)
      .addModifiers(PUBLIC_FINAL)
      .superclass(ParameterizedTypeName.get(TABLE, structureElementTypeName))
      .addMethod(constructor())
      .addField(structureField())
      .addFields(columnFields(filer))
      .addMethod(aliasOverride())
      .addMethod(mapper());
  if (hasAnyPersistedComplexColumns && !isView) {
    classBuilder.addMethod(queryPartsAddOverride(METHOD_ADD_DEEP_QUERY_PARTS));
    if (isQueryPartNeededForShallowQuery) {
      classBuilder.addMethod(queryPartsAddOverride(METHOD_ADD_SHALLOW_QUERY_PARTS));
    }
  }
  if (isView) {
    classBuilder.addMethod(perfectSelectionOverride());
  }
  writeSource(filer, classBuilder.build());
}
 
Example 24
Project: sqlitemagic   File: ViewWriter.java   View source code 6 votes vote down vote up
public void writeSource(Filer filer, ViewElement viewElement) throws IOException {
  final boolean isFullQueryNeeded = !viewElement.isFullQuerySameAsShallow();
  final RetrieveMethodsBodyBuilder retrieveMethodsBodyBuilder = RetrieveMethodsBodyBuilder.create(viewElement);

  final TypeSpec.Builder daoClassBuilder = TypeSpec.classBuilder(getGeneratedDaoClassNameString(viewElement.getViewElement()))
      .addModifiers(CLASS_MODIFIERS)
      .addField(schemaConstant(viewElement))
      .addMethod(shallowObjectFromCursorPosition(viewElement, retrieveMethodsBodyBuilder));

  if (isFullQueryNeeded) {
    daoClassBuilder.addMethod(fullObjectFromCursorPosition(viewElement, retrieveMethodsBodyBuilder));
  }

  if (viewElement.isInterface()) {
    daoClassBuilder.addType(interfaceImplementation(viewElement));
  }

  WriterUtil.writeSource(filer, daoClassBuilder.build(), viewElement.getPackageName());

  StructureWriter.from(viewElement, environment).write(filer);
}
 
Example 25
Project: sqlitemagic   File: ColumnClassWriter.java   View source code 6 votes vote down vote up
public TypeSpec write(@NonNull Filer filer) throws IOException {
  final TypeSpec.Builder classBuilder = TypeSpec.classBuilder(className)
      .addModifiers(CLASS_MODIFIERS)
      .addTypeVariable(parentTableType)
      .addTypeVariable(nullabilityType)
      .superclass(superClass)
      .addMethod(constructor())
      .addMethod(toSqlArg())
      .addMethod(aliasOverride());
  if (transformerElement != null) {
    classBuilder.addMethod(cursorParserOverride(transformerElement))
        .addMethod(statementParserOverride(transformerElement));
  }
  if (unique) {
    classBuilder.addSuperinterface(ParameterizedTypeName.get(UNIQUE, nullabilityType));
  }
  final TypeSpec type = classBuilder.build();
  writeSource(filer, type);
  return type;
}
 
Example 26
Project: sqlitemagic   File: GenClassesManagerWriter.java   View source code 6 votes vote down vote up
public void writeSource(Environment environment, GenClassesManagerStep managerStep) throws IOException {
  if (!environment.getAllTableElements().isEmpty()) {
    Filer filer = environment.getFiler();
    TypeSpec.Builder classBuilder = TypeSpec.classBuilder(CLASS_NAME_GENERATED_CLASSES_MANAGER)
        .addModifiers(CLASS_MODIFIERS)
        .addMethod(databaseConfigurator(environment))
        .addMethod(databaseSchemaCreator(environment, managerStep))
        .addMethod(clearData(environment))
        .addMethod(nrOfTables(environment))
        .addMethod(dbVersion(environment))
        .addMethod(dbName(environment))
        .addMethod(columnForValue(environment, managerStep));
    WriterUtil.writeSource(filer, classBuilder.build(), PACKAGE_ROOT);
    persistLatestStructure(environment);
  }
}
 
Example 27
Project: sqlitemagic   File: ModelWriter.java   View source code 6 votes vote down vote up
public void writeSource(Filer filer, TableElement tableElement) throws IOException {
  final TypeName tableElementTypeName = tableElement.getTableElementTypeName();
  final EntityEnvironment entityEnvironment = new EntityEnvironment(tableElement, tableElementTypeName);
  final TypeSpec.Builder daoClassBuilder = TypeSpec.classBuilder(entityEnvironment.getDaoClassNameString())
      .addModifiers(CLASS_MODIFIERS);
  final TypeSpec.Builder handlerClassBuilder = TypeSpec.classBuilder(entityEnvironment.getHandlerClassNameString())
      .addModifiers(CLASS_MODIFIERS);

  for (ModelPartGenerator generator : modelPartGenerators) {
    generator.write(daoClassBuilder, handlerClassBuilder, entityEnvironment);
  }

  WriterUtil.writeSource(filer, daoClassBuilder.build(), tableElement.getPackageName());
  WriterUtil.writeSource(filer, handlerClassBuilder.build());

  ColumnClassWriter.from(tableElement, environment, false).write(filer);
  StructureWriter.from(entityEnvironment, environment).write(filer);
}
 
Example 28
Project: java-code-gen   File: Generator.java   View source code 6 votes vote down vote up
default void writeServiceNames(Class<?> serviceClass, Filer filer, List<String> generatedClassNames) throws IOException {
    String resourceFile = "META-INF/services/" + serviceClass.getName();
    FileObject existingFile = filer.getResource(StandardLocation.CLASS_OUTPUT, "", resourceFile);
    List<String> lines = new ArrayList<>();
    try (Reader reader = existingFile.openReader(false)) {
        try (BufferedReader bufferedReader = new BufferedReader(reader)) {
            lines.addAll(bufferedReader.lines().collect(Collectors.toList()));
        }
    } catch (IOException e) {
        // Just ignore because reading from a non-existing file and there is no way to detect its existence
        // than open the input stream/reader.
    }

    lines.addAll(generatedClassNames);

    FileObject newFile = filer.createResource(StandardLocation.CLASS_OUTPUT, "", resourceFile);
    try (Writer writer = newFile.openWriter()) {
        try (BufferedWriter bufferedWriter = new BufferedWriter(writer)) {
            for (String line : lines) {
                bufferedWriter.write(line);
                bufferedWriter.newLine();
            }
        }
    }
}
 
Example 29
Project: java-code-gen   File: BeanGenerator.java   View source code 6 votes vote down vote up
@Override
public void generate(TypeElement clazz, Filer filer) throws IOException {
    if (clazz.getKind() != ElementKind.INTERFACE) {
        throw new GeneratorException(clazz, "Should be an interface");
    }
    Bean annotation = clazz.getAnnotation(Bean.class);
    PackageElement packageElem = Models.getPackage(clazz);
    String packageName = packageElem.getQualifiedName().toString();
    String simpleName = clazz.getSimpleName().toString();
    String beanName = simpleName + "Bean";
    String beanFullName = packageName + "." + beanName;
    TypeName beanTypeName = ClassName.get(packageName, beanName);
    String builderName = simpleName + "Builder";
    ClassName builderClassName = ClassName.get(packageName, builderName);
    String extractorName = simpleName + "PropNameExtractor";
    BeanInfo info = BeanInfo.fromType(clazz, models);
    boolean shouldHaveNonDefaultConstructor = info.shouldHaveNonDefaultConstructor();

    JavaFile.builder(packageName, genBean(info, beanName, shouldHaveNonDefaultConstructor, builderClassName)).build().writeTo(filer);
    JavaFile.builder(packageName, genBuilder(info, ClassName.get(packageName, builderName), builderName, beanTypeName, beanFullName)).build().writeTo(filer);
    if (annotation.propNameExtractor()) {
        JavaFile.builder(packageName, getPropNameExtractor(info, extractorName)).build().writeTo(filer);
    }
}
 
Example 30
Project: ocelot   File: FileWriterServicesTest.java   View source code 6 votes vote down vote up
/**
 * Test of getFileObjectWriterInClassOutput method, of class FileWriterServices.
 * @throws java.lang.Exception
 */
@Test
public void testGetFileObjectWriterInClassOutput() throws Exception {
	System.out.println("getFileObjectWriterInClassOutput");
	String pkg = "PKG";
	String name= "NAME";
	FileObject fileObject = mock(FileObject.class);
	Messager messager = mock(Messager.class);
	Filer filer = mock(Filer.class);
	Writer writer = mock(Writer.class);
	BodyWriter bodyWriter = mock(BodyWriter.class);
	FileWriterServices instance = spy(new FileWriterServices(messager, filer));
	instance.bodyWriter = bodyWriter;

	when(filer.createResource(eq(StandardLocation.CLASS_OUTPUT), eq(pkg), eq(name))).thenReturn(fileObject);
	when(fileObject.openWriter()).thenReturn(writer);
	Writer result = instance.getFileObjectWriterInClassOutput(pkg, name);
	assertThat(result).isEqualTo(writer);
}
 
Example 31
Project: Akatsuki   File: RetainedStateModel.java   View source code 6 votes vote down vote up
@Override
public void writeToFile(Filer filer) throws IOException {
	if (!config.enabled()) {
		Log.verbose(context,
				"@Retained disabled for class " + classModel().asClassInfo() + ", skipping...");
		return;
	}
	BundleRetainerClassBuilder builder = new BundleRetainerClassBuilder(context, classModel(),
			EnumSet.allOf(Direction.class), CLASS_INFO_FUNCTION, CLASS_INFO_FUNCTION);

	builder.withFieldPredicate(this);
	builder.withAnalysisTransformation(this);

	JavaFile javaFile = JavaFile
			.builder(info.fullyQualifiedPackageName, builder.build().build()).build();
	javaFile.writeTo(filer);
}
 
Example 32
Project: HawleyRetainer   File: HawleyRetainerDentist.java   View source code 6 votes vote down vote up
public void writeToFiler(Filer filer) throws IOException {
    final ClassName targetClassName = ClassName.get(mClassPackage, mClassTarget);

    final TypeSpec.Builder builder = TypeSpec.classBuilder(mClassName)
            .addModifiers(Modifier.PUBLIC)
            .addTypeVariable(TypeVariableName.get("T", targetClassName))
            .addMethod(generateRestoreRetainedObjectMapMethod())
            .addMethod(generateSaveRetainedObjectMapMethod());

    if (mClassParent != null) {
        builder.superclass(ParameterizedTypeName.get(ClassName.bestGuess(mClassParent), TypeVariableName.get("T")));
    } else {
        builder.superclass(ParameterizedTypeName.get(ClassName.get(Retainer.Object.class), TypeVariableName.get("T")));
    }

    final JavaFile retainerFile = JavaFile.builder(mClassPackage, builder.build()).build();

    retainerFile.writeTo(filer);
}
 
Example 33
Project: barber   File: Barbershop.java   View source code 6 votes vote down vote up
/**
 * Generates the class code and writes to a new source file.
 *
 * @param filer Annotation filer instance provided by {@link BarberProcessor}
 * @throws IOException
 */
void writeToFiler(Filer filer) throws IOException {
    ClassName targetClassName = ClassName.get(classPackage, targetClass);
    TypeSpec.Builder barberShop = TypeSpec.classBuilder(className)
            .addModifiers(Modifier.PUBLIC)
            .addTypeVariable(TypeVariableName.get("T", targetClassName))
            .addMethod(generateStyleMethod())
            .addMethod(generateCheckParentMethod());

    if (parentBarbershop == null) {
        barberShop.addSuperinterface(ParameterizedTypeName.get(ClassName.get(Barber.IBarbershop.class), TypeVariableName.get("T")));
        barberShop.addField(FieldSpec.builder(WeakHashSet.class, "lastStyledTargets", Modifier.PROTECTED).initializer("new $T()", WeakHashSet.class).build());
    } else {
        barberShop.superclass(ParameterizedTypeName.get(ClassName.bestGuess(parentBarbershop), TypeVariableName.get("T")));
    }

    JavaFile javaFile = JavaFile.builder(classPackage, barberShop.build()).build();
    javaFile.writeTo(filer);
}
 
Example 34
Project: Postman   File: PostmenEnabledCollectedClassWriter.java   View source code 6 votes vote down vote up
@Override
public void writeToFile(@NonNull Elements elements, @NonNull Filer filer) throws IOException {
    Element classElement = mCollectedClass.getClassElement();
    String typeNameAsString = getTypeNameAsString(classElement);
    TypeName typeName = TypeVariableName.get(typeNameAsString);
    List<CollectedField> fields = mCollectedClass.getFields();
    TypeSpec.Builder classBuilder = TypeSpec.classBuilder(asFileName(typeNameAsString) + "$$Postman")
            .addModifiers(PUBLIC, FINAL);
    classBuilder.superclass(ParameterizedTypeName.get(BASE_PARCELER, typeName));

    // Generate parcel method
    classBuilder.addMethod(createShipMethodSpec(typeName, fields));
    // Generate unparcel method
    classBuilder.addMethod(createReceiveMethodSpec(typeName, fields));

    String packageName = elements.getPackageOf(classElement).getQualifiedName().toString();
    JavaFile javaFile = JavaFile.builder(packageName, classBuilder.build())
            .addFileComment("Generated code from Postman. Do not modify!")
            .build();
    javaFile.writeTo(filer);
}
 
Example 35
Project: bridje-framework   File: ControlProcessor.java   View source code 6 votes vote down vote up
@Override
public synchronized void init(ProcessingEnvironment processingEnv)
{
    //Creating necesary objects for annotations procesing.
    super.init(processingEnv);
    Messager messager = processingEnv.getMessager();
    try
    {
        Filer filer = processingEnv.getFiler();
        //Creating output file
        FileObject fobj = filer.createResource(StandardLocation.CLASS_OUTPUT, "", CONTROLS_RESOURCE_FILE);
        writer = fobj.openWriter();
    }
    catch (IOException e)
    {
        messager.printMessage(Diagnostic.Kind.ERROR, e.getMessage());
        LOG.severe(e.getMessage());
    }
}
 
Example 36
Project: bridje-framework   File: ClassListPropertyFile.java   View source code 6 votes vote down vote up
@Override
public synchronized void init(ProcessingEnvironment processingEnv)
{
    //Creating necessary objects for annotations processing.
    super.init(processingEnv);
    Messager messager = processingEnv.getMessager();
    try
    {
        Filer filer = processingEnv.getFiler();
        //Creating output file
        FileObject fobj = filer.createResource(StandardLocation.CLASS_OUTPUT, "", getFileName());
        writer = fobj.openWriter();
    }
    catch (IOException e)
    {
        messager.printMessage(Diagnostic.Kind.ERROR, e.getMessage());
        LOG.severe(e.getMessage());
    }
}
 
Example 37
Project: Kinject   File: CodeGen.java   View source code 6 votes vote down vote up
private static void writeClassFile(String packageName, TypeSpec classSpec, Filer filer) throws ProcessorException {
	try {
		AnnotationSpec generatedAnnotation = AnnotationSpec.builder(Generated.class)
			.addMember("value", "$S", CODE_GEN)
			.build();
		classSpec = classSpec.toBuilder()
			.addAnnotation(generatedAnnotation)
			.build();
		JavaFile javaFile = JavaFile.builder(packageName, classSpec)
			.skipJavaLangImports(true)
			.build();
		javaFile.writeTo(filer);
	} catch (IOException e) {
		throw new ProcessorException("Cannot generate code file %s.%s.", packageName, classSpec.name);
	}
}
 
Example 38
Project: auto-parse   File: EclipseHack.java   View source code 6 votes vote down vote up
EclipseIFile(ProcessingEnvironment processingEnv, TypeElement element) {
  Filer filer = processingEnv.getFiler();
  // walk up the enclosing elements until you find a top-level element
  Element topLevel = element;
  while (topLevel.getEnclosingElement().getKind() != ElementKind.PACKAGE) {
    topLevel = topLevel.getEnclosingElement();
  }
  try {
    FileObject resource = filer.getResource(StandardLocation.SOURCE_PATH,
        processingEnv.getElementUtils().getPackageOf(element).getQualifiedName(),
        topLevel.getSimpleName() + ".java");
    this.file = new File(resource.toUri());
    if (!file.canRead()) {
      processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
          "Cannot find source code in file " + file, element);
    }
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 39
Project: ocelot   File: FileWriterServicesTest.java   View source code 6 votes vote down vote up
/**
 * Test of copyFileToClassesOutput method, of class FileWriterServices.
 * @throws java.io.IOException
 */
@Test
public void testCopyFileToClassesOutput() throws IOException {
	System.out.println("copyFileToClassesOutput");
	String path = "";
	String filename = "test.js";
	Messager messager = mock(Messager.class);
	Filer filer = mock(Filer.class);
	Writer writer = mock(Writer.class);
	BodyWriter bodyWriter = mock(BodyWriter.class);
	FileWriterServices instance = spy(new FileWriterServices(messager, filer));
	instance.bodyWriter = bodyWriter;

	doReturn(writer).doThrow(IOException.class).when(instance).getFileObjectWriterInClassOutput(eq(""), eq(filename));

	instance.copyResourceToClassesOutput(path, filename);
	instance.copyResourceToClassesOutput(path, filename);
	verify(bodyWriter).write(eq(writer), any(InputStream.class));
}
 
Example 40
Project: form-follows-function   File: T6413690.java   View source code 6 votes vote down vote up
public boolean process(Set<? extends TypeElement> annotations,
                       RoundEnvironment roundEnvironment) {
    Elements elements = processingEnv.getElementUtils();
    Filer filer = processingEnv.getFiler();
    TypeElement testMe = elements.getTypeElement(TestMe.class.getName());
    Set<? extends Element> supers = roundEnvironment.getElementsAnnotatedWith(testMe);
    try {
        for (Element sup : supers) {
            Writer sub = filer.createSourceFile(sup.getSimpleName() + "_GENERATED").openWriter();
            sub.write(String.format("class %s_GENERATED extends %s {}",
                                    sup.getSimpleName(),
                                    ((TypeElement)sup).getQualifiedName()));
            sub.close();
        }
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
    return true;
}