javax.annotation.processing.Filer Java Examples

The following examples show how to use javax.annotation.processing.Filer. 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: SharedPropertiesNGenerator.java    From data-mediator with Apache License 2.0 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 #2
Source File: TurbineProcessingEnvironment.java    From turbine with Apache License 2.0 6 votes vote down vote up
public TurbineProcessingEnvironment(
    Filer filer,
    Types types,
    Elements elements,
    Messager messager,
    Map<String, String> processorOptions,
    SourceVersion sourceVersion,
    @Nullable ClassLoader processorLoader,
    Map<String, byte[]> statistics) {
  this.filer = filer;
  this.types = types;
  this.processorOptions = processorOptions;
  this.sourceVersion = sourceVersion;
  this.elements = elements;
  this.statistics = statistics;
  this.messager = messager;
  this.processorLoader = processorLoader;
}
 
Example #3
Source File: AnnotationProcessor.java    From buck with Apache License 2.0 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
  if (roundEnv.processingOver()) {
    Filer filer = processingEnv.getFiler();
    try {
      JavaFileObject sourceFile = filer.createSourceFile("com.example.buck.Test");
      try (OutputStream out = sourceFile.openOutputStream()) {
        out.write("package com.example.buck; class Test { }".getBytes());
      }
    } catch (IOException e) {
      throw new AssertionError(e);
    }
  }

  return false;
}
 
Example #4
Source File: StructureWriter.java    From sqlitemagic with Apache License 2.0 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 #5
Source File: LayoutProcessor.java    From FastLayout with Apache License 2.0 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 #6
Source File: ModelWriter.java    From sqlitemagic with Apache License 2.0 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 #7
Source File: ColumnClassWriter.java    From sqlitemagic with Apache License 2.0 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();
  final TypeElement typeElement = environment.getElementUtils().getTypeElement(PACKAGE_ROOT + "." + className);
  // write source only if there isn't already this type
  if (typeElement == null) {
    writeSource(filer, type);
  }
  return type;
}
 
Example #8
Source File: IncrementalAnnotationProcessorProcessor.java    From gradle-incap-helper with Apache License 2.0 6 votes vote down vote up
private void generateConfigFiles() {
  Filer filer = processingEnv.getFiler();
  try {
    // TODO: merge with an existing file (in case of incremental compilation, in a
    // non-incremental-compile-aware environment; e.g. Maven)
    FileObject fileObject =
        filer.createResource(StandardLocation.CLASS_OUTPUT, "", RESOURCE_FILE);
    try (PrintWriter out =
        new PrintWriter(
            new OutputStreamWriter(fileObject.openOutputStream(), StandardCharsets.UTF_8))) {
      processors.forEach((processor, type) -> out.println(processor + "," + type.name()));
      if (out.checkError()) {
        throw new IOException("Error writing to the file");
      }
    }
  } catch (IOException e) {
    fatalError("Unable to create " + RESOURCE_FILE + ", " + e);
  }
}
 
Example #9
Source File: EntrySpec.java    From alchemy with Apache License 2.0 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 #10
Source File: ContractSpec.java    From alchemy with Apache License 2.0 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 #11
Source File: PropNameInterStageStore.java    From litho with Apache License 2.0 6 votes vote down vote up
/**
 * Helper method for obtaining resources from a {@link Filer}, taking care of some javac
 * peculiarities.
 */
private static Optional<FileObject> getResource(
    final Filer filer,
    final JavaFileManager.Location location,
    final String packageName,
    final String filePath) {
  try {
    final FileObject resource = filer.getResource(location, packageName, filePath);
    resource.openInputStream().close();
    return Optional.of(resource);
  } catch (final Exception e) {
    // ClientCodeException can be thrown by a bug in the javac ClientCodeWrapper
    if (!(e instanceof FileNotFoundException
        || e.getClass().getName().equals("com.sun.tools.javac.util.ClientCodeException"))) {
      throw new RuntimeException(
          String.format("Error opening resource %s/%s", packageName, filePath), e.getCause());
    }
    return Optional.empty();
  }
}
 
Example #12
Source File: SchemaWriter.java    From kvs-schema with MIT License 6 votes vote down vote up
public void write(Filer filer) throws IOException {
    TypeSpec.Builder classBuilder = TypeSpec.classBuilder(model.getClassName().simpleName());
    classBuilder.addModifiers(Modifier.PUBLIC, Modifier.FINAL);
    ClassName superClassName = ClassName.get(PrefsSchema.class);
    classBuilder.superclass(superClassName);

    List<FieldSpec> fieldSpecs = createFields();
    classBuilder.addFields(fieldSpecs);

    List<MethodSpec> methodSpecs = new ArrayList<>();
    methodSpecs.addAll(createConstructors());
    methodSpecs.add(createInitializeMethod());
    methodSpecs.addAll(createMethods());
    classBuilder.addMethods(methodSpecs);

    TypeSpec outClass = classBuilder.build();

    JavaFile.builder(model.getClassName().packageName(), outClass)
            .build()
            .writeTo(filer);
}
 
Example #13
Source File: ExtraUtilityClassBuilder.java    From PrettyBundle with Apache License 2.0 6 votes vote down vote up
private void generateCode(String className, Map<String, ExtraClassesGrouped> extrasGroupedMap, Elements elementUtils, Types typeUtils, Filer filer) throws IOException {
    final TypeSpec.Builder activitiesClassBuilder = TypeSpec.classBuilder(className)
            .addModifiers(Modifier.PUBLIC);

    final List<MethodSpec> methods = getMethods(extrasGroupedMap, elementUtils, typeUtils);

    if (methods == null || methods.size() == 0) {
        // Nothing created if there is no @Extra annotation is Added.
        return;
    }
    for (MethodSpec method : methods) {
        activitiesClassBuilder.addMethod(method);
    }

    JavaFile.builder(packageName, activitiesClassBuilder.build()).build().writeTo(filer);
}
 
Example #14
Source File: SchemaSpec.java    From alchemy with Apache License 2.0 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 #15
Source File: ExtensionTest.java    From auto with Apache License 2.0 6 votes vote down vote up
@Override
public String generateClass(
    Context context, String className, String classToExtend, boolean isFinal) {
  String sideClassName = "Side_" + context.autoValueClass().getSimpleName();
  String sideClass =
      "" //
      + "package " + context.packageName() + ";\n"
      + "class " + sideClassName + " {}\n";
  Filer filer = context.processingEnvironment().getFiler();
  try {
    String sideClassFqName = context.packageName() + "." + sideClassName;
    JavaFileObject sourceFile =
        filer.createSourceFile(sideClassFqName, context.autoValueClass());
    try (Writer sourceWriter = sourceFile.openWriter()) {
      sourceWriter.write(sideClass);
    }
  } catch (IOException e) {
    context
        .processingEnvironment()
        .getMessager()
        .printMessage(Diagnostic.Kind.ERROR, e.toString());
  }
  return null;
}
 
Example #16
Source File: RetainedStateModel.java    From Akatsuki with Apache License 2.0 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 #17
Source File: TableSpec.java    From alchemy with Apache License 2.0 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 #18
Source File: Barbershop.java    From barber with Apache License 2.0 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 #19
Source File: StaticLoaderGenerator.java    From data-mediator with Apache License 2.0 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 #20
Source File: GenClassesManagerWriter.java    From sqlitemagic with Apache License 2.0 5 votes vote down vote up
public void writeSource(Environment environment, GenClassesManagerStep managerStep) throws IOException {
  final List<Dual<TypeElement, String>> submoduleDatabases = environment.getSubmoduleDatabases();
  if (!environment.getAllTableElements().isEmpty() || (submoduleDatabases != null && !submoduleDatabases.isEmpty())) {
    MigrationsHandler.Companion.handleDebugMigrations(environment, managerStep);

    final Filer filer = environment.getFiler();
    final String className = environment.getGenClassesManagerClassName();
    TypeSpec.Builder classBuilder = TypeSpec.classBuilder(className)
        .addModifiers(CLASS_MODIFIERS)
        .addMethod(databaseConfigurator(environment, className))
        .addMethod(databaseSchemaCreator(environment, managerStep, className))
        .addMethod(clearData(environment, className))
        .addMethod(migrateViews(environment, managerStep, className))
        .addMethod(nrOfTables(environment, className));

    if (!environment.isSubmodule()) {
      classBuilder
          .addMethod(columnForValue(environment, managerStep, className))
          .addMethod(dbVersion(environment, className))
          .addMethod(dbName(environment, className))
          .addMethod(submoduleNames(environment, className))
          .addMethod(isDebug(environment, className));
    } else {
      classBuilder.addMethod(columnForValueOrNull(environment, managerStep, className));
    }
    WriterUtil.writeSource(filer, classBuilder.build(), PACKAGE_ROOT);
  }
}
 
Example #21
Source File: TransportProcessor.java    From transport with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Generates the UDF metadata resource file in a pretty-printed JSON format
 */
private void generateUDFMetadataFile() {
  Filer filer = processingEnv.getFiler();
  try {
    FileObject fileObject = filer.createResource(StandardLocation.CLASS_OUTPUT, "", Constants.UDF_RESOURCE_FILE_PATH);
    try (Writer writer = fileObject.openWriter()) {
      _transportUdfMetadata.toJson(writer);
    }
    debug("Wrote Transport UDF metadata file to: " + fileObject.toUri());
  } catch (IOException e) {
    fatalError(String.format("Unable to create UDF metadata resource file: %s", e));
  }
}
 
Example #22
Source File: AnnotationProcessor.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
  if (!roundEnv.processingOver() && !generated) {
    try {
      Filer filer = processingEnv.getFiler();

      JavaFileObject cSource = filer.createSourceFile("ImmutableC");
      try (OutputStream outputStream = cSource.openOutputStream()) {
        outputStream.write("public class ImmutableC { }".getBytes());
      }

      JavaFileObject dSource = filer.createSourceFile("RemovableD");
      try (OutputStream outputStream = dSource.openOutputStream()) {
        outputStream.write("public class RemovableD { }".getBytes());
      }

      FileObject dResource =
          filer.createResource(StandardLocation.CLASS_OUTPUT, "", "RemovableD");
      try (OutputStream outputStream = dResource.openOutputStream()) {
        outputStream.write("foo".getBytes());
      }

      generated = true;
    } catch (IOException e) {
      throw new AssertionError(e);
    }
  }

  return true;
}
 
Example #23
Source File: GenCode.java    From hkt with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private IO<Unit> generateClass(String genClassName, List<TypeElement> allTypeElements, List<P2<HktEffectiveVisibility, String>> allMethods) {

        PackageElement packageELement = Elts.getPackageElement(genClassName.substring(0, genClassName.lastIndexOf(".")));

        HktEffectiveVisibility classVisibility = allMethods.stream()
            .map(P2::_1)
            .filter(HktEffectiveVisibility.Public::equals)
            .findAny()
            .orElse(HktEffectiveVisibility.Package);

        String genSimpleClassName = genClassName.substring(packageELement.getQualifiedName().toString().length() + 1,
            genClassName.length());

        String explicitImports = allTypeElements.stream()
            .map(this::packageRelativeTypeElement)
            .filter(te -> !Elts.getPackageOf(te).equals(packageELement))
            .map(te -> "import " + te.toString() + ";")
            .collect(joining("\n"));

        String methods = allMethods.stream().map(P2::_2).collect(joining("\n\n"));

        String classContent = MessageFormat.format(CLASS_TEMPLATE, packageELement.getQualifiedName().toString(),
            classVisibility.prefix(), genSimpleClassName, explicitImports, methods);

        return IO.effect(() -> {
            try (Writer classWriter = new OutputStreamWriter(
                    Filer.createSourceFile(genClassName).openOutputStream(), UTF_8)) {
                classWriter.append(classContent);
                classWriter.flush();
            }
        });
    }
 
Example #24
Source File: GenCode.java    From hkt with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
GenCode(Elements elts, Types types, Filer filer, TypeElement elt) {
    Elts = elts;
    Types = types;
    Filer = filer;
    __Elt = elt;
    TypeEqElt = Elts.getTypeElement(TypeEq.class.getName());
}
 
Example #25
Source File: BindDaoFactoryBuilder.java    From kripton with Apache License 2.0 5 votes vote down vote up
/**
 * Build dao factory interface.
 *
 * @param elementUtils the element utils
 * @param filer the filer
 * @param schema the schema
 * @return schema typeName
 * @throws Exception the exception
 */
public String buildDaoFactoryInterface(Elements elementUtils, Filer filer, SQLiteDatabaseSchema schema) throws Exception {
	String schemaName = generateDaoFactoryName(schema);

	PackageElement pkg = elementUtils.getPackageOf(schema.getElement());
	String packageName = pkg.isUnnamed() ? "" : pkg.getQualifiedName().toString();

	AnnotationProcessorUtilis.infoOnGeneratedClasses(BindDataSource.class, packageName, schemaName);
	classBuilder = buildDaoFactoryInterfaceInternal(elementUtils, filer, schema);
	TypeSpec typeSpec = classBuilder.build();
	JavaWriterHelper.writeJava2File(filer, packageName, typeSpec);

	return schemaName;
}
 
Example #26
Source File: J2clTestingProcessingStepTest.java    From j2cl with Apache License 2.0 5 votes vote down vote up
private J2clTestingProcessingStep createProcessor() {
  ProcessingEnvironment processingEnv = mock(ProcessingEnvironment.class);
  when(processingEnv.getTypeUtils()).thenReturn(compilation.getTypes());
  when(processingEnv.getElementUtils()).thenReturn(compilation.getElements());
  when(processingEnv.getMessager()).thenReturn(messager);
  when(processingEnv.getFiler()).thenReturn(mock(Filer.class));
  return new J2clTestingProcessingStep(processingEnv);
}
 
Example #27
Source File: AnnotationProcessorUtil.java    From kumuluzee with MIT License 5 votes vote down vote up
public static void writeFile(Set<String> content, String resourceName, Filer filer) throws IOException {
    FileObject file = readOldFile(content, resourceName, filer);
    if (file != null) {
        try {
            writeFile(content, resourceName, file, filer);
            return;
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
    }
    writeFile(content, resourceName, null, filer);
}
 
Example #28
Source File: BaseViewGenerator.java    From PowerfulRecyclerViewAdapter with Apache License 2.0 5 votes vote down vote up
/**
 * create a Java source file
 *
 * @return
 */
protected JavaFileObject createFile() {
    JavaFileObject result = null;
    Filer filer = processingEnvironment.getFiler();
    try {
        result = filer.createSourceFile(getModelClassName());
    } catch (IOException e) {
        logger.log(Diagnostic.Kind.ERROR, "create source file failed");
        e.printStackTrace();
    }
    return result;
}
 
Example #29
Source File: JServiceCodeGenerator.java    From jackdaw with Apache License 2.0 5 votes vote down vote up
@Override
public final void onFinish() throws Exception {
    for (final Map.Entry<String, Set<String>> entry : allServices.entrySet()) {
        final String providerClass = entry.getKey();
        final Set<String> services = entry.getValue();
        final String resourceFile = DIR_SERVICES + providerClass;

        final ProcessingEnvironment env = ProcessorContextHolder.getProcessingEnvironment();
        final Filer filer = env.getFiler();

        writeServices(filer, resourceFile, services);
    }
}
 
Example #30
Source File: TreeShimsCopier.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annos, RoundEnvironment roundEnv) {
    for (Element el : roundEnv.getRootElements()) {
        if (el.getKind() != ElementKind.CLASS)
            continue;
        TypeElement type = (TypeElement) el;
        String qualName = type.getQualifiedName().toString();
        String targetPackage = ALLOWED_CLASSES2TARGET_PACKAGE.get(qualName);
        if (targetPackage != null) {
            try {
                Filer filer = processingEnv.getFiler();
                FileObject fo = filer.getResource(StandardLocation.SOURCE_PATH, ((PackageElement) type.getEnclosingElement()).getQualifiedName().toString(), type.getSimpleName() + ".java");
                URI source = fo.toUri();
                StringBuilder path2Shims = new StringBuilder();
                int p = qualName.split("\\.").length;
                for (int i = 0; i < p; i++) {
                    path2Shims.append("../");
                }
                path2Shims.append("../java.source.base/src/org/netbeans/modules/java/source/TreeShims.java");
                URI treeShims = source.resolve(path2Shims.toString());
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                try (InputStream in = treeShims.toURL().openStream()) {
                    int r;

                    while ((r = in.read()) != (-1)) {
                        baos.write(r);
                    }
                }
                String content = new String(baos.toByteArray(), "UTF-8");
                content = content.replace("package org.netbeans.modules.java.source;", "package " + targetPackage + ";");
                try (OutputStream out = filer.createSourceFile(targetPackage + ".TreeShims", type).openOutputStream()) {
                    out.write(content.getBytes("UTF-8"));
                }
            } catch (IOException ex) {
                throw new IllegalStateException(ex);
            }
        }
    }
    return false;
}