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.
Example 1
Project: EasyRouter   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
Project: Android-Router   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
Project: nalu   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
Project: web3j   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
Project: toothpick   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
Project: caffeine   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
Project: auto   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
Project: Briefness   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
Project: client-sdk-java   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)));


    //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
Project: Intimate   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
Project: DaggerAutoInject   File: DaggerAutoInjectProcessor.java    License: Apache License 2.0 6 votes vote down vote up
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
Project: soabase-halva   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
Project: aws-sdk-java-v2   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
Project: AirData   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
Project: ApiManager   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
Project: soabase-halva   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
Project: etherscan-explorer   File: AbiTypesGenerator.java    License: GNU General Public License v3.0 5 votes vote down vote up
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
Project: etherscan-explorer   File: AbiTypesMapperGenerator.java    License: GNU General Public License v3.0 5 votes vote down vote up
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
Project: servicetalk   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
Project: raml-java-tools   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
Project: sqlitemagic   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
Project: jackdaw   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
Project: aws-sdk-java-v2   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
Project: spring-init   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
Project: aws-sdk-java-v2   File: ClientSimpleMethodsIntegrationTests.java    License: Apache License 2.0 5 votes vote down vote up
@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
Project: auto   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
Project: vault   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
Project: aws-sdk-java-v2   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
Project: Barricade   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
Project: kripton   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);
	}

}
 
Example 31
Project: paperparcel   File: PaperParcelWriter.java    License: Apache License 2.0 5 votes vote down vote up
final TypeSpec.Builder write() {
  ClassName className = ClassName.get(descriptor.element());
  return TypeSpec.classBuilder(name)
      .addModifiers(FINAL)
      .addFields(adapterDependencies(descriptor.adapters().values()))
      .addField(creator(className))
      .addMethod(writeToParcel(className))
      .addMethod(MethodSpec.constructorBuilder().addModifiers(PRIVATE).build());
}
 
Example 32
Project: crnk-framework   File: CrnkProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private void addPathConstants(TypeElement resourceType, TypeSpec.Builder typeBuilder) {
    TypeName typeName = ClassName.bestGuess(getSimpleName(resourceType, false));
    String name = firstToLower(getSimpleName(resourceType.getSimpleName().toString(), false));

    FieldSpec.Builder fieldBuilder = FieldSpec.builder(typeName, name, Modifier.STATIC, Modifier.PUBLIC);
    fieldBuilder.initializer("new " + typeName.toString() + "()");
    typeBuilder.addField(fieldBuilder.build());
}
 
Example 33
Project: litho   File: MatcherGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private static <T extends SpecModel & HasEnclosedSpecModel> MethodSpec generateBuildMethod(
    final T specModel) {
  final MethodSpec.Builder buildMethodBuilder =
      MethodSpec.methodBuilder("build")
          .addModifiers(Modifier.PUBLIC)
          .returns(getMatcherConditionTypeName());

  final CodeBlock innerMatcherLogicBlock = generateMatchMethodBody(specModel);

  final TypeSpec matcherInnerClass =
      TypeSpec.anonymousClassBuilder("")
          .superclass(getMatcherConditionTypeName())
          .addMethod(
              MethodSpec.methodBuilder("matches")
                  .addModifiers(Modifier.PUBLIC)
                  .addParameter(ClassNames.INSPECTABLE_COMPONENT, "value")
                  .returns(TypeName.BOOLEAN)
                  .addAnnotation(Override.class)
                  .addCode(innerMatcherLogicBlock)
                  .build())
          .build();

  return buildMethodBuilder
      .addStatement("final $T mainBuilder = $L", getMatcherConditionTypeName(), matcherInnerClass)
      .addStatement(
          "return $T.allOf(mainBuilder, $T.buildCommonMatcher(this))",
          ClassNames.ASSERTJ_JAVA6ASSERTIONS,
          ClassNames.BASE_MATCHER_BUILDER)
      .build();
}
 
Example 34
Project: RxAndroidOrm   File: QueryLoggerGenerator.java    License: Apache License 2.0 5 votes vote down vote up
public TypeSpec generate() {
    return TypeSpec.interfaceBuilder(Constants.QUERY_LOGGER)
            .addModifiers(Modifier.PUBLIC)
            .addMethod(MethodSpec.methodBuilder("onQuery")
                    .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
                    .addParameter(ClassName.get(String.class), "query")
                    .addParameter(ArrayTypeName.get(String[].class), "datas")
                    .build())
            .build();
}
 
Example 35
Project: data-mediator   File: ImplInfo.java    License: Apache License 2.0 5 votes vote down vote up
public void addImplMethods(TypeSpec.Builder curBuilder){
      for(MethodInfo info : getMethodInfo()){
          MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(info.getMethodName())
                  .addModifiers(Modifier.PUBLIC)
                  .returns(info.getReturnType());

          final List<ParamInfo> paramInfos = info.getParamInfos();
          final Object[] params = new Object[ 3 + paramInfos.size()]; //implClass + implName + module + dependProp + other params.
          params[0] = info.getImplClass().getTypeName();
          params[1] = info.getImplMethodName();
          params[2] = "this";

          StringBuilder sb = new StringBuilder();
          sb.append( "$T.$N( $N " );

          if(!paramInfos.isEmpty()){
              int i = 3;
              for (ParamInfo pInfo : paramInfos){
                  sb.append(", ").append("$N");
                  params[i++] = pInfo.paramName;
                  methodBuilder.addParameter(pInfo.paramType, pInfo.paramName);
              }
          }
          sb.append(")");
          if(info.isReturnVoid()){
              methodBuilder.addStatement(sb.toString(), params);
          }else{
              methodBuilder.addStatement("return " + sb.toString(), params);
          }
          curBuilder.addMethod(methodBuilder.build());
      }
}
 
Example 36
Project: spring-data-jpa-entity-graph   File: NodeComposer.java    License: MIT License 5 votes vote down vote up
public NodeComposer() {
  rootType = TypeVariableName.get("R");

  FieldSpec rootField =
      FieldSpec.builder(rootType, Constants.PATH_SEPARATOR)
          .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
          .build();

  ParameterizedTypeName listOfString = ParameterizedTypeName.get(List.class, String.class);

  FieldSpec pathField =
      FieldSpec.builder(listOfString, "path")
          .addModifiers(Modifier.PRIVATE, Modifier.FINAL)
          .build();

  MethodSpec constructor =
      MethodSpec.constructorBuilder()
          .addModifiers(Modifier.PUBLIC)
          .addParameter(rootType, "root")
          .addParameter(listOfString, "path")
          .addStatement("this.____ = root")
          .addStatement("this.path = path")
          .build();

  typeSpecBuilder =
      TypeSpec.classBuilder(SIMPLE_NAME)
          .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
          .addTypeVariable(rootType)
          .addField(rootField)
          .addField(pathField)
          .addMethod(constructor);
}
 
Example 37
Project: componentrouter   File: MethodRouterGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 添加构造方法
 * @param builder
 * @param routeType
 */
private void addConstructorMethod(TypeSpec.Builder builder, ClassName routeType) {
    MethodSpec.Builder methodBuilder = MethodSpec.constructorBuilder()
            .addParameter(routeType, "obj")
            .addModifiers(Modifier.PUBLIC)
            .addCode(PROXY_FIELD_NAME + "=obj;\n");
    builder.addMethod(methodBuilder.build());
}
 
Example 38
Project: componentrouter   File: MethodRouterGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *
 * is() 方法
 * @param builder
 * @param routeType
 */
private void addIsForMethod(TypeSpec.Builder builder, ClassName routeType) {
    MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(METHOD_IS)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL, Modifier.STATIC)
            .returns(boolean.class)
            .addParameter(Object.class, "obj")
            .addCode("return $T.class==obj.getClass();\n", routeType);
    builder.addMethod(methodBuilder.build());
}
 
Example 39
Project: auto-value-with   File: AutoValueWithExtension.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String generateClass(
        Context context, String className, String classToExtend, boolean isFinal) {
    TypeSpec subclass =
            newTypeSpecBuilder(context, className, classToExtend, isFinal)
                    .addMethods(generateWithMethods(context))
                    .build();

    return JavaFile.builder(context.packageName(), subclass).build().toString();
}
 
Example 40
Project: react-native-GPay   File: ReactPropertyProcessor.java    License: MIT License 5 votes vote down vote up
private void generateCode(ClassInfo classInfo, List<PropertyInfo> properties)
    throws IOException, ReactPropertyException {
  MethodSpec getMethods = MethodSpec.methodBuilder("getProperties")
      .addModifiers(PUBLIC)
      .addAnnotation(Override.class)
      .addParameter(PROPERTY_MAP_TYPE, "props")
      .returns(TypeName.VOID)
      .addCode(generateGetProperties(properties))
      .build();

  TypeName superType = getSuperType(classInfo);
  ClassName className = classInfo.mClassName;

  String holderClassName =
      getClassName((TypeElement) classInfo.mElement, className.packageName()) + "$$PropsSetter";
  TypeSpec holderClass = TypeSpec.classBuilder(holderClassName)
      .addSuperinterface(superType)
      .addModifiers(PUBLIC)
      .addMethod(generateSetPropertySpec(classInfo, properties))
      .addMethod(getMethods)
      .build();

  JavaFile javaFile = JavaFile.builder(className.packageName(), holderClass)
      .addFileComment("Generated by " + getClass().getName())
      .build();

  javaFile.writeTo(mFiler);
}