javax.annotation.processing.Filer源码实例Demo

类javax.annotation.processing.Filer源码实例Demo

下面列出了javax.annotation.processing.Filer 类实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: sqlitemagic   文件: ModelWriter.java
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);
}
 
源代码2 项目: sqlitemagic   文件: StructureWriter.java
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());
}
 
源代码3 项目: buck   文件: AnnotationProcessor.java
@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;
}
 
源代码4 项目: sqlitemagic   文件: ColumnClassWriter.java
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;
}
 
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);
  }
}
 
源代码6 项目: litho   文件: PropNameInterStageStore.java
/**
 * 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();
  }
}
 
源代码7 项目: kvs-schema   文件: SchemaWriter.java
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);
}
 
源代码8 项目: Akatsuki   文件: RetainedStateModel.java
@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);
}
 
源代码9 项目: barber   文件: Barbershop.java
/**
 * 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);
}
 
源代码10 项目: data-mediator   文件: StaticLoaderGenerator.java
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;
}
 
源代码11 项目: data-mediator   文件: SharedPropertiesNGenerator.java
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;
}
 
源代码12 项目: auto   文件: ExtensionTest.java
@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;
}
 
源代码13 项目: PrettyBundle   文件: ExtraUtilityClassBuilder.java
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);
}
 
源代码14 项目: alchemy   文件: SchemaSpec.java
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);
}
 
源代码15 项目: alchemy   文件: TableSpec.java
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;
}
 
源代码16 项目: alchemy   文件: ContractSpec.java
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);
}
 
源代码17 项目: alchemy   文件: EntrySpec.java
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);
}
 
源代码18 项目: turbine   文件: TurbineProcessingEnvironment.java
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;
}
 
源代码19 项目: FastLayout   文件: LayoutProcessor.java
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;
}
 
源代码20 项目: jackdaw   文件: JServiceCodeGenerator.java
@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);
    }
}
 
源代码21 项目: PrettyBundle   文件: ExtraUtilityClassBuilder.java
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);
    }
}
 
源代码22 项目: buck   文件: AnnotationProcessor.java
@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;
}
 
源代码23 项目: IntentLife   文件: BinderFactory.java
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);
}
 
源代码24 项目: ShapeView   文件: FactoryCodeBuilder.java
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);
}
 
源代码25 项目: transport   文件: TransportProcessor.java
/**
 * 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));
  }
}
 
源代码26 项目: sqlitemagic   文件: GenClassesManagerWriter.java
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);
  }
}
 
源代码27 项目: netbeans   文件: TreeShimsCopier.java
@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;
}
 
源代码28 项目: kripton   文件: BindDaoFactoryBuilder.java
/**
 * 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;
}
 
源代码29 项目: j2cl   文件: J2clTestingProcessingStepTest.java
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);
}
 
源代码30 项目: kumuluzee   文件: AnnotationProcessorUtil.java
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);
}
 
如果文章对您有帮助,请点击页面广告。以鼓励作者做出的努力。
 类所在包
 类方法
 同包方法