Java Code Examples for com.squareup.javapoet.TypeSpec.Builder#addMethod()

The following examples show how to use com.squareup.javapoet.TypeSpec.Builder#addMethod() . 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: ArgumentBuilderModel.java    From Akatsuki with Apache License 2.0 6 votes vote down vote up
private void extendConcludingBuilder(ProcessorContext context, Builder builderTypeBuilder,
		DeclaredType concludingBuilder) {
	if (context.utils().isAssignable(concludingBuilder,
			context.utils().of(ClassArgBuilder.class), true)) {
		// implement the constructor with class parameters
		// TODO that bundle part is redundant... consider improving
		builderTypeBuilder.addMethod(MethodSpec.constructorBuilder()
				.addParameter(ClassName.get(AndroidTypes.Bundle.asMirror(context)),
						"bundle")
				.addCode("super(bundle, $L.class);", targetClassName).build());
	} else if (context.utils().isAssignable(concludingBuilder,
			context.utils().of(ArgConcludingBuilder.class), true)) {
		// this is probably an user implemented one
		builderTypeBuilder.addMethod(MethodSpec.constructorBuilder()
				.addCode("this.bundle = new Bundle();").build());
	} else {
		throw new AssertionError(concludingBuilder + " is not supported, @ArgConfig should"
				+ " not allow this in the first place...");
	}
}
 
Example 2
Source File: InitializerSpec.java    From spring-init with Apache License 2.0 5 votes vote down vote up
private TypeSpec createInitializer(TypeElement type) {
	Builder builder = TypeSpec.classBuilder(getClassName());
	builder.addSuperinterface(SpringClassNames.INITIALIZER_TYPE);
	builder.addModifiers(Modifier.PUBLIC);
	this.hasEnabled = maybeAddEnabled(builder);
	builder.addMethod(createInitializer());
	return builder.build();
}
 
Example 3
Source File: JSupplierCodeGenerator.java    From jackdaw with Apache License 2.0 5 votes vote down vote up
private void addFunction(
    final Builder builder, final TypeElement typeElement,
    final Element element, final JSupplier annotation
) {
    final JSupplierType functionType = annotation.type();
    final String packageName = getFunctionPackageName(functionType);
    final String caller = ModelUtils.getCaller(element);
    final TypeName typeName = TypeUtils.getTypeName(element, true);

    final ClassName supplierClass = ClassName.get(packageName, CLASS_NAME);
    final TypeName parameterClass = TypeUtils.getTypeName(typeElement);
    final ParameterizedTypeName fieldTypeName =
        ParameterizedTypeName.get(supplierClass, typeName);

    builder.addMethod(
        MethodSpec.methodBuilder(TypeUtils.getName(element))
            .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
            .addParameter(parameterClass, "o", Modifier.FINAL)
            .returns(fieldTypeName)
            .addCode(
                SourceTextUtils.lines(
                    "return new $T() {",
                        "@Override",
                        "public $T get() {",
                            "return o.$L;",
                        "}",
                    "};",
                    ""
                ),
                fieldTypeName, typeName, caller
            )
            .build()
    );
}
 
Example 4
Source File: AnnotationBuilder.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
private static AnnotationImpl createAnnotationImpl(TypeElement annotation) {
  String implName = annotation.getSimpleName().toString() + "Impl";
  Builder annotationImpl =
      TypeSpec.classBuilder(implName)
          .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
          .addSuperinterface(TypeName.get(annotation.asType()))
          .addMethod(
              MethodSpec.methodBuilder("annotationType")
                  .addAnnotation(Override.class)
                  .addModifiers(Modifier.PUBLIC)
                  .returns(
                      ParameterizedTypeName.get(
                          ClassName.get(Class.class),
                          WildcardTypeName.subtypeOf(Annotation.class)))
                  .addCode("return $T.class;\n", annotation)
                  .build());
  List<ParameterSpec> parameters = new ArrayList<>();
  Map<FieldSpec, AnnotationValue> defaults = new HashMap<>();
  for (ExecutableElement method : ElementFilter.methodsIn(annotation.getEnclosedElements())) {
    FieldSpec field =
        FieldSpec.builder(
                TypeName.get(method.getReturnType()),
                method.getSimpleName().toString(),
                Modifier.PRIVATE,
                Modifier.FINAL)
            .build();
    if (method.getDefaultValue() != null) {
      defaults.put(field, method.getDefaultValue());
    }

    annotationImpl
        .addField(field)
        .addMethod(
            MethodSpec.methodBuilder(field.name)
                .addModifiers(Modifier.PUBLIC)
                .addAnnotation(Override.class)
                .returns(field.type)
                .addCode("return $N;\n", field)
                .build());
    parameters.add(
        ParameterSpec.builder(
                TypeName.get(method.getReturnType()), method.getSimpleName().toString())
            .build());
  }

  MethodSpec.Builder constructorBuilder =
      MethodSpec.constructorBuilder().addParameters(parameters);
  for (ParameterSpec parameter : parameters) {
    constructorBuilder.addCode("this.$1N = $1N;\n", parameter.name);
  }
  annotationImpl.addMethod(constructorBuilder.build());

  annotationImpl.addMethod(EqualsMethod.generate(annotation));
  annotationImpl.addMethod(HashCodeMethod.generate(annotation));
  annotationImpl.addMethod(ToStringMethod.generate(annotation));

  return new AnnotationImpl(annotationImpl.build(), defaults);
}
 
Example 5
Source File: DynamicEntityBuilder.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
private void createOnPersistMethod(Builder builder) {
	MethodSpec method = MethodSpec.methodBuilder("onPersist").addModifiers(Modifier.PUBLIC).returns(void.class)
			.addException(Exception.class).build();
	builder.addMethod(method);
}
 
Example 6
Source File: SyncClientClass.java    From aws-sdk-java-v2 with Apache License 2.0 4 votes vote down vote up
@Override
public TypeSpec poetSpec() {
    ClassName interfaceClass = poetExtensions.getClientClass(model.getMetadata().getSyncInterface());

    Builder classBuilder = PoetUtils.createClassBuilder(className)
                                    .addAnnotation(SdkInternalApi.class)
                                    .addModifiers(FINAL)
                                    .addSuperinterface(interfaceClass)
                                    .addJavadoc("Internal implementation of {@link $1T}.\n\n@see $1T#builder()",
                                                interfaceClass)
                                    .addField(SyncClientHandler.class, "clientHandler", PRIVATE, FINAL)
                                    .addField(protocolSpec.protocolFactory(model))
                                    .addField(SdkClientConfiguration.class, "clientConfiguration", PRIVATE, FINAL)
                                    .addMethod(constructor())
                                    .addMethod(nameMethod())
                                    .addMethods(protocolSpec.additionalMethods())
                                    .addMethods(operations());

    protocolSpec.createErrorResponseHandler().ifPresent(classBuilder::addMethod);

    classBuilder.addMethod(protocolSpec.initProtocolFactory(model));

    classBuilder.addMethod(closeMethod());

    if (model.hasPaginators()) {
        classBuilder.addMethod(applyPaginatorUserAgentMethod(poetExtensions, model));
    }

    if (model.containsRequestSigners()) {
        classBuilder.addMethod(applySignerOverrideMethod(poetExtensions, model));
    }

    if (model.getCustomizationConfig().getUtilitiesMethod() != null) {
        classBuilder.addMethod(utilitiesMethod());
    }

    model.getEndpointOperation().ifPresent(
        o -> classBuilder.addField(EndpointDiscoveryRefreshCache.class, "endpointDiscoveryCache", PRIVATE));

    return classBuilder.build();
}
 
Example 7
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 8
Source File: ArgumentBuilderModel.java    From Akatsuki with Apache License 2.0 4 votes vote down vote up
@Override
public void build(PartialModel model, Builder builderTypeBuilder,
		SimpleBundleContext bundleContext, List<FieldModel> fields,
		Optional<SourceClassModel> superClass) {

	// TODO what if out target class has some generic parameter of
	// <A,B...>?

	TypeName builderClassName = ParameterizedTypeName.get(info.toClassName(), T, var("BT"));

	builderTypeBuilder.addTypeVariable(TypeVariableName.get("T", model.targetClassName));

	builderTypeBuilder.addTypeVariable(TypeVariableName.get("BT", builderClassName));

	if (superClass.isPresent()) {
		// implement our parent

		ClassInfo superClassInfo = superClass.get().asClassInfo();
		if (enclosingClass.isPresent())
			superClassInfo = superClassInfo.withEnclosingClasses(enclosingClass.get());

		superClassInfo = superClassInfo.withNameTransform(BUILDER_NAME_FUNCTION);

		ClassName superClassName = superClassInfo.toClassName();

		builderTypeBuilder
				.superclass(ParameterizedTypeName.get(superClassName, T, var("BT")));
	} else {
		// or inherit the class containing our build method
		builderTypeBuilder.superclass(model.concludingBuilderTypeName());
	}

	builderTypeBuilder.addMethod(
			MethodSpec.constructorBuilder().addParameter(bundleTypeName, "bundle")
					.addCode("super(bundle, $L.class);", model.targetClassName).build());

	// if (!superClass.isPresent()) {
	// we are the first!
	builderTypeBuilder.addMethod(MethodSpec.constructorBuilder()
			.addParameter(bundleTypeName, "bundle").addParameter(Class.class, "clazz")
			.addCode("super(bundle, clazz);").addModifiers(Modifier.PUBLIC).build())
			.build();
	// }

	CodeBlock.Builder block = CodeBlock.builder();

	// enable check if runtime check is required and whether the class
	// contains non-optional fields at all
	boolean appendCheck = model.config.type().check == Check.RUNTIME
			&& fields.stream().anyMatch(f -> !f.annotation(Arg.class).get().optional());

	if (appendCheck) {
		block.addStatement("$T<$T> missing = new $T<>()", Set.class, String.class,
				HashSet.class);
	}

	for (FieldModel field : fields) {
		Arg arg = field.annotation(Arg.class).get();

		Element<TypeMirror> element = new Element<>(field);
		String setterName = arg.value();
		if (Strings.isNullOrEmpty(setterName)) {
			setterName = field.name();
			// TODO allow and apply field name transform here
		}
		CascadingTypeAnalyzer<?, ? extends TypeMirror, ? extends Analysis> analyzer = context
				.resolver().resolve(element);
		Analysis analysis = analyzer.transform(bundleContext, element, InvocationType.SAVE);

		MethodSpec.Builder setterBuilder = MethodSpec.methodBuilder(setterName)
				.addModifiers(Modifier.PUBLIC)
				.addParameter(ClassName.get(field.type()), setterName)
				.addCode(analysis.emit());
		setBuilderReturnSpec(var("BT"), setterBuilder);
		builderTypeBuilder.addMethod(setterBuilder.build());

		if (appendCheck && !arg.optional()) {
			block.addStatement("if(!bundle.containsKey($1S)) missing.add($1S)", setterName);
		}

	}

	if (appendCheck) {
		block.addStatement("if(missing.isEmpty()) throw new RuntimeException(\"Some or "
				+ "all of the non-optional values \"+missing+\" not set!\")");
		MethodSpec.Builder checkMethodBuilder = MethodSpec.methodBuilder("check")
				.addModifiers(Modifier.PUBLIC).returns(Void.TYPE).addCode(block.build());
		builderTypeBuilder.addMethod(checkMethodBuilder.build());
	}

}
 
Example 9
Source File: ArgumentBuilderModel.java    From Akatsuki with Apache License 2.0 4 votes vote down vote up
@Override
public void build(PartialModel model, Builder builderTypeBuilder,
		SimpleBundleContext bundleContext, List<FieldModel> fields,
		Optional<SourceClassModel> superClass) {

	// last field returns a concluding builder
	TypeName previousName = model.concludingBuilderTypeName();

	// last to first
	int last = fields.size() - 1;
	for (int i = last; i >= 0; i--) {
		FieldModel field = fields.get(i);
		Arg arg = field.annotation(Arg.class).get();

		Element<TypeMirror> element = new Element<>(field);
		String setterName = arg.value();
		if (Strings.isNullOrEmpty(setterName)) {
			setterName = field.name();
			// TODO allow and apply field name transform here
		}

		CascadingTypeAnalyzer<?, ? extends TypeMirror, ? extends Analysis> analyzer = context
				.resolver().resolve(element);
		Analysis analysis = analyzer.transform(bundleContext, element, InvocationType.SAVE);

		MethodSpec.Builder setterBuilder = MethodSpec.methodBuilder(setterName)
				.addModifiers(Modifier.PUBLIC)
				.addParameter(ClassName.get(field.type()), setterName)
				.addCode(analysis.emit()).returns(previousName);

		if (i == 0) {
			// entry point is a method
			if (i == last) {
				setterBuilder.addCode("return new $T($L, $L);", previousName, "bundle()",
						"targetClass()");
			} else {
				setterBuilder.addCode("return new $T();", previousName);

			}

			builderTypeBuilder.addMethod(setterBuilder.build());

			// we're almost done
			// if the first field is optional, the whole builder can be
			// concluded without any setter, otherwise, implement our
			// base arg builder
			builderTypeBuilder.superclass(arg.optional() ? model.concludingBuilderTypeName()
					: ParameterizedTypeName.get(
							ClassName.get(Internal.ClassArgBuilder.class),
							model.targetClassName));

			model.extendConcludingBuilder(context, builderTypeBuilder);

		} else {
			// start chaining
			Builder builder = TypeSpec
					.classBuilder(Utils.toCapitalCase(setterName) + "Builder")
					.addModifiers(Modifier.PUBLIC);

			if (arg.optional())
				builder.superclass(previousName);
			if (i == last) {
				if (arg.optional()) {
					// last optional field builder needs to implement
					// concluding
					// builder
					builder.addMethod(MethodSpec.constructorBuilder()
							.addCode("super($1L" + ".this" + ".$2L, " + "$1L.this.$3L);",
									model.builderSimpleName, "bundle()", "targetClass()")
							.build());
					setterBuilder.addCode("return this;");
				} else {
					// last non optional field builder needs to return a
					// new
					// concluding builder
					setterBuilder.addCode("return new $T($L, $L);", previousName,
							"bundle" + "()", "targetClass()");
				}
			} else {
				// everything in between returns the next builder
				setterBuilder.addCode("return new $T();", previousName);
			}

			builder.addMethod(setterBuilder.build());

			TypeSpec typeSpec = builder.build();
			builderTypeBuilder.addType(typeSpec);

			previousName = model.get(typeSpec.name);
		}
	}

}