Java Code Examples for javax.annotation.processing.Filer

The following examples show how to use javax.annotation.processing.Filer. These examples are extracted from open source projects. 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 Project: sqlitemagic   Source File: ModelWriter.java    License: 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 2
Source Project: sqlitemagic   Source File: StructureWriter.java    License: 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 3
Source Project: buck   Source File: AnnotationProcessor.java    License: 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 Project: sqlitemagic   Source File: ColumnClassWriter.java    License: 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 5
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 6
Source Project: litho   Source File: PropNameInterStageStore.java    License: 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 7
Source Project: kvs-schema   Source File: SchemaWriter.java    License: 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 8
Source Project: Akatsuki   Source File: RetainedStateModel.java    License: 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 9
Source Project: barber   Source File: Barbershop.java    License: 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 10
Source Project: data-mediator   Source File: StaticLoaderGenerator.java    License: 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 11
Source Project: data-mediator   Source File: SharedPropertiesNGenerator.java    License: 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 12
Source Project: auto   Source File: ExtensionTest.java    License: 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 13
Source Project: PrettyBundle   Source File: ExtraUtilityClassBuilder.java    License: 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 Project: alchemy   Source File: SchemaSpec.java    License: 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 Project: alchemy   Source File: TableSpec.java    License: 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 16
Source Project: alchemy   Source File: ContractSpec.java    License: 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 17
Source Project: alchemy   Source File: EntrySpec.java    License: 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 18
Source Project: turbine   Source File: TurbineProcessingEnvironment.java    License: 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 19
Source Project: FastLayout   Source File: LayoutProcessor.java    License: 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 20
Source Project: jackdaw   Source File: JServiceCodeGenerator.java    License: 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 21
Source Project: PrettyBundle   Source File: ExtraUtilityClassBuilder.java    License: Apache License 2.0 5 votes vote down vote up
public void generateCode(Elements elementUtils, Types typeUtils, Filer filer) throws IOException {
    if (activityExtrasGroupedMap.size() > 0) {
        generateCode(ACTIVITIES, activityExtrasGroupedMap, elementUtils, typeUtils, filer);
    }
    if (serviceExtrasGroupedMap.size() > 0) {
        generateCode(SERVICES, serviceExtrasGroupedMap, elementUtils, typeUtils, filer);
    }
    if (fragmentExtrasGroupedMap.size() > 0) {
        generateCode(FRAGMENTS, fragmentExtrasGroupedMap, elementUtils, typeUtils, filer);
    }
}
 
Example 22
Source Project: buck   Source File: AnnotationProcessor.java    License: 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 Project: IntentLife   Source File: BinderFactory.java    License: Apache License 2.0 5 votes vote down vote up
static void produce(Elements elementUtils, Filer filer,
                    Map<TypeElement, List<TargetField>> targetClasses) {
    // bind method for proxy class.
    MethodSpec.Builder proxyBindMethodBuilder = MethodSpec.methodBuilder(BIND)
            .addModifiers(Modifier.STATIC, Modifier.FINAL, Modifier.PUBLIC)
            .addParameter(ClassName.bestGuess(OBJECT_CLASS_NAME), TARGET, Modifier.FINAL)
            .addParameter(ClassName.bestGuess(BUNDLE_CLASS_NAME), SOURCE, Modifier.FINAL);
    for (Map.Entry<TypeElement, List<TargetField>> entry : targetClasses.entrySet()) {
        final List<TargetField> fields = entry.getValue();
        if (fields == null || fields.isEmpty()) {
            continue;
        }
        /*
          Common parameter
         */
        final TypeElement targetTypeElement = entry.getKey();
        // Activity package name,like "cn.icheny.intentlife.sample".
        final String packageName = elementUtils.getPackageOf(targetTypeElement).getQualifiedName().toString();
        // Activity class name ,like "cn.icheny.intentlife.sample.MainActivity"
        final String targetClassName = targetTypeElement.getQualifiedName().toString();
        // binder class simple name,like "MainActivity_Binder"
        final String binderSimpleClassName = targetClassName.substring(packageName.length() + 1) + BINDER_CLASS_SUFFIX;

        // Generate binder.
        final JavaFile binder = produceBinder(packageName, targetClassName, binderSimpleClassName, fields);
        generateFile(filer, binder);
        // Add proxy control.
        addProxyControl(proxyBindMethodBuilder, packageName, targetClassName, binderSimpleClassName);
    }
    // Generate proxy.
    final JavaFile proxy = produceProxy(proxyBindMethodBuilder);
    generateFile(filer, proxy);
}
 
Example 24
Source Project: ShapeView   Source File: FactoryCodeBuilder.java    License: Apache License 2.0 5 votes vote down vote up
public void generateCode(Messager messager, Elements elementUtils, Filer filer) throws IOException {
    TypeElement superClassName = elementUtils.getTypeElement(mSupperClsName);
    String factoryClassName = superClassName.getSimpleName() + SUFFIX;
    PackageElement pkg = elementUtils.getPackageOf(superClassName);
    String packageName = pkg.isUnnamed() ? null : pkg.getQualifiedName().toString();

    TypeSpec typeSpec = TypeSpec
        .classBuilder(factoryClassName)
        .addModifiers(Modifier.PUBLIC)
        .addMethod(newCreateMethod(elementUtils, superClassName))
        .build();

    // Write file
    JavaFile.builder(packageName, typeSpec).build().writeTo(filer);
}
 
Example 25
/**
 * 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 26
Source Project: sqlitemagic   Source File: GenClassesManagerWriter.java    License: 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 27
Source Project: netbeans   Source File: TreeShimsCopier.java    License: 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;
}
 
Example 28
Source Project: kripton   Source File: BindDaoFactoryBuilder.java    License: 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 29
Source Project: j2cl   Source File: J2clTestingProcessingStepTest.java    License: 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 30
Source Project: kumuluzee   Source File: AnnotationProcessorUtil.java    License: 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);
}