com.squareup.javapoet.JavaFile Java Examples

The following examples show how to use com.squareup.javapoet.JavaFile. 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: RetrofitServiceProcessor.java    From kaif-android with Apache License 2.0 6 votes vote down vote up
private void generateCode(RetrofitServiceInterface retrofitServiceInterface) {

    TypeSpec typeSpec = retrofitServiceInterface.createRetryStaleInterface();

    TypeElement annotatedClassElement = retrofitServiceInterface.getAnnotatedClassElement();
    JavaFile javaFile = JavaFile.builder(elementUtils.getPackageOf(annotatedClassElement)
        .getQualifiedName()
        .toString(), typeSpec).build();
    try {
      JavaFileObject jfo = filer.createSourceFile(retrofitServiceInterface.getQualifiedName());
      try (Writer writer = jfo.openWriter()) {
        javaFile.writeTo(writer);
      }
    } catch (IOException e) {
      error(annotatedClassElement, e.getMessage());
    }
  }
 
Example #2
Source File: Tuple1CasesGenerator.java    From motif with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
  TypeName A = TypeVariableName.get("A");
  TypeName t = ParameterizedTypeName.get(ClassName.get(Tuple1.class), A);

  Match1MethodSpec tuple1Match = Match1MethodSpec.builder()
      .withName("tuple1").withSummaryJavadoc("Matches a tuple of 1 element.\n")
      .withMatchExtractor(Tuple1FieldExtractor.class).withParamA(A, "a").build();

  JavaFile tuple1CasesFile = CasesGenerator.newBuilder(
      "com.leacox.motif.cases", "Tuple1Cases", t)
      .addFileComment(Copyright.COPYRIGHT_NOTICE)
      .addJavadoc("Motif cases for matching a {@link Tuple1}.\n")
      .addMatch1Method(tuple1Match)
      .build().generate();

  try {
    tuple1CasesFile.writeTo(System.out);
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
Example #3
Source File: BundleBindingAdapterGenerator.java    From pocketknife with Apache License 2.0 6 votes vote down vote up
public JavaFile generate() throws IOException {
    TypeVariableName t = TypeVariableName.get("T");
    TypeSpec.Builder classBuilder = TypeSpec.classBuilder(className)
            .addTypeVariable(TypeVariableName.get(t.name, ClassName.get(targetType)))
            .addModifiers(PUBLIC)
            .addJavadoc(getGeneratedComment(BundleBindingAdapterGenerator.class));

    if (parentAdapter != null) {
        classBuilder.superclass(ParameterizedTypeName.get(parentAdapter, t));
    } else {
        classBuilder.addSuperinterface(ParameterizedTypeName.get(ClassName.get(BundleBinding.class), t));
    }

    addSaveStateMethod(classBuilder, t);
    addRestoreStateMethod(classBuilder, t);
    addBindingArgumentsMethod(classBuilder, t);

    return JavaFile.builder(classPackage, classBuilder.build()).build();
}
 
Example #4
Source File: IntentBuilderGenerator.java    From dart with Apache License 2.0 6 votes vote down vote up
@Override
public String brewJava() {
  TypeSpec.Builder intentBuilderTypeBuilder =
      TypeSpec.classBuilder(builderClassName()).addModifiers(Modifier.PUBLIC);

  emitInitialStateGetter(intentBuilderTypeBuilder);
  emitNextStateGetter(intentBuilderTypeBuilder);
  emitExtraDSLStateMachine(intentBuilderTypeBuilder);
  emitResolvedOptionalSequence(intentBuilderTypeBuilder);
  emitInitialState(intentBuilderTypeBuilder);

  //build
  JavaFile javaFile =
      JavaFile.builder(target.classPackage, intentBuilderTypeBuilder.build())
          .addFileComment("Generated code from Henson. Do not modify!")
          .addStaticImport(ActivityClassFinder.class, "getClassDynamically")
          .build();
  return javaFile.toString();
}
 
Example #5
Source File: RouterBuildHelper.java    From grouter-android with Apache License 2.0 6 votes vote down vote up
public static void build(File sourceDir, File jsonDir, String projectName, String scheme, String host) {
    RouterModel routerModel = getRouterModel(jsonDir, projectName, scheme, host, false);
    if (routerModel == null) {
        return;
    }
    try {
        JavaFile activityJavaFile = RouterActivityCodeBuilder.getJavaFile(projectName + "ActivityCenter", routerModel.activityModels);
        JavaFile taskJavaFile = RouterTaskCodeBuilder.getJavaFile(projectName + "TaskCenter", routerModel.taskModels);
        JavaFile componentJavaFile = RouterComponentCodeBuilder.getJavaFile(projectName + "ComponentCenter", routerModel.componentModels);
        JavaFile initializer = RouterAutoInitializerBuilder.getJavaFile(projectName, scheme, host, routerModel);
        // 代理
        RouterDelegateCodeBuilder.buildJavaFile(projectName,projectName + "DelegateCenter", routerModel.delegateModels, sourceDir);

        activityJavaFile.writeTo(sourceDir);
        taskJavaFile.writeTo(sourceDir);
        componentJavaFile.writeTo(sourceDir);
        initializer.writeTo(sourceDir);
    } catch (Throwable e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}
 
Example #6
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 #7
Source File: OptionalCasesGenerator.java    From motif with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
  TypeName T = TypeVariableName.get("T");
  TypeName o = ParameterizedTypeName.get(ClassName.get(Optional.class), T);

  Match0MethodSpec noneMatch = Match0MethodSpec.builder()
      .withName("none").withSummaryJavadoc("Matches an empty {@link Optional}.\n")
      .withMatchExtractor(OptionalNoneFieldExtractor.class).build();

  Match1MethodSpec someMatch = Match1MethodSpec.builder()
      .withName("some").withSummaryJavadoc("Matches a non-empty {@link Optional}.\n")
      .withMatchExtractor(OptionalFieldExtractor.class).withParamA(T, "t").build();

  JavaFile optionalCasesFile =
      CasesGenerator.newBuilder("com.leacox.motif.cases", "OptionalCases", o)
          .addFileComment(Copyright.COPYRIGHT_NOTICE)
          .addJavadoc("Motif cases for matching an {@link Optional}.\n")
          .addMatch0Method(noneMatch)
          .addMatch1Method(someMatch)
          .build().generate();

  try {
    optionalCasesFile.writeTo(System.out);
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
Example #8
Source File: ConstantGenerator.java    From greycat with Apache License 2.0 6 votes vote down vote up
private static JavaFile generateGlobalConstant(String packageName, Constant[] globalConstants) {
    TypeSpec.Builder javaClass = TypeSpec.classBuilder(CONSTANT_CLASS_NAME);
    javaClass.addModifiers(PUBLIC, FINAL);
    for (Constant constant : globalConstants) {
        String value = constant.value();
        if (constant.type().equals("Task") && value != null) {
            value = "greycat.Tasks.newTask().parse(\"" + value.replaceAll("\"", "'").trim() + "\",null);";
        } else if (constant.type().equals("String") && value != null) {
            value = "\""+value+"\"";
        }
        FieldSpec.Builder field = FieldSpec.builder(clazz(constant.type()), constant.name())
                .addModifiers(PUBLIC, STATIC);
        if (value != null) {
            field.addModifiers(FINAL).initializer(value);
        }
        javaClass.addField(field.build());
    }
    return JavaFile.builder(packageName, javaClass.build()).build();
}
 
Example #9
Source File: GenerateYamlLoaderSupportClasses.java    From camel-k-runtime with Apache License 2.0 6 votes vote down vote up
@Override
public void execute() throws MojoFailureException {
    try {
        JavaFile.builder("org.apache.camel.k.loader.yaml", generateJacksonModule())
            .indent("    ")
            .build()
            .writeTo(Paths.get(output));
        JavaFile.builder("org.apache.camel.k.loader.yaml", generateReifiers())
            .indent("    ")
            .build()
            .writeTo(Paths.get(output));
        JavaFile.builder("org.apache.camel.k.loader.yaml", generateResolver())
            .indent("    ")
            .build()
            .writeTo(Paths.get(output));
    } catch (IOException e) {
        throw new MojoFailureException(e.getMessage());
    }
}
 
Example #10
Source File: GenerateYamlParserSupportClasses.java    From camel-k-runtime with Apache License 2.0 6 votes vote down vote up
@Override
public void execute() throws MojoFailureException {
    try {
        JavaFile.builder("org.apache.camel.k.loader.yaml.parser", generateHasExpression())
            .indent("    ")
            .build()
            .writeTo(Paths.get(output));
        JavaFile.builder("org.apache.camel.k.loader.yaml.parser", generateHasDataFormat())
            .indent("    ")
            .build()
            .writeTo(Paths.get(output));
        JavaFile.builder("org.apache.camel.k.loader.yaml.parser", generateHasLoadBalancerType())
            .indent("    ")
            .build()
            .writeTo(Paths.get(output));
    } catch (IOException e) {
        throw new MojoFailureException(e.getMessage());
    }
}
 
Example #11
Source File: GeneratedAnnotationsTest.java    From auto with Apache License 2.0 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
  if (first) {
    TypeSpec.Builder type = TypeSpec.classBuilder("G");
    GeneratedAnnotationSpecs.generatedAnnotationSpec(
            processingEnv.getElementUtils(),
            processingEnv.getSourceVersion(),
            TestProcessor.class)
        .ifPresent(type::addAnnotation);
    JavaFile javaFile = JavaFile.builder("", type.build()).build();
    try {
      javaFile.writeTo(processingEnv.getFiler());
    } catch (IOException e) {
      throw new UncheckedIOException(e);
    }
    first = false;
  }
  return false;
}
 
Example #12
Source File: BuilderGenerator.java    From pocketknife with Apache License 2.0 6 votes vote down vote up
public JavaFile generate() {
    TypeSpec.Builder classBuilder = TypeSpec.classBuilder(className)
            .addSuperinterface(ClassName.get(classPackage, interfaceName))
            .addModifiers(PUBLIC)
            .addJavadoc(getGeneratedComment(BuilderGenerator.class));

    generateKeys(classBuilder);

    if (contextRequired) {
        classBuilder.addField(ClassName.get(typeUtil.contextType), CONTEXT, PRIVATE, FINAL);
        classBuilder.addMethod(MethodSpec.constructorBuilder()
                .addModifiers(PUBLIC)
                .addParameter(ClassName.get(typeUtil.contextType), CONTEXT)
                .addStatement("this.$N = $N", CONTEXT, CONTEXT)
                .build());
    }

    generateMethods(classBuilder);

    return JavaFile.builder(classPackage, classBuilder.build()).build();
}
 
Example #13
Source File: MvpCompiler.java    From Moxy with MIT License 6 votes vote down vote up
private <E extends Element, R> void generateCode(Element element,
                                                 ElementKind kind,
                                                 ElementProcessor<E, R> processor,
                                                 JavaFilesGenerator<R> classGenerator) {
	if (element.getKind() != kind) {
		getMessager().printMessage(Diagnostic.Kind.ERROR, element + " must be " + kind.name());
	}

	//noinspection unchecked
	R result = processor.process((E) element);

	if (result == null) return;

	for (JavaFile file : classGenerator.generate(result)) {
		createSourceFile(file);
	}
}
 
Example #14
Source File: CodeGenerator.java    From shortbread with Apache License 2.0 6 votes vote down vote up
void generate() {
    TypeSpec shortbread = TypeSpec.classBuilder("ShortbreadGenerated")
            .addAnnotation(AnnotationSpec.builder(suppressLint)
                    .addMember("value", "$S", "NewApi")
                    .addMember("value", "$S", "ResourceType")
                    .build())
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addMethod(createShortcuts())
            .addMethod(callMethodShortcut())
            .build();

    JavaFile javaFile = JavaFile.builder("shortbread", shortbread)
            .indent("    ")
            .build();

    try {
        javaFile.writeTo(filer);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #15
Source File: AkatsukiProcessorSourceNameTest.java    From Akatsuki with Apache License 2.0 6 votes vote down vote up
private static GeneratedClassWithName staticInnerClass(String... classes) {
	// maybe (String first, String...more) ?
	if (classes.length == 0)
		throw new IllegalArgumentException("");
	String[] generatedClasses = new String[classes.length];
	TypeSpec.Builder lastBuilder = null;
	for (int i = classes.length - 1; i >= 0; i--) {
		String clazz = classes[i];
		final Builder currentBuilder = TypeSpec.classBuilder(clazz)
				.addModifiers((i == 0 ? Modifier.PUBLIC : Modifier.STATIC))
				.addField(field(STRING_TYPE, clazz.toLowerCase(), Retained.class));
		if (lastBuilder != null) {
			currentBuilder.addType(lastBuilder.build());
		}
		// we generate static inner class names eg A.B -> A$B
		generatedClasses[i] = IntStream.range(0, i + 1).boxed().map(n -> classes[n])
				.collect(Collectors.joining("$"));
		lastBuilder = currentBuilder;
	}
	final JavaFile file = JavaFile.builder(TEST_PACKAGE, lastBuilder.build()).build();
	final JavaFileObject object = JavaFileObjects
			.forSourceString(TEST_PACKAGE + "." + classes[0], file.toString());

	return new GeneratedClassWithName(object, generatedClasses);
}
 
Example #16
Source File: ObjectMappableProcessor.java    From sqlbrite-dao with Apache License 2.0 6 votes vote down vote up
/**
 * Generate code
 */
private void generateCode() throws IOException {

  for (ObjectMappableAnnotatedClass clazz : annotatedClasses) {

    String packageName = getPackageName(clazz);

    // Generate the mapper class
    String mapperClassName = clazz.getSimpleClassName() + "Mapper";
    TypeSpec mapperClass = TypeSpec.classBuilder(mapperClassName)
        .addJavadoc("Generated class to work with Cursors and ContentValues for $T\n",
            ClassName.get(clazz.getElement()))
        .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
        .addMethod(MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE).build())
        .addField(generateRxMappingMethod(clazz))
        .addMethod(generateContentValuesMethod(clazz, mapperClassName, "ContentValuesBuilder"))
        .addType(
            generateContentValuesBuilderClass(clazz, mapperClassName, "ContentValuesBuilder"))
        .build();

    JavaFile.builder(packageName, mapperClass).build().writeTo(filer);
  }
}
 
Example #17
Source File: Case1CasesGenerator.java    From motif with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
  TypeName A = TypeVariableName.get("A");
  TypeName bounds = ParameterizedTypeName.get(ClassName.get(Case1.class), A);
  TypeName t = TypeVariableName.get("T", bounds);
  TypeName clazz = ParameterizedTypeName.get(ClassName.get(Class.class), t);

  Match1MethodSpec case1Match = Match1MethodSpec.builder()
      .withName("case1").withSummaryJavadoc("Matches a case class of one element.\n")
      .addNonMatchParam(clazz, "clazz").withMatchExtractor(Case1FieldExtractor.class, "clazz")
      .withParamA(A, "a").build();

  JavaFile cases1CasesFile = CasesGenerator.newBuilder(
      "com.leacox.motif.cases", "Case1Cases", t)
      .addFileComment(Copyright.COPYRIGHT_NOTICE)
      .addJavadoc("Motif cases for matching a {@link Case1}.\n")
      .addMatch1Method(case1Match)
      .build().generate();

  try {
    cases1CasesFile.writeTo(System.out);
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
Example #18
Source File: ModuleServiceProcessor.java    From FriendCircle with GNU General Public License v3.0 5 votes vote down vote up
private void generateJavaFile() {
    try {
        JavaFile javaFile = JavaFile.builder(APT_PACKAGE_NAME, createType())
                .addFileComment("$S", "Generated code from " + APT_PACKAGE_NAME + "." + APT_FILE_NAME + " Do not modify!")
                .build();
        javaFile.writeTo(mFiler);
    } catch (IOException e) {
        loge(e);
    }
}
 
Example #19
Source File: ExtraBinderGenerator.java    From dart with Apache License 2.0 5 votes vote down vote up
@Override
public String brewJava() {
  TypeSpec.Builder binderTypeSpec =
      TypeSpec.classBuilder(binderClassName()).addModifiers(Modifier.PUBLIC);
  emitBind(binderTypeSpec);
  JavaFile javaFile =
      JavaFile.builder(target.classPackage, binderTypeSpec.build())
          .addFileComment("Generated code from Dart. Do not modify!")
          .build();
  return javaFile.toString();
}
 
Example #20
Source File: IntentBindingAdapterGenerator.java    From pocketknife with Apache License 2.0 5 votes vote down vote up
public JavaFile generate() throws IOException {
    TypeVariableName t = TypeVariableName.get("T");
    TypeSpec.Builder classBuilder = TypeSpec.classBuilder(className)
            .addTypeVariable(TypeVariableName.get(t.name, ClassName.get(targetType)))
            .addModifiers(PUBLIC)
            .addJavadoc(getGeneratedComment(IntentBindingAdapterGenerator.class));

    // Add Interface or Parent Class
    if (parentAdapter != null) {
        classBuilder.superclass(ParameterizedTypeName.get(parentAdapter, t));
    } else {
        classBuilder.addSuperinterface(ParameterizedTypeName.get(ClassName.get(IntentBinding.class), t));
    }

    MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(BIND_EXTRAS_METHOD)
            .addModifiers(PUBLIC)
            .addParameter(ParameterSpec.builder(t, TARGET).build())
            .addParameter(ParameterSpec.builder(ClassName.get(typeUtil.intentType), INTENT).build());
    if (parentAdapter != null) {
        methodBuilder.addStatement("super.$L($N, $N)", BIND_EXTRAS_METHOD, TARGET, INTENT);
    }
    methodBuilder.beginControlFlow("if ($N == null)", INTENT);
    methodBuilder.addStatement("throw new $T($S)", IllegalStateException.class, "intent is null");
    methodBuilder.endControlFlow();

    for (IntentFieldBinding field : fields) {
        addBindExtraField(methodBuilder, field);
    }

    classBuilder.addMethod(methodBuilder.build());

    return JavaFile.builder(classPackage, classBuilder.build()).build();
}
 
Example #21
Source File: AbstractComponentsProcessor.java    From litho with Apache License 2.0 5 votes vote down vote up
protected void generate(SpecModel specModel, EnumSet<RunMode> runMode) throws IOException {
  final String packageName = getPackageName(specModel.getComponentTypeName());
  JavaFile.builder(packageName, specModel.generate(runMode))
      .skipJavaLangImports(true)
      .build()
      .writeTo(processingEnv.getFiler());
}
 
Example #22
Source File: RegisterRouterProcessor.java    From Android-Router with MIT License 5 votes vote down vote up
private void generateRouterRegisterClass(String module, String path, String classFullName) {
	try {
		String pkgName = CompilerHelper.ROUTER_MANAGER_PKN;
		String className = CompilerHelper.getCombineClassFullName(classFullName) + CompilerHelper.ROUTER_MANAGER_CLASS_NAME_SUFFIX;
		String methodName = CompilerHelper.ROUTER_MANAGER_METHOD_NAME;
		MethodSpec registerRouter = computeAddRouter(methodName, module, path, classFullName);

		TypeSpec routerManger = TypeSpec.classBuilder(className).addModifiers(Modifier.PUBLIC).addMethod(registerRouter).build();
		JavaFile javaFile = JavaFile.builder(pkgName, routerManger).build();
		javaFile.writeTo(mFiler);
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example #23
Source File: ControllerCreatorGenerator.java    From nalu with Apache License 2.0 5 votes vote down vote up
public void generate()
    throws ProcessorException {
  TypeSpec.Builder typeSpec = TypeSpec.classBuilder(controllerModel.getController()
                                                                   .getSimpleName() + ProcessorConstants.CREATOR_IMPL)
                                      .addJavadoc(BuildWithNaluCommentProvider.get()
                                                                              .getGeneratedComment())
                                      .superclass(ParameterizedTypeName.get(ClassName.get(AbstractControllerCreator.class),
                                                                            controllerModel.getContext()
                                                                                           .getTypeName()))
                                      .addModifiers(Modifier.PUBLIC,
                                                    Modifier.FINAL)
                                      .addSuperinterface(ClassName.get(IsControllerCreator.class));
  typeSpec.addMethod(createConstructor());
  typeSpec.addMethod(createCreateMethod());
  typeSpec.addMethod(createFinishCreateMethod());
  typeSpec.addMethod(createSetParameterMethod());

  JavaFile javaFile = JavaFile.builder(controllerModel.getController()
                                                      .getPackage(),
                                       typeSpec.build())
                              .build();
  try {
    //      System.out.println(javaFile.toString());
    javaFile.writeTo(this.processingEnvironment.getFiler());
  } catch (IOException e) {
    throw new ProcessorException("Unable to write generated file: >>" +
                                 controllerModel.getController()
                                                .getSimpleName() +
                                 ProcessorConstants.CREATOR_IMPL +
                                 "<< -> exception: " +
                                 e.getMessage());
  }
}
 
Example #24
Source File: ListConsCasesGenerator.java    From motif with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
  TypeName E = TypeVariableName.get("T");
  TypeName l = ParameterizedTypeName.get(ClassName.get(List.class), E);

  Match0MethodSpec nilMatch = Match0MethodSpec.builder()
      .withName("nil").withSummaryJavadoc("Matches an empty list.\n")
      .withMatchExtractor(ListConsNilFieldExtractor.class).build();

  Match1MethodSpec headNilMatch = Match1MethodSpec.builder()
      .withName("headNil").withSummaryJavadoc("Matches a list with exactly one element.\n")
      .withMatchExtractor(ListConsHeadFieldExtractor.class).withParamA(E, "head").build();

  Match2MethodSpec headTailMatch = Match2MethodSpec.builder()
      .withName("headTail")
      .withSummaryJavadoc(
          "Matches a list with a head element and a tail of remaining elements.\n")
      .withMatchExtractor(ListConsHeadTailFieldExtractor.class).withParamA(E, "head")
      .withParamB(l, "tail").build();

  JavaFile listCasesFile = CasesGenerator.newBuilder("com.leacox.motif.cases", "ListConsCases", l)
      .addFileComment(Copyright.COPYRIGHT_NOTICE)
      .addJavadoc("Motif cases for matching a {@link List} with cons.\n")
      .addMatch0Method(nilMatch)
      .addMatch1Method(headNilMatch)
      .addMatch2Method(headTailMatch)
      .build().generate();

  try {
    listCasesFile.writeTo(System.out);
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
Example #25
Source File: EntityHandler.java    From RxPay with Apache License 2.0 5 votes vote down vote up
public void generateCode(JavaFile code) {
        try {
            code.writeTo(filer);
        } catch (Exception e) {
//            e.printStackTrace();
        }
    }
 
Example #26
Source File: AutoMatterProcessor.java    From auto-matter with Apache License 2.0 5 votes vote down vote up
private void process(final Element element) throws IOException, AutoMatterProcessorException {
  final Descriptor d = new Descriptor(element, elements, types);

  TypeSpec builder = builder(d);
  JavaFile javaFile = JavaFile.builder(d.packageName(), builder)
      .skipJavaLangImports(true)
      .build();
  javaFile.writeTo(filer);
}
 
Example #27
Source File: ZeroCellAnnotationProcessor.java    From zerocell with Apache License 2.0 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {
    for(Element annotatedElement : env.getElementsAnnotatedWith(ZerocellReaderBuilder.class)) {
        if (annotatedElement.getKind() != ElementKind.CLASS) {
            env.errorRaised();
            return true;
        }
        TypeElement classElement = (TypeElement) annotatedElement;
        try {
            ZerocellReaderBuilder annotation = annotatedElement.getAnnotation(ZerocellReaderBuilder.class);
            Optional<String> customReaderName =  Optional.empty();
            String name = annotation.value();
            if (!name.equals("__none__") && !name.isEmpty()) {
                customReaderName = Optional.of(name);
            }
            ReaderTypeSpec spec = new ReaderTypeSpec(classElement, customReaderName);
            JavaFile javaFile = spec.build();
            javaFile.writeTo(filer);
        } catch (Exception ioe) {
            ioe.printStackTrace();
            messager.printMessage(Diagnostic.Kind.ERROR,
                    String.format("Failed to generate the Reader class for %s, got exception: %s",
                        classElement.getQualifiedName().toString(),
                        ioe.getMessage()),
                    annotatedElement);
            env.errorRaised();
            return true;
        }
    }
    return false;
}
 
Example #28
Source File: AbstractVKeyProcessor.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private JavaFile createJavaFile(
    String packageName, String converterClassName, TypeMirror entityTypeMirror) {
  TypeName entityType = ClassName.get(entityTypeMirror);

  ParameterizedTypeName attributeConverter =
      ParameterizedTypeName.get(
          ClassName.get("google.registry.persistence.converter", "VKeyConverter"),
          entityType,
          ClassName.get(getSqlColumnType()));

  MethodSpec getAttributeClass =
      MethodSpec.methodBuilder("getAttributeClass")
          .addAnnotation(Override.class)
          .addModifiers(Modifier.PROTECTED)
          .returns(
              ParameterizedTypeName.get(
                  ClassName.get(Class.class), ClassName.get(entityTypeMirror)))
          .addStatement("return $T.class", entityType)
          .build();

  TypeSpec vKeyConverter =
      TypeSpec.classBuilder(converterClassName)
          .addAnnotation(
              AnnotationSpec.builder(ClassName.get(Converter.class))
                  .addMember("autoApply", "true")
                  .build())
          .addModifiers(Modifier.FINAL)
          .superclass(attributeConverter)
          .addMethod(getAttributeClass)
          .build();

  return JavaFile.builder(packageName, vKeyConverter).build();
}
 
Example #29
Source File: JavaGeneratorTest.java    From raptor with Apache License 2.0 5 votes vote down vote up
private void writeJavaFile(ClassName javaTypeName, TypeSpec typeSpec, Location location)
        throws IOException {
    JavaFile.Builder builder = JavaFile.builder(javaTypeName.packageName(), typeSpec)
            .addFileComment("$L", "Code generated by Wire protocol buffer compiler, do not edit.");
    if (location != null) {
        builder.addFileComment("\nSource file: $L", location);
    }
    JavaFile javaFile = builder.build();
    try {
        javaFile.writeTo(new File(GENERATED_SOURCE_DIR));
    } catch (IOException e) {
        throw new IOException("Failed to write " + javaFile.packageName + "."
                + javaFile.typeSpec.name + " to " + GENERATED_SOURCE_DIR, e);
    }
}
 
Example #30
Source File: BaseProcessor.java    From pandroid with Apache License 2.0 5 votes vote down vote up
protected void saveClass(ProcessingEnvironment environment, String packageName, TypeSpec.Builder classBuilder) {
    JavaFile javaFile = JavaFile.builder(packageName, classBuilder.build())
            .build();
    javaFile.toJavaFileObject();
    try {
        javaFile.writeTo(environment.getFiler());
        classGenerated = true;
    } catch (IOException e) {
        log(environment, e.getMessage(), Diagnostic.Kind.ERROR);
    }
}