Java Code Examples for com.squareup.javapoet.TypeSpec

The following examples show how to use com.squareup.javapoet.TypeSpec. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: EasyRouter   Source File: InterceptorProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private TypeSpec getInterceptorInitializer(Set<? extends Element> interceptorElements) throws ClassNotFoundException {
    ClassName interceptor = ClassName.get("com.android.easyrouter.intercept", "IInterceptor");
    ClassName list = ClassName.get("java.util", "List");
    TypeName interceptorList = ParameterizedTypeName.get(list, interceptor);

    MethodSpec.Builder routerInitBuilder = MethodSpec
            .methodBuilder("initModuleInterceptor")
            .returns(interceptorList)
            .addModifiers(Modifier.PUBLIC)
            .addModifiers(Modifier.STATIC);
    routerInitBuilder.addStatement("List<IInterceptor> list = new java.util.ArrayList()");
    for (Element element : interceptorElements) {
        routerInitBuilder.addStatement("list.add(new $T())",
                ClassName.get((TypeElement) element));
    }
    routerInitBuilder.addStatement("return list");

    return TypeSpec.classBuilder(CompilerConstant.AutoCreateInterceptorPrefix + moduleName)
            .addModifiers(Modifier.PUBLIC)
            .addMethod(routerInitBuilder.build())
            .build();
}
 
Example 2
Source Project: Android-Router   Source File: RegisterRouterProcessor.java    License: MIT License 6 votes vote down vote up
private void generateRouterRule(List<RouterModule> moduleList) {
	System.out.println("moduleList = " + Arrays.toString(moduleList.toArray()));
	try {
		String pkgName = CompilerHelper.ROUTER_MANAGER_TABLE_PKN;
		String className = CompilerHelper.ROUTER_MANAGER_TABLE_CLASS_NAME + moduleList.get(0).module;
		String methodName = CompilerHelper.ROUTER_MANAGER_TABLE_METHOD_NAME;
		MethodSpec registerRouter = computeRouterTable(methodName, moduleList);

		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 3
Source Project: nalu   Source File: ApplicationGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private void generateLoadDefaultsRoutes(TypeSpec.Builder typeSpec,
                                        MetaModel metaModel) {
  typeSpec.addMethod(MethodSpec.methodBuilder("loadDefaultRoutes")
                               .addModifiers(Modifier.PUBLIC)
                               .addAnnotation(Override.class)
                               .addStatement("$T sb01 = new $T()",
                                             ClassName.get(StringBuilder.class),
                                             ClassName.get(StringBuilder.class))
                               .addStatement("this.startRoute = $S",
                                             metaModel.getStartRoute())
                               .addStatement("sb01.append(\"found startRoute >>$L<<\")",
                                             metaModel.getStartRoute())
                               .addStatement("$T.get().logDetailed(sb01.toString(), 2)",
                                             ClassName.get(ClientLogger.class))
                               .addStatement("sb01.setLength(0)")
                               .addStatement("$T.get().logDetailed(sb01.toString(), 2)",
                                             ClassName.get(ClientLogger.class))
                               .build());
}
 
Example 4
Source Project: web3j   Source File: SolidityFunctionWrapperTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildFuncNameConstants() throws Exception {
    AbiDefinition functionDefinition =
            new AbiDefinition(
                    false,
                    Arrays.asList(new AbiDefinition.NamedType("param", "uint8")),
                    "functionName",
                    Collections.emptyList(),
                    "function",
                    true);
    TypeSpec.Builder builder = TypeSpec.classBuilder("testClass");

    builder.addFields(
            solidityFunctionWrapper.buildFuncNameConstants(
                    Collections.singletonList(functionDefinition)));

    String expected =
            "class testClass {\n"
                    + "  public static final java.lang.String FUNC_FUNCTIONNAME = \"functionName\";\n"
                    + "}\n";

    assertEquals(builder.build().toString(), (expected));
}
 
Example 5
Source Project: toothpick   Source File: FactoryGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private void emitSuperMemberInjectorFieldIfNeeded(TypeSpec.Builder scopeMemberTypeSpec) {
  if (constructorInjectionTarget.superClassThatNeedsMemberInjection != null) {
    ClassName superTypeThatNeedsInjection =
        ClassName.get(constructorInjectionTarget.superClassThatNeedsMemberInjection);
    ParameterizedTypeName memberInjectorSuperParameterizedTypeName =
        ParameterizedTypeName.get(
            ClassName.get(MemberInjector.class), superTypeThatNeedsInjection);
    FieldSpec.Builder superMemberInjectorField =
        FieldSpec.builder(
                memberInjectorSuperParameterizedTypeName, "memberInjector", Modifier.PRIVATE)
            // TODO use proper typing here
            .initializer(
                "new $L__MemberInjector()",
                getGeneratedFQNClassName(
                    constructorInjectionTarget.superClassThatNeedsMemberInjection));
    scopeMemberTypeSpec.addField(superMemberInjectorField.build());
  }
}
 
Example 6
Source Project: caffeine   Source File: NodeFactoryGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private void writeJavaFile() throws IOException {
  String header = Resources.toString(Resources.getResource("license.txt"), UTF_8).trim();
  JavaFile.builder(getClass().getPackage().getName(), nodeFactory.build())
      .addFileComment(header, Year.now(timeZone))
      .indent("  ")
      .build()
      .writeTo(directory);

  for (TypeSpec node : nodeTypes) {
    JavaFile.builder(getClass().getPackage().getName(), node)
            .addFileComment(header, Year.now(timeZone))
            .indent("  ")
            .build()
            .writeTo(directory);
  }
}
 
Example 7
Source Project: auto   Source File: SerializableAutoValueExtension.java    License: Apache License 2.0 6 votes vote down vote up
private String generate() {
  ClassName superclass = ClassName.get(context.packageName(), classToExtend);
  Optional<AnnotationSpec> generatedAnnotationSpec =
      GeneratedAnnotationSpecs.generatedAnnotationSpec(
          context.processingEnvironment().getElementUtils(),
          context.processingEnvironment().getSourceVersion(),
          SerializableAutoValueExtension.class);

  TypeSpec.Builder subclass =
      TypeSpec.classBuilder(className)
          .superclass(getClassTypeName(superclass, typeVariableNames))
          .addTypeVariables(typeVariableNames)
          .addModifiers(isFinal ? Modifier.FINAL : Modifier.ABSTRACT)
          .addMethod(constructor())
          .addMethod(writeReplace())
          .addType(proxyGenerator.generate());
  generatedAnnotationSpec.ifPresent(subclass::addAnnotation);

  return JavaFile.builder(context.packageName(), subclass.build()).build().toString();
}
 
Example 8
Source Project: Briefness   Source File: FinalRClassBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private static void addResourceField(TypeSpec.Builder resourceType, VariableDeclarator variable,
                                     ClassName annotation) {
  String fieldName = variable.getNameAsString();
  String fieldValue = variable.getInitializer()
      .map(Node::toString)
      .orElseThrow(
          () -> new IllegalStateException("Field " + fieldName + " missing initializer"));
  FieldSpec.Builder fieldSpecBuilder = FieldSpec.builder(int.class, fieldName)
      .addModifiers(PUBLIC, STATIC, FINAL)
      .initializer(fieldValue);

  if (annotation != null) {
    fieldSpecBuilder.addAnnotation(annotation);
  }

  resourceType.addField(fieldSpecBuilder.build());
}
 
Example 9
@Test
public void testBuildFuncNameConstants() throws Exception {
    AbiDefinition functionDefinition = new AbiDefinition(
            false,
            Arrays.asList(
                    new AbiDefinition.NamedType("param", "uint8")),
            "functionName",
            Collections.emptyList(),
            "function",
            true);
    TypeSpec.Builder builder = TypeSpec.classBuilder("testClass");

    builder.addFields(solidityFunctionWrapper
            .buildFuncNameConstants(Collections.singletonList(functionDefinition)));


    //CHECKSTYLE:OFF
    String expected =
            "class testClass {\n" +
                    "  public static final java.lang.String FUNC_FUNCTIONNAME = \"functionName\";\n" +
                    "}\n";
    //CHECKSTYLE:ON


    assertThat(builder.build().toString(), is(expected));
}
 
Example 10
Source Project: Intimate   Source File: GenerateSystemCode.java    License: Apache License 2.0 6 votes vote down vote up
public JavaFile generate() {
    MethodSpec.Builder construction = MethodSpec.constructorBuilder()
            .addModifiers(Modifier.PUBLIC)
            .addException(ClassNotFoundException.class)
            .addParameter(Object.class, "object");
    if (model.getTargetName().fullName.contains("$") || model.isNeedForName()) {
        construction.addStatement("this.mObject = object")
                .addStatement("this.mClass = Class.forName($S)", model.getTargetName().fullName);
    } else {
        construction.addStatement("this.mObject = object")
                .addStatement("this.mClass = $N.class", model.getTargetName().fullName);
    }

    TypeSpec.Builder implClass = TypeSpec.classBuilder(model.getImplClassName())
            .addModifiers(Modifier.PUBLIC)
            .addSuperinterface(model.getInterfaceName().typeName)
            .addMethod(construction.build())
            .addField(Object.class, "mObject")
            .addField(Class.class, "mClass");

    generateFiled(implClass, model.getFieldList());
    generateMethod(implClass, model.getMethodList());

    return JavaFile.builder(INTIMATE_PACKAGE, implClass.build()).build();
}
 
Example 11
private void constructFragmentModule() {
    final TypeSpec.Builder builder = TypeSpec.classBuilder(Constants.FRAGMENT_MODULE)
            .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
            .addAnnotation(Constants.DAGGER_MODULE);

    for (FragmentHolder fragmentHolder : fragmentHolders.values()) {
        builder.addMethod(MethodSpec.methodBuilder(Constants.METHOD_CONTRIBUTE + fragmentHolder.className)
                .addAnnotation(Constants.DAGGER_ANDROID_ANNOTATION)
                .addModifiers(Modifier.ABSTRACT)
                .returns(fragmentHolder.classNameComplete)
                .build()
        );
    }

    final TypeSpec newClass = builder.build();
    final JavaFile javaFile = JavaFile.builder(Constants.PACKAGE_NAME, newClass).build();

    try {
        javaFile.writeTo(System.out);
        javaFile.writeTo(filer);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 12
Source Project: soabase-halva   Source File: PassCreate.java    License: Apache License 2.0 6 votes vote down vote up
private void addTypeAliasType(TypeSpec.Builder builder, ClassName aliasClassName, DeclaredType parentType)
{
    TypeName parentTypeName = ClassName.get(parentType);
    ClassName typeAliasTypeName = ClassName.get(TypeAliasType.class);
    ClassName anyTypeName = ClassName.get(AnyType.class);
    ParameterizedTypeName typeName = ParameterizedTypeName.get(typeAliasTypeName, parentTypeName, aliasClassName);

    CodeBlock codeBlock = CodeBlock.builder()
        .add(
            "new $T<>(new $T<$T>(){}, new $T<$T>(){}, $L::$L)",
            typeAliasTypeName,
            anyTypeName,
            parentTypeName,
            anyTypeName,
            aliasClassName,
            aliasClassName.simpleName(),
            aliasClassName.simpleName()
            )
        .build();

    FieldSpec fieldSpec = FieldSpec.builder(typeName, "TypeAliasType", Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
        .initializer(codeBlock)
        .build();
    builder.addField(fieldSpec);
}
 
Example 13
Source Project: aws-sdk-java-v2   Source File: AsyncClientInterface.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public TypeSpec poetSpec() {
    TypeSpec.Builder result = PoetUtils.createInterfaceBuilder(className);

    result.addSuperinterface(SdkClient.class)
          .addField(FieldSpec.builder(String.class, "SERVICE_NAME")
                             .addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
                             .initializer("$S", model.getMetadata().getSigningName())
                             .build());

    PoetUtils.addJavadoc(result::addJavadoc, getJavadoc());

    if (!model.getCustomizationConfig().isExcludeClientCreateMethod()) {
        result.addMethod(create());
    }

    result.addMethod(builder())
          .addMethods(operationsAndSimpleMethods());

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

    return result.build();
}
 
Example 14
Source Project: AirData   Source File: DatabaseHelperCreator.java    License: MIT License 6 votes vote down vote up
private MethodSpec generateDeleteByIdMethod(TypeSpec.Builder typeSpecBuilder) {
    MethodSpec.Builder saveMethodBuidler = MethodSpec.methodBuilder("delete")
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC)
            .returns(TypeName.INT)
            .addParameter(ClassName.get(Object.class), "bean");

    for (TableInfo table : tables) {

        String daoField = table.getDaoClassName().replace("$$", "").toLowerCase();

        MethodSpec methodSpec = MethodSpec.methodBuilder("delete")
                .addModifiers(Modifier.PUBLIC)
                .returns(TypeName.INT)
                .addParameter(ClassName.get(table.getPackageName(), table.getClassName()), "bean")
                .addStatement("return $L.delete(bean)", daoField)
                .build();
        typeSpecBuilder.addMethod(methodSpec);

        saveMethodBuidler.addStatement("if(bean instanceof $L) return delete(($L)bean)", table.getClassName(), table.getClassName());
    }

    saveMethodBuidler.addStatement("return 0");
    return saveMethodBuidler.build();
}
 
Example 15
Source Project: ApiManager   Source File: ApiImplProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private TypeSpec buildClass(ApiContract<ClassName> apiNameContract) {
    return TypeSpec.classBuilder(apiNameContract.getApi().simpleName() + ApiConstants.SEPARATOR + ApiConstants.CONTRACT)
            .addSuperinterface(ClassName.get(elements.getTypeElement(ApiConstants.INTERFACE_NAME_CONTRACT)))
            .addModifiers(Modifier.PUBLIC)
            .addMethod(buildMethod(apiNameContract))
            .build();
}
 
Example 16
Source Project: soabase-halva   Source File: PassCreate.java    License: Apache License 2.0 5 votes vote down vote up
private void addImplicitItem(TypeSpec.Builder builder, ImplicitSpec spec, FoundImplicit foundImplicit, TypeMirror implicitInterface, ExecutableElement method)
{
    MethodSpec.Builder methodSpecBuilder = MethodSpec.overriding(method);
    if ( method.getReturnType().getKind() == TypeKind.TYPEVAR )
    {
        DeclaredType declaredType = (DeclaredType)implicitInterface;
        if ( declaredType.getTypeArguments().size() == 1 )
        {
            methodSpecBuilder.returns(ClassName.get(declaredType.getTypeArguments().get(0)));
        }
    }

    CodeBlock.Builder codeBlockBuilder = CodeBlock.builder();
    if ( method.getReturnType().getKind() != TypeKind.VOID )
    {
        codeBlockBuilder.add("return ");
    }
    codeBlockBuilder.add(new ImplicitValue(environment, spec, contextItems, foundImplicit).build());
    codeBlockBuilder.add(".$L(", method.getSimpleName());

    AtomicBoolean isFirst = new AtomicBoolean(true);
    method.getParameters().forEach(parameter -> {
        if ( !isFirst.compareAndSet(true, false) )
        {
            codeBlockBuilder.add(", ");
        }
        codeBlockBuilder.add(parameter.getSimpleName().toString());
    });

    methodSpecBuilder.addCode(codeBlockBuilder.addStatement(")").build());
    builder.addMethod(methodSpecBuilder.build());
}
 
Example 17
private <T extends Type> void generateStaticArrayTypes(
        Class<T> superclass, String path) throws IOException {
    String packageName = createPackageName(superclass);
    ClassName className;

    for (int length = 1; length <= StaticArray.MAX_SIZE_OF_STATIC_ARRAY; length++) {

        TypeVariableName typeVariableName = TypeVariableName.get("T").withBounds(Type.class);

        MethodSpec constructorSpec = MethodSpec.constructorBuilder()
                .addModifiers(Modifier.PUBLIC)
                .addParameter(ParameterizedTypeName.get(ClassName.get(List.class),
                        typeVariableName), "values")
                .addStatement("super($L, $N)", length, "values")
                .build();

        MethodSpec arrayOverloadConstructorSpec = MethodSpec.constructorBuilder()
                .addAnnotation(SafeVarargs.class)
                .addModifiers(Modifier.PUBLIC)
                .addParameter(ArrayTypeName.of(typeVariableName), "values")
                .varargs()
                .addStatement("super($L, $N)", length, "values")
                .build();

        className = ClassName.get(packageName, superclass.getSimpleName() + length);

        TypeSpec bytesType = TypeSpec
                .classBuilder(className.simpleName())
                .addTypeVariable(typeVariableName)
                .addJavadoc(CODEGEN_WARNING)
                .superclass(ParameterizedTypeName.get(ClassName.get(superclass),
                        typeVariableName))
                .addModifiers(Modifier.PUBLIC)
                .addMethods(Arrays.asList(constructorSpec, arrayOverloadConstructorSpec))
                .build();

        write(packageName, bytesType, path);
    }
}
 
Example 18
private void generate(String destinationDir) throws IOException {

        String typesPackageName = "org.web3j.abi.datatypes";
        String autoGeneratedTypesPackageName = typesPackageName + ".generated";

        MethodSpec.Builder builder = MethodSpec.methodBuilder("getType")
                .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                .addParameter(String.class, TYPE)
                .returns(
                        ParameterizedTypeName.get(ClassName.get(Class.class),
                                WildcardTypeName.subtypeOf(Object.class))
                )
                .beginControlFlow("switch (type)");

        builder = addTypes(builder, typesPackageName);
        builder = addGeneratedTypes(builder, autoGeneratedTypesPackageName);
        builder = builder.addStatement("default:\nthrow new $T($S\n+ $N)",
                UnsupportedOperationException.class,
                "Unsupported type encountered: ", TYPE);
        builder.endControlFlow();

        MethodSpec methodSpec = builder.build();

        MethodSpec constructorSpec = MethodSpec.constructorBuilder()
                .addModifiers(Modifier.PRIVATE)
                .build();

        TypeSpec typeSpec = TypeSpec
                .classBuilder("AbiTypes")
                .addJavadoc(buildWarning(AbiTypesMapperGenerator.class))
                .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
                .addMethod(constructorSpec)
                .addMethod(methodSpec)
                .build();

        write(autoGeneratedTypesPackageName, typeSpec, destinationDir);
    }
 
Example 19
Source Project: servicetalk   Source File: Generator.java    License: Apache License 2.0 5 votes vote down vote up
private TypeSpec newDefaultClientClassSpec(final State state, final ClassName defaultClientClass,
                                           final ClassName defaultBlockingClientClass) {
    final TypeSpec.Builder typeSpecBuilder = classBuilder(defaultClientClass)
            .addModifiers(PRIVATE, STATIC, FINAL)
            .addSuperinterface(state.clientClass)
            .addField(GrpcClientCallFactory, factory, PRIVATE, FINAL)
            .addMethod(methodBuilder("asBlockingClient")
                    .addModifiers(PUBLIC)
                    .addAnnotation(Override.class)
                    .returns(state.blockingClientClass)
                    // TODO: Cache client
                    .addStatement("return new $T($L)", defaultBlockingClientClass, factory)
                    .build())
            .addMethod(newDelegatingMethodSpec(executionContext, factory, GrpcExecutionContext, null))
            .addMethod(newDelegatingCompletableMethodSpec(onClose, factory))
            .addMethod(newDelegatingCompletableMethodSpec(closeAsync, factory))
            .addMethod(newDelegatingCompletableMethodSpec(closeAsyncGracefully, factory))
            .addMethod(newDelegatingCompletableToBlockingMethodSpec(close, closeAsync, factory))
            .addMethod(newDelegatingCompletableToBlockingMethodSpec(closeGracefully, closeAsyncGracefully,
                    factory));

    final MethodSpec.Builder constructorBuilder = constructorBuilder()
            .addModifiers(PRIVATE)
            .addParameter(GrpcClientCallFactory, factory, FINAL)
            .addStatement("this.$N = $N", factory, factory);

    addClientFieldsAndMethods(state, typeSpecBuilder, constructorBuilder, false);

    typeSpecBuilder.addMethod(constructorBuilder.build());
    return typeSpecBuilder.build();
}
 
Example 20
Source Project: raml-java-tools   Source File: ConstructorExtension.java    License: Apache License 2.0 5 votes vote down vote up
private TypeName findField(final TypeSpec clazz, final TypeDeclaration field) {
	for (FieldSpec fieldSpec : clazz.fieldSpecs) {
		if (Objects.equals(field.name(), fieldSpec.name)) {
			return fieldSpec.type;
		}
	}
	throw new IllegalArgumentException("There is no field of name: " + field.name());
}
 
Example 21
Source Project: sqlitemagic   Source File: ModelPersistingGenerator.java    License: Apache License 2.0 5 votes vote down vote up
static void addMethodInternalCallOnComplexColumnsIfNeeded(TypeSpec.Builder daoClassBuilder,
                                                          EntityEnvironment entityEnvironment,
                                                          String methodName,
                                                          ReturnCallback<String, ColumnElement> callableMethodCallback,
                                                          ParameterSpec... params) {
  addMethodInternalCallOnComplexColumnsIfNeeded(daoClassBuilder, entityEnvironment, methodName,
      new ReturnCallback2<String, ParameterSpec, ColumnElement>() {
        @Override
        public String call(ParameterSpec param, ColumnElement columnElement) {
          return param.name;
        }
      },
      callableMethodCallback, params);
}
 
Example 22
Source Project: jackdaw   Source File: JAdapterCodeGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void addMethod(
    final TypeSpec.Builder builder, final ExecutableElement element
) {
    final TypeMirror returnType = element.getReturnType();
    final List<? extends VariableElement> parameters = element.getParameters();
    final String methodName = TypeUtils.getName(element);

    final Set<Modifier> modifiers = Sets.newHashSet(element.getModifiers());
    modifiers.remove(Modifier.ABSTRACT);
    final Modifier[] methodModifiers = modifiers.toArray(new Modifier[0]);

    final MethodSpec.Builder methodBuilder =
        MethodSpec.methodBuilder(methodName)
            .addModifiers(methodModifiers)
            .addAnnotation(Override.class)
            .returns(TypeName.get(returnType));

    final TypeKind returnTypeKind = returnType.getKind();
    if (returnTypeKind != TypeKind.VOID) {
        final String defaultValue = TypeUtils.getDefaultValue(returnTypeKind);
        methodBuilder.addStatement("return " + defaultValue);
    }

    for (final VariableElement parameter : parameters) {
        methodBuilder.addParameter(
            TypeUtils.getTypeName(parameter),
            TypeUtils.getName(parameter),
            Modifier.FINAL
        );
    }

    builder.addMethod(methodBuilder.build());
}
 
Example 23
Source Project: aws-sdk-java-v2   Source File: BaseExceptionClass.java    License: Apache License 2.0 5 votes vote down vote up
public TypeSpec builderInterface() {
    TypeSpec.Builder builder =
        TypeSpec.interfaceBuilder(baseExceptionClassName.nestedClass("Builder"))
                .addSuperinterface(ClassName.get(AwsServiceException.class).nestedClass("Builder"))
                .addModifiers(Modifier.PUBLIC)
                .addMethods(ExceptionProperties.builderInterfaceMethods(className().nestedClass("Builder")));

    return builder.build();
}
 
Example 24
Source Project: spring-init   Source File: SlimConfigurationProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private void write(TypeSpec type, String packageName) {
	JavaFile file = JavaFile.builder(packageName, type).build();
	try {
		file.writeTo(this.filer);
	}
	catch (IOException ex) {
		throw new IllegalStateException(ex);
	}
}
 
Example 25
@Override
public TypeSpec poetSpec() {
    ClassName interfaceClass = poetExtensions.getClientClass(model.getMetadata().getSyncInterface());

    TypeSpec.Builder builder = PoetUtils.createClassBuilder(className())
                                        .addModifiers(Modifier.PUBLIC)
                                        .addField(FieldSpec.builder(interfaceClass, "client")
                                                           .addModifiers(Modifier.PRIVATE, Modifier.STATIC)
                                                           .build())
                                        .addMethod(setup());

    model.simpleMethodsRequiringTesting().stream().map(this::simpleMethodsTest).forEach(builder::addMethod);

    return builder.build();
}
 
Example 26
Source Project: auto   Source File: FactoryWriter.java    License: Apache License 2.0 5 votes vote down vote up
private void addImplementationMethods(
    TypeSpec.Builder factory, FactoryDescriptor descriptor) {
  for (ImplementationMethodDescriptor methodDescriptor :
      descriptor.implementationMethodDescriptors()) {
    MethodSpec.Builder implementationMethod =
        methodBuilder(methodDescriptor.name())
            .addAnnotation(Override.class)
            .returns(TypeName.get(methodDescriptor.returnType()))
            .varargs(methodDescriptor.isVarArgs());
    if (methodDescriptor.publicMethod()) {
      implementationMethod.addModifiers(PUBLIC);
    }
    implementationMethod.addParameters(parameters(methodDescriptor.passedParameters()));
    implementationMethod.addStatement(
        "return create($L)",
        FluentIterable.from(methodDescriptor.passedParameters())
            .transform(
                new Function<Parameter, String>() {
                  @Override
                  public String apply(Parameter parameter) {
                    return parameter.name();
                  }
                })
            .join(ARGUMENT_JOINER));
    factory.addMethod(implementationMethod.build());
  }
}
 
Example 27
Source Project: vault   Source File: FieldsInjection.java    License: Apache License 2.0 5 votes vote down vote up
@Override TypeSpec.Builder getTypeSpecBuilder() {
  TypeSpec.Builder builder = TypeSpec.classBuilder(className.simpleName())
      .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
      .superclass(BaseFields.class);

  for (FieldMeta field : fields) {
    builder.addField(createFieldSpec(field));
  }

  return builder;
}
 
Example 28
Source Project: aws-sdk-java-v2   Source File: AwsServiceBaseRequestSpec.java    License: Apache License 2.0 5 votes vote down vote up
private TypeSpec builderImplSpec() {
    return TypeSpec.classBuilder("BuilderImpl")
            .addModifiers(Modifier.PROTECTED, Modifier.STATIC, Modifier.ABSTRACT)
            .addSuperinterface(className().nestedClass("Builder"))
            .superclass(ClassName.get(AwsRequest.class).nestedClass("BuilderImpl"))
            .addMethod(MethodSpec.constructorBuilder()
                    .addModifiers(Modifier.PROTECTED)
                    .build())
            .addMethod(MethodSpec.constructorBuilder()
                    .addModifiers(Modifier.PROTECTED)
                    .addParameter(className(), "request")
                    .addStatement("super(request)")
                    .build())
            .build();
}
 
Example 29
Source Project: Barricade   Source File: CodeGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private static TypeSpec generateEndpointsInnerClass(Set<String> endPoints) {
  TypeSpec.Builder classBuilder =
      classBuilder(ENDPOINTS_CLASS_NAME).addModifiers(PUBLIC, STATIC, FINAL);
  for (String endPoint : endPoints) {
    FieldSpec valuesField = FieldSpec.builder(String.class,
        StringUtils.removeAllSpecialCharacters(endPoint).toUpperCase())
        .addModifiers(PUBLIC, STATIC, FINAL)
        .initializer("$S", endPoint)
        .build();
    classBuilder.addField(valuesField);
  }
  return classBuilder.build();
}
 
Example 30
Source Project: kripton   Source File: SqlInsertBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Generate.
 *
 * @param classBuilder
 *            the class builder
 * @param method
 *            the method
 */
public static void generate(TypeSpec.Builder classBuilder, SQLiteModelMethod method) {
	InsertType insertResultType = detectInsertType(method);

	// if true, field must be associate to ben attributes
	TypeName returnType = method.getReturnClass();

	AssertKripton.failWithInvalidMethodSignException(insertResultType == null, method);

	// generate method code
	MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(method.getName()).addAnnotation(Override.class)
			.addModifiers(Modifier.PUBLIC);

	ParameterSpec parameterSpec;
	for (Pair<String, TypeName> item : method.getParameters()) {
		parameterSpec = ParameterSpec.builder(item.value1, item.value0).build();
		methodBuilder.addParameter(parameterSpec);
	}
	methodBuilder.returns(returnType);

	// fail if we use jql to INSERT_BEAN with operation of INSERT-FOR-SELECT
	// AssertKripton.failWithInvalidMethodSignException(insertResultType ==
	// InsertType.INSERT_BEAN && method.jql.containsSelectOperation, method,
	// "INSERT-FROM-SELECT SQL can not be used with method sign");

	// generate inner code
	methodBuilder.addComment("Specialized Insert - $L - BEGIN", insertResultType.getClass().getSimpleName());
	insertResultType.generate(classBuilder, methodBuilder, method, returnType);
	methodBuilder.addComment("Specialized Insert - $L - END", insertResultType.getClass().getSimpleName());

	MethodSpec methodSpec = methodBuilder.build();
	classBuilder.addMethod(methodSpec);

	if (method.contentProviderEntryPathEnabled) {
		// we need to generate insert for content provider to
		generateInsertForContentProvider(classBuilder, method, insertResultType);
	}

}