Java Code Examples for com.squareup.javapoet.JavaFile#toString()

The following examples show how to use com.squareup.javapoet.JavaFile#toString() . 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: BundleExtension.java    From auto-value-bundle with MIT License 6 votes vote down vote up
@Override
public String generateClass(Context context, String className, String classToExtend, boolean isFinal) {
    String packageName = context.packageName();
    Map<String, TypeName> types = convertPropertiesToTypes(context.properties());

    TypeSpec subclass = TypeSpec.classBuilder(className)
            .addModifiers(isFinal ? FINAL : ABSTRACT)
            .superclass(ClassName.get(context.packageName(), classToExtend))
            .addMethod(generateConstructor(types))
            .addMethod(generateUnbundleMethod(context))
            .addMethod(generateUnboxMethod(ClassName.get("java.lang", "Byte"), TypeName.BYTE, "byte"))
            .addMethod(generateUnboxMethod(ClassName.get("java.lang", "Short"), TypeName.SHORT, "short"))
            .addMethod(generateUnboxMethod(ClassName.get("java.lang", "Float"), TypeName.FLOAT, "float"))
            .addMethod(generateUnboxMethod(ClassName.get("java.lang", "Character"), TypeName.CHAR, "char"))
            .build();

    JavaFile javaFile = JavaFile.builder(packageName, subclass).build();
    return javaFile.toString();
}
 
Example 2
Source File: MemberInjectorGenerator.java    From toothpick with Apache License 2.0 6 votes vote down vote up
public String brewJava() {
  // Interface to implement
  ClassName className = ClassName.get(targetClass);
  ParameterizedTypeName memberInjectorInterfaceParameterizedTypeName =
      ParameterizedTypeName.get(ClassName.get(MemberInjector.class), className);

  // Build class
  TypeSpec.Builder scopeMemberTypeSpec =
      TypeSpec.classBuilder(getGeneratedSimpleClassName(targetClass) + MEMBER_INJECTOR_SUFFIX)
          .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
          .addSuperinterface(memberInjectorInterfaceParameterizedTypeName);
  emitSuperMemberInjectorFieldIfNeeded(scopeMemberTypeSpec);
  emitInjectMethod(scopeMemberTypeSpec, fieldInjectionTargetList, methodInjectionTargetList);

  JavaFile javaFile =
      JavaFile.builder(className.packageName(), scopeMemberTypeSpec.build()).build();
  return javaFile.toString();
}
 
Example 3
Source File: FactoryGenerator.java    From toothpick with Apache License 2.0 6 votes vote down vote up
public String brewJava() {
  // Interface to implement
  ClassName className = ClassName.get(constructorInjectionTarget.builtClass);
  ParameterizedTypeName parameterizedTypeName =
      ParameterizedTypeName.get(ClassName.get(Factory.class), className);

  // Build class
  TypeSpec.Builder factoryTypeSpec =
      TypeSpec.classBuilder(
              getGeneratedSimpleClassName(constructorInjectionTarget.builtClass) + FACTORY_SUFFIX)
          .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
          .addSuperinterface(parameterizedTypeName);
  emitSuperMemberInjectorFieldIfNeeded(factoryTypeSpec);
  emitCreateInstance(factoryTypeSpec);
  emitGetTargetScope(factoryTypeSpec);
  emitHasScopeAnnotation(factoryTypeSpec);
  emitHasSingletonAnnotation(factoryTypeSpec);
  emitHasReleasableAnnotation(factoryTypeSpec);
  emitHasProvidesSingletonAnnotation(factoryTypeSpec);
  emitHasProvidesReleasableAnnotation(factoryTypeSpec);

  JavaFile javaFile = JavaFile.builder(className.packageName(), factoryTypeSpec.build()).build();
  return javaFile.toString();
}
 
Example 4
Source File: GeneratedCodeGenerator.java    From jackdaw with Apache License 2.0 6 votes vote down vote up
@Override
public final void generate(final CodeGeneratorContext context) throws Exception {
    final TypeElement typeElement = context.getTypeElement();
    final String packageName = context.getPackageName();
    final String className = context.getClassName(getNameModifier());

    final JavaFileObject file = ProcessorUtils.createSourceFile(typeElement, packageName, className);
    try (
        final Writer writer = file.openWriter();
        final PrintWriter printWriter = new PrintWriter(writer)
    ) {
        final TypeSpec.Builder typeSpecBuilder = generateCommon(className);
        generateBody(context, typeSpecBuilder);

        final TypeSpec typeSpec = typeSpecBuilder.build();
        final JavaFile javaFile = JavaFile.builder(packageName, typeSpec)
            .indent(SourceTextUtils.INDENT)
            .skipJavaLangImports(true)
            .build();

        final String sourceCode = javaFile.toString();
        printWriter.write(sourceCode);
        printWriter.flush();
    }
}
 
Example 5
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 6
Source File: Bundler.java    From easybundler with Apache License 2.0 5 votes vote down vote up
/**
 * Process the BundlerClass and return the source of a generated Bundler class, as a String.
 * The output of this method is intended for writing to a ".java" file.
 */
public String getBundlerClassSource() {
    // Create class named {FooObject}Bundler
    TypeSpec bundlerType = TypeSpec.classBuilder(getBundlerClassName())
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addMethod(createToBundleMethod())
            .addMethod(createFromBundleMethod())
            .build();

    JavaFile javaFile = JavaFile.builder(info.className.packageName(), bundlerType)
            .build();

    return javaFile.toString();
}
 
Example 7
Source File: OpenApi2JaxRs.java    From apicurio-studio with Apache License 2.0 5 votes vote down vote up
/**
 * Generates the JaxRsApplication java class.
 */
protected String generateJaxRsApplication() throws IOException {
    TypeSpec jaxRsApp = TypeSpec.classBuilder(ClassName.get(this.settings.javaPackage, "JaxRsApplication"))
            .addModifiers(Modifier.PUBLIC)
            .superclass(ClassName.get("javax.ws.rs.core", "Application"))
            .addAnnotation(ClassName.get("javax.enterprise.context", "ApplicationScoped"))
            .addAnnotation(AnnotationSpec.builder(ClassName.get("javax.ws.rs", "ApplicationPath"))
                    .addMember("value", "$S", "/")
                    .build())
            .addJavadoc("The JAX-RS application.\n")
            .build();
    JavaFile javaFile = JavaFile.builder(this.settings.javaPackage, jaxRsApp).build();
    return javaFile.toString();
}
 
Example 8
Source File: AutoValueRedactedExtension.java    From auto-value-redacted with Apache License 2.0 5 votes vote down vote up
@Override
public String generateClass(Context context, String className, String classToExtend,
    boolean isFinal) {
  String packageName = context.packageName();
  TypeElement autoValueClass = context.autoValueClass();
  List<? extends TypeParameterElement> typeParameters = autoValueClass.getTypeParameters();
  Name superName = autoValueClass.getSimpleName();
  Map<String, ExecutableElement> properties = context.properties();

  TypeSpec.Builder subclass = TypeSpec.classBuilder(className) //
      .addModifiers(isFinal ? Modifier.FINAL : Modifier.ABSTRACT) //
      .addMethod(generateConstructor(properties)) //
      .addMethod(generateToString(superName, properties));

  ClassName superclass = ClassName.get(packageName, classToExtend);
  if (typeParameters.isEmpty()) {
    subclass.superclass(superclass);
  } else {
    List<TypeVariableName> typeVariables = new ArrayList<>();
    for (TypeParameterElement typeParameter : typeParameters) {
      typeVariables.add(TypeVariableName.get(typeParameter));
    }
    subclass.addTypeVariables(typeVariables)
        .superclass(
            ParameterizedTypeName.get(superclass, typeVariables.toArray(new TypeName[0])));
  }

  JavaFile javaFile = JavaFile.builder(packageName, subclass.build()).build();
  return javaFile.toString();
}
 
Example 9
Source File: CodeGenUtils.java    From Akatsuki with Apache License 2.0 5 votes vote down vote up
public static String createTestSource(String className, Iterable<FieldSpec> fieldSpecs) {
	TypeSpec testType = TypeSpec.classBuilder(className)
			.addModifiers(Modifier.PUBLIC, Modifier.FINAL).addFields(fieldSpecs).build();
	JavaFile javaFile = JavaFile.builder(IntegrationTestBase.TEST_PACKAGE, testType).build();
	// javaFile.toString() does the same thing as using a string writer
	// internally
	return javaFile.toString();
}
 
Example 10
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 11
Source File: NavigationModelBinderGenerator.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);
  emitAssign(binderTypeSpec);

  JavaFile javaFile =
      JavaFile.builder(target.classPackage, binderTypeSpec.build())
          .addFileComment("Generated code from Dart. Do not modify!")
          .build();
  return javaFile.toString();
}
 
Example 12
Source File: AutoParcelProcessor.java    From auto-parcel with Apache License 2.0 4 votes vote down vote up
private String generateClass(TypeElement type, String className, String classToExtend, boolean isFinal) {
    if (type == null) {
        mErrorReporter.abortWithError("generateClass was invoked with null type", type);
    }
    if (className == null) {
        mErrorReporter.abortWithError("generateClass was invoked with null class name", type);
    }
    if (classToExtend == null) {
        mErrorReporter.abortWithError("generateClass was invoked with null parent class", type);
    }
    List<VariableElement> nonPrivateFields = getParcelableFieldsOrError(type);
    if (nonPrivateFields.isEmpty()) {
        mErrorReporter.abortWithError("generateClass error, all fields are declared PRIVATE", type);
    }

    // get the properties
    ImmutableList<Property> properties = buildProperties(nonPrivateFields);

    // get the type adapters
    ImmutableMap<TypeMirror, FieldSpec> typeAdapters = getTypeAdapters(properties);

    // get the parcel version
    //noinspection ConstantConditions
    int version = type.getAnnotation(AutoParcel.class).version();

    // Generate the AutoParcel_??? class
    String pkg = TypeUtil.packageNameOf(type);
    TypeName classTypeName = ClassName.get(pkg, className);
    TypeSpec.Builder subClass = TypeSpec.classBuilder(className)
            // Add the version
            .addField(TypeName.INT, "version", PRIVATE)
            // Class must be always final
            .addModifiers(FINAL)
            // extends from original abstract class
            .superclass(ClassName.get(pkg, classToExtend))
            // Add the DEFAULT constructor
            .addMethod(generateConstructor(properties))
            // Add the private constructor
            .addMethod(generateConstructorFromParcel(processingEnv, properties, typeAdapters))
            // overrides describeContents()
            .addMethod(generateDescribeContents())
            // static final CREATOR
            .addField(generateCreator(processingEnv, properties, classTypeName, typeAdapters))
            // overrides writeToParcel()
            .addMethod(generateWriteToParcel(version, processingEnv, properties, typeAdapters)); // generate writeToParcel()

    if (!ancestoIsParcelable(processingEnv, type)) {
        // Implement android.os.Parcelable if the ancestor does not do it.
        subClass.addSuperinterface(ClassName.get("android.os", "Parcelable"));
    }

    if (!typeAdapters.isEmpty()) {
        typeAdapters.values().forEach(subClass::addField);
    }


    JavaFile javaFile = JavaFile.builder(pkg, subClass.build()).build();
    return javaFile.toString();
}
 
Example 13
Source File: OpenApi2JaxRs.java    From apicurio-studio with Apache License 2.0 4 votes vote down vote up
/**
 * Generates a Jax-rs interface from the given codegen information.
 * @param _interface
 */
protected String generateJavaInterface(CodegenJavaInterface _interface) {
    // Create the JAX-RS interface spec itself.
    Builder interfaceBuilder = TypeSpec
            .interfaceBuilder(ClassName.get(_interface.getPackage(), _interface.getName()));
    interfaceBuilder.addModifiers(Modifier.PUBLIC)
            .addAnnotation(AnnotationSpec.builder(ClassName.get("javax.ws.rs", "Path"))
                    .addMember("value", "$S", _interface.getPath()).build())
            .addJavadoc("A JAX-RS interface.  An implementation of this interface must be provided.\n");

    // Add specs for all the methods.
    for (CodegenJavaMethod cgMethod : _interface.getMethods()) {
        com.squareup.javapoet.MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(cgMethod.getName());
        methodBuilder.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT);
        // The @Path annotation.
        if (cgMethod.getPath() != null) {
            methodBuilder.addAnnotation(AnnotationSpec.builder(ClassName.get("javax.ws.rs", "Path"))
                    .addMember("value", "$S", cgMethod.getPath()).build());
        }
        // The @GET, @PUT, @POST, etc annotation
        methodBuilder.addAnnotation(AnnotationSpec.builder(ClassName.get("javax.ws.rs", cgMethod.getMethod().toUpperCase())).build());
        // The @Produces annotation
        if (cgMethod.getProduces() != null && !cgMethod.getProduces().isEmpty()) {
            methodBuilder.addAnnotation(AnnotationSpec.builder(ClassName.get("javax.ws.rs", "Produces"))
                    .addMember("value", "$L", toStringArrayLiteral(cgMethod.getProduces())).build());
        }
        // The @Consumes annotation
        if (cgMethod.getConsumes() != null && !cgMethod.getConsumes().isEmpty()) {
            methodBuilder.addAnnotation(AnnotationSpec.builder(ClassName.get("javax.ws.rs", "Consumes"))
                    .addMember("value", "$L", toStringArrayLiteral(cgMethod.getConsumes())).build());
        }
        // The method return type.
        if (cgMethod.getReturn() != null) {
            TypeName returnType = generateTypeName(cgMethod.getReturn().getCollection(),
                    cgMethod.getReturn().getType(), cgMethod.getReturn().getFormat(), true,
                    ClassName.get("javax.ws.rs.core", "Response"));
            if (getSettings().reactive || cgMethod.isAsync()) {
                returnType = generateReactiveTypeName(returnType);
            }
            methodBuilder.returns(returnType);
        }
        
        // The method arguments.
        if (cgMethod.getArguments() != null && !cgMethod.getArguments().isEmpty()) {
            for (CodegenJavaArgument cgArgument : cgMethod.getArguments()) {
                TypeName defaultParamType = ClassName.OBJECT;
                if (cgArgument.getIn().equals("body")) {
                    defaultParamType = ClassName.get("java.io", "InputStream");
                }
                TypeName paramType = generateTypeName(cgArgument.getCollection(), cgArgument.getType(),
                        cgArgument.getFormat(), cgArgument.getRequired(), defaultParamType);
                if (cgArgument.getTypeSignature() != null) {
                    // TODO try to find a re-usable data type that matches the type signature
                }
                com.squareup.javapoet.ParameterSpec.Builder paramBuilder = ParameterSpec.builder(paramType,
                        paramNameToJavaArgName(cgArgument.getName()));
                if (cgArgument.getIn().equals("path")) {
                    paramBuilder.addAnnotation(AnnotationSpec.builder(ClassName.get("javax.ws.rs", "PathParam"))
                            .addMember("value", "$S", cgArgument.getName()).build());
                }
                if (cgArgument.getIn().equals("query")) {
                    paramBuilder.addAnnotation(AnnotationSpec.builder(ClassName.get("javax.ws.rs", "QueryParam"))
                            .addMember("value", "$S", cgArgument.getName()).build());
                }
                if (cgArgument.getIn().equals("header")) {
                    paramBuilder.addAnnotation(AnnotationSpec.builder(ClassName.get("javax.ws.rs", "HeaderParam"))
                            .addMember("value", "$S", cgArgument.getName()).build());
                }
                methodBuilder.addParameter(paramBuilder.build());
            }
        }
        
        // TODO:: error responses (4xx and 5xx)
        // Should errors be modeled in some way?  JAX-RS has a few ways to handle them.  I'm inclined to 
        // not generate anything in the interface for error responses.
        
        // Javadoc
        if (cgMethod.getDescription() != null) {
            methodBuilder.addJavadoc(cgMethod.getDescription());
            methodBuilder.addJavadoc("\n");
        }
        
        interfaceBuilder.addMethod(methodBuilder.build());
    }
    
    TypeSpec jaxRsInterface = interfaceBuilder.build();
    
    JavaFile javaFile = JavaFile.builder(_interface.getPackage(), jaxRsInterface).build();
    return javaFile.toString();
}
 
Example 14
Source File: TestSource.java    From Akatsuki with Apache License 2.0 4 votes vote down vote up
public String generateSource() {
	checkInner();
	JavaFile javaFile = JavaFile.builder(packageName, specBuilder().build()).build();
	return javaFile.toString();
}
 
Example 15
Source File: Generator.java    From reflection-no-reflection with Apache License 2.0 4 votes vote down vote up
private void printJavaFile(JavaFile javaFile) {
    String buffer = javaFile.toString();
    System.out.println(buffer);
}