Java Code Examples for com.squareup.javapoet.TypeSpec#Builder

The following examples show how to use com.squareup.javapoet.TypeSpec#Builder . 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: IntentBuilderGenerator.java    From dart with Apache License 2.0 6 votes vote down vote up
@Override
public String brewJava() {
  TypeSpec.Builder intentBuilderTypeBuilder =
      TypeSpec.classBuilder(builderClassName()).addModifiers(Modifier.PUBLIC);

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

  //build
  JavaFile javaFile =
      JavaFile.builder(target.classPackage, intentBuilderTypeBuilder.build())
          .addFileComment("Generated code from Henson. Do not modify!")
          .addStaticImport(ActivityClassFinder.class, "getClassDynamically")
          .build();
  return javaFile.toString();
}
 
Example 2
Source File: EventStreamVisitorBuilderImplSpec.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
protected MethodSpec.Builder applyVisitSubTypeMethodSpecUpdates(TypeSpec.Builder typeBuilder,
                                                                MethodSpec.Builder methodBuilder,
                                                                ShapeModel s) {
    ClassName eventSubType = poetExt.getModelClass(s.getShapeName());
    TypeName eventConsumerType = consumerType(eventSubType);
    FieldSpec consumerField = FieldSpec.builder(eventConsumerType, "on" + eventSubType.simpleName())
                                       .addModifiers(Modifier.PRIVATE, Modifier.FINAL)
                                       .build();
    typeBuilder.addField(consumerField);

    constrBuilder.addStatement("this.$1L = builder.$1L != null ?\n"
                               + "builder.$1L :\n"
                               + "$2T.super::visit", consumerField.name, visitorType);
    return methodBuilder
        .addAnnotation(Override.class)
        .addStatement("$L.accept(event)", consumerField.name);
}
 
Example 3
Source File: AutoCodecProcessor.java    From bazel with Apache License 2.0 6 votes vote down vote up
private TypeSpec.Builder buildClassWithInstantiatorStrategy(
    TypeElement encodedType, AutoCodec annotation) throws SerializationProcessingFailedException {
  ExecutableElement constructor = selectInstantiator(encodedType);
  List<? extends VariableElement> fields = constructor.getParameters();

  TypeSpec.Builder codecClassBuilder =
      AutoCodecUtil.initializeCodecClassBuilder(encodedType, env);

  if (encodedType.getAnnotation(AutoValue.class) == null) {
    initializeUnsafeOffsets(codecClassBuilder, encodedType, fields);
    codecClassBuilder.addMethod(
        buildSerializeMethodWithInstantiator(encodedType, fields, annotation));
  } else {
    codecClassBuilder.addMethod(
        buildSerializeMethodWithInstantiatorForAutoValue(encodedType, fields, annotation));
  }

  MethodSpec.Builder deserializeBuilder =
      AutoCodecUtil.initializeDeserializeMethodBuilder(encodedType, env);
  buildDeserializeBody(deserializeBuilder, fields);
  addReturnNew(deserializeBuilder, encodedType, constructor, /*builderVar=*/ null, env);
  codecClassBuilder.addMethod(deserializeBuilder.build());

  return codecClassBuilder;
}
 
Example 4
Source File: BaseClientBuilderInterface.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public TypeSpec poetSpec() {
    TypeSpec.Builder builder = PoetUtils.createInterfaceBuilder(builderInterfaceName)
                    .addTypeVariable(PoetUtils.createBoundedTypeVariableName("B", builderInterfaceName, "B", "C"))
                    .addTypeVariable(TypeVariableName.get("C"))
                    .addSuperinterface(PoetUtils.createParameterizedTypeName(AwsClientBuilder.class, "B", "C"))
                    .addJavadoc(getJavadoc());

    if (model.getEndpointOperation().isPresent()) {
        if (model.getCustomizationConfig().isEnableEndpointDiscoveryMethodRequired()) {
            builder.addMethod(enableEndpointDiscovery());
        }

        builder.addMethod(endpointDiscovery());
    }

    if (model.getCustomizationConfig().getServiceSpecificClientConfigClass() != null) {
        builder.addMethod(serviceConfigurationMethod());
        builder.addMethod(serviceConfigurationConsumerBuilderMethod());
    }

    return builder.build();
}
 
Example 5
Source File: AsyncClientBuilderClass.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public TypeSpec poetSpec() {
    TypeSpec.Builder builder =
            PoetUtils.createClassBuilder(builderClassName)
                     .addAnnotation(SdkInternalApi.class)
                     .addModifiers(Modifier.FINAL)
                     .superclass(ParameterizedTypeName.get(builderBaseClassName, builderInterfaceName, clientInterfaceName))
                     .addSuperinterface(builderInterfaceName)
                     .addJavadoc("Internal implementation of {@link $T}.", builderInterfaceName);

    if (model.getEndpointOperation().isPresent()) {
        builder.addMethod(endpointDiscoveryEnabled());

        if (model.getCustomizationConfig().isEnableEndpointDiscoveryMethodRequired()) {
            builder.addMethod(enableEndpointDiscovery());
        }
    }

    return builder.addMethod(buildClientMethod()).build();
}
 
Example 6
Source File: WriterUtil.java    From sqlitemagic with Apache License 2.0 6 votes vote down vote up
public static void addOperationByColumnToOperationBuilder(TypeSpec.Builder builder,
                                                          TypeName interfaceName) {
  final TypeVariableName inputColumnType = TypeVariableName.get("C", ParameterizedTypeName.get(UNIQUE, NOT_NULLABLE_COLUMN));

  builder
      .addField(FieldSpec
          .builder(OPERATION_BY_COLUMNS, OPERATION_BY_COLUMNS_VARIABLE, PRIVATE, FINAL)
          .addAnnotation(NON_NULL)
          .initializer("new $T<>(2)", ARRAY_LIST)
          .build())
      .addMethod(MethodSpec
          .methodBuilder(METHOD_BY_COLUMN)
          .addModifiers(Modifier.PUBLIC)
          .addAnnotation(Override.class)
          .addAnnotation(NON_NULL)
          .addAnnotation(CHECK_RESULT)
          .addTypeVariable(inputColumnType)
          .addParameter(ParameterSpec.builder(inputColumnType, "column").build())
          .returns(interfaceName)
          .addStatement("this.$L.add(($T) column)",
              OPERATION_BY_COLUMNS_VARIABLE, COLUMN)
          .addStatement("return this")
          .build());
}
 
Example 7
Source File: RegionGenerator.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private void addGlobalRegions(TypeSpec.Builder builder) {
    builder.addField(FieldSpec.builder(className(), "AWS_GLOBAL")
                              .addModifiers(PUBLIC, STATIC, FINAL)
                              .initializer("$T.of($S, true)", className(), "aws-global")
                              .build())
           .addField(FieldSpec.builder(className(), "AWS_CN_GLOBAL")
                              .addModifiers(PUBLIC, STATIC, FINAL)
                              .initializer("$T.of($S, true)", className(), "aws-cn-global")
                              .build())
           .addField(FieldSpec.builder(className(), "AWS_US_GOV_GLOBAL")
                              .addModifiers(PUBLIC, STATIC, FINAL)
                              .initializer("$T.of($S, true)", className(), "aws-us-gov-global")
                              .build())
           .addField(FieldSpec.builder(className(), "AWS_ISO_GLOBAL")
                              .addModifiers(PUBLIC, STATIC, FINAL)
                              .initializer("$T.of($S, true)", className(), "aws-iso-global")
                              .build())
           .addField(FieldSpec.builder(className(), "AWS_ISO_B_GLOBAL")
                              .addModifiers(PUBLIC, STATIC, FINAL)
                              .initializer("$T.of($S, true)", className(), "aws-iso-b-global")
                              .build());
}
 
Example 8
Source File: RouterActivityCodeBuilder.java    From grouter-android with Apache License 2.0 6 votes vote down vote up
private static void addTypeSpec(String centerName,TypeSpec.Builder RouterHelper, TypeSpec.Builder builderSet, ActivityModel typeModel) {
    int index = typeModel.type.lastIndexOf(".") + 1;
    String name = typeModel.type.substring(index);
    TypeSpec.Builder typeSpec = TypeSpec.classBuilder(name + "Helper")
            .addModifiers(Modifier.STATIC,Modifier.PUBLIC).superclass(RouterBuilder);


    ClassName className = ClassName.get("com.grouter", centerName, "BuilderSet", name + "Helper");

    MethodSpec methodSpec = MethodSpec.constructorBuilder().addStatement("super($S)", typeModel.type).build();
    typeSpec.addMethod(methodSpec);
    for (ParameterModel typeMember : typeModel.params) {
        addMethodSpec(typeSpec, className, typeMember);
    }
    builderSet.addType(typeSpec.build());
    // 在 RouterHelper 增加快速创建构造器的方法
    MethodSpec methodSpec1 = MethodSpec.methodBuilder(name).addModifiers(Modifier.PUBLIC, Modifier.STATIC).returns(className).addStatement("return new $T()", className).build();
    RouterHelper.addMethod(methodSpec1);
}
 
Example 9
Source File: GeneratedCodeGenerator.java    From jackdaw with Apache License 2.0 5 votes vote down vote up
private TypeSpec.Builder createTypeSpecBuilder(final ClassType classType, final String className) {
    switch (classType) {
        case ANNOTATION:
            return TypeSpec.annotationBuilder(className);
        case INTERFACE:
            return TypeSpec.interfaceBuilder(className);
        default:
            return TypeSpec.classBuilder(className);
    }
}
 
Example 10
Source File: ArrayTypeHandlerPlugin.java    From raml-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public TypeSpec.Builder classCreated(ArrayPluginContext enumerationPluginContext, TypeDeclaration ramlType, TypeSpec.Builder incoming, EventType eventType) {

    for (ArrayTypeHandlerPlugin plugin : plugins) {
        if ( incoming == null ) {
            break;
        }
        incoming = plugin.classCreated(enumerationPluginContext, ramlType, incoming, eventType);
    }

    return incoming;
}
 
Example 11
Source File: Utils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 构建 DevEnvironment 类对象
 * @return {@link TypeSpec.Builder}
 */
public static TypeSpec.Builder builderDevEnvironment_Class() {
    // 创建 DevEnvironment 类
    TypeSpec.Builder classBuilder = TypeSpec.classBuilder(ENVIRONMENT_FILE_NAME)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addJavadoc("detail: 环境配置工具类\n")
            .addJavadoc("@author Ttt\n");
    // 创建 DevEnvironment 无参构造函数
    // private DevEnvironment() {}
    MethodSpec constructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE).build();
    return classBuilder.addMethod(constructor);
}
 
Example 12
Source File: EventStreamVisitorInterfaceSpec.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
protected MethodSpec.Builder applyVisitSubTypeMethodSpecUpdates(TypeSpec.Builder typeBuilder,
                                                                MethodSpec.Builder methodBuilder,
                                                                ShapeModel eventShape) {
    ClassName eventSubType = poetExt.getModelClass(eventShape.getShapeName());
    String javadocs = new DocumentationBuilder()
        .description("Invoked when a {@link $T} is encountered. If this is not overridden, the event will "
                     + "be given to {@link #visitDefault($T)}.")
        .param("event", "Event being visited")
        .build();
    return methodBuilder.addModifiers(Modifier.DEFAULT)
                        .addStatement("visitDefault(event)")
                        .addJavadoc(javadocs, eventSubType, eventStreamBaseClass);
}
 
Example 13
Source File: AutoLayoutProcessor.java    From AutoLayout-Android with Apache License 2.0 5 votes vote down vote up
private void exportToFile(List<ParsedInfo> infos) {
    if (!infos.isEmpty()) {
        MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("create")
                .addAnnotation(Override.class)
                .addModifiers(PUBLIC)
                .addParameter(String.class, "name")
                .addParameter(CONTEXT_TYPE, "context")
                .addParameter(ATTRIBUTE_SET_TYPE, "attrs")
                .returns(VIEW_TYPE)
                .beginControlFlow("switch (name)");

        for (ParsedInfo info : infos) {
            if (info.superCanonicalName.startsWith("android.widget.")) {//Standard android layout.
                info.superCanonicalName = info.superCanonicalName.substring(info.superCanonicalName.lastIndexOf('.') + 1);
            }

            ClassName className = ClassName.bestGuess(info.canonicalName);
            methodBuilder.addStatement("case $S: return new $T(context, attrs)", info.superCanonicalName, className);
        }
        methodBuilder.endControlFlow();
        methodBuilder.addStatement("return null");

        TypeSpec.Builder result = TypeSpec.classBuilder(VIEW_CREATOR_IMPL)
                .addSuperinterface(VIEW_CREATOR_TYPE)
                .addModifiers(PUBLIC)
                .addMethod(methodBuilder.build());

        try {
            JavaFile.builder(PACKAGE_NAME, result.build())
                    .addFileComment("Generated code from AutoLayout. Do not modify!")
                    .build().writeTo(filer);
        } catch (IOException e) {
            e.printStackTrace();
            error("Unable to write %s.", VIEW_CREATOR_IMPL);
        }
    }
}
 
Example 14
Source File: RpcProxyGenerator.java    From fastjgame with Apache License 2.0 5 votes vote down vote up
@Override
public void execute() {
    // 代理类不可以继承
    final TypeSpec.Builder typeBuilder = TypeSpec.classBuilder(getClientProxyClassName(typeElement))
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addAnnotation(processorInfoAnnotation);

    // 生成代理方法
    for (final ExecutableElement method : rpcMethods) {
        typeBuilder.addMethod(genClientMethodProxy(method));
    }

    // 写入文件
    AutoUtils.writeToFile(typeElement, typeBuilder, elementUtils, messager, filer);
}
 
Example 15
Source File: EventSubscribeProcessor.java    From fastjgame with Apache License 2.0 5 votes vote down vote up
private void genProxyClass(TypeElement typeElement, List<? extends Element> methodList) {
    final TypeSpec.Builder typeBuilder = TypeSpec.classBuilder(getProxyClassName(typeElement))
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addAnnotation(AutoUtils.SUPPRESS_UNCHECKED_ANNOTATION)
            .addAnnotation(processorInfoAnnotation)
            .addMethod(genRegisterMethod(typeElement, methodList));

    // 写入文件
    AutoUtils.writeToFile(typeElement, typeBuilder, elementUtils, messager, filer);
}
 
Example 16
Source File: JAdapterCodeGenerator.java    From jackdaw with 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 17
Source File: InsertManager.java    From data-mediator with Apache License 2.0 4 votes vote down vote up
public static void addClassAnnotation(TypeSpec.Builder typeBuilder){
    for (TypeInsertDelegate delegate : sInserts){
        delegate.addClassAnnotation(typeBuilder);
    }
}
 
Example 18
Source File: SelectRawHelper.java    From kripton with Apache License 2.0 4 votes vote down vote up
@Override
public void generateCommonPart(SQLiteModelMethod method, TypeSpec.Builder classBuilder, MethodSpec.Builder methodBuilder, Set<JQLProjection> fieldList, boolean mapFields) {
	generateCommonPart(method, classBuilder, methodBuilder, fieldList, GenerationType.NO_CLOSE_CURSOR, null, true, false, "paginatedResult");
}
 
Example 19
Source File: SolidityFunctionWrapperTest.java    From client-sdk-java with Apache License 2.0 4 votes vote down vote up
@Test
public void testBuildEventConstantMultipleValueReturn() throws Exception {

    AbiDefinition.NamedType id = new AbiDefinition.NamedType("id", "string", true);
    AbiDefinition.NamedType fromAddress = new AbiDefinition.NamedType("from", "address");
    AbiDefinition.NamedType toAddress = new AbiDefinition.NamedType("to", "address");
    AbiDefinition.NamedType value = new AbiDefinition.NamedType("value", "uint256");
    AbiDefinition.NamedType message = new AbiDefinition.NamedType("message", "string");
    fromAddress.setIndexed(true);
    toAddress.setIndexed(true);

    AbiDefinition functionDefinition = new AbiDefinition(
            false,
            Arrays.asList(id, fromAddress, toAddress, value, message),
            "Transfer",
            new ArrayList<>(),
            "event",
            false);
    TypeSpec.Builder builder = TypeSpec.classBuilder("testClass");

    builder.addMethods(
            solidityFunctionWrapper.buildEventFunctions(functionDefinition, builder));

    //CHECKSTYLE:OFF
    String expected =
            "class testClass {\n"
                    + "  public static final org.web3j.abi.datatypes.Event TRANSFER_EVENT = new org.web3j.abi.datatypes.Event(\"Transfer\", \n"
                    + "      java.util.Arrays.<org.web3j.abi.TypeReference<?>>asList(new org.web3j.abi.TypeReference<org.web3j.abi.datatypes.Utf8String>(true) {}, new org.web3j.abi.TypeReference<org.web3j.abi.datatypes.Address>(true) {}, new org.web3j.abi.TypeReference<org.web3j.abi.datatypes.Address>(true) {}, new org.web3j.abi.TypeReference<org.web3j.abi.datatypes.generated.Uint256>() {}, new org.web3j.abi.TypeReference<org.web3j.abi.datatypes.Utf8String>() {}));\n  ;\n\n"
                    + "  public java.util.List<TransferEventResponse> getTransferEvents(org.web3j.protocol.core.methods.response.TransactionReceipt transactionReceipt) {\n"
                    + "    java.util.List<org.web3j.tx.Contract.EventValuesWithLog> valueList = extractEventParametersWithLog(TRANSFER_EVENT, transactionReceipt);\n"
                    + "    java.util.ArrayList<TransferEventResponse> responses = new java.util.ArrayList<TransferEventResponse>(valueList.size());\n"
                    + "    for (org.web3j.tx.Contract.EventValuesWithLog eventValues : valueList) {\n"
                    + "      TransferEventResponse typedResponse = new TransferEventResponse();\n"
                    + "      typedResponse.log = eventValues.getLog();\n"
                    + "      typedResponse.id = (byte[]) eventValues.getIndexedValues().get(0).getValue();\n"
                    + "      typedResponse.from = (java.lang.String) eventValues.getIndexedValues().get(1).getValue();\n"
                    + "      typedResponse.to = (java.lang.String) eventValues.getIndexedValues().get(2).getValue();\n"
                    + "      typedResponse.value = (java.math.BigInteger) eventValues.getNonIndexedValues().get(0).getValue();\n"
                    + "      typedResponse.message = (java.lang.String) eventValues.getNonIndexedValues().get(1).getValue();\n"
                    + "      responses.add(typedResponse);\n"
                    + "    }\n"
                    + "    return responses;\n"
                    + "  }\n"
                    + "\n"
                    + "  public rx.Observable<TransferEventResponse> transferEventObservable" +
                    "(org.web3j.protocol.core.methods.request.PlatonFilter filter) {\n"
                    + "    return web3j.platonLogObservable(filter).map(new rx.functions.Func1<org.web3j.protocol.core.methods.response.Log, TransferEventResponse>() {\n"
                    + "      @java.lang.Override\n"
                    + "      public TransferEventResponse call(org.web3j.protocol.core.methods.response.Log log) {\n"
                    + "        org.web3j.tx.Contract.EventValuesWithLog eventValues = extractEventParametersWithLog(TRANSFER_EVENT, log);\n"
                    + "        TransferEventResponse typedResponse = new TransferEventResponse();\n"
                    + "        typedResponse.log = log;\n"
                    + "        typedResponse.id = (byte[]) eventValues.getIndexedValues().get(0).getValue();\n"
                    + "        typedResponse.from = (java.lang.String) eventValues.getIndexedValues().get(1).getValue();\n"
                    + "        typedResponse.to = (java.lang.String) eventValues.getIndexedValues().get(2).getValue();\n"
                    + "        typedResponse.value = (java.math.BigInteger) eventValues.getNonIndexedValues().get(0).getValue();\n"
                    + "        typedResponse.message = (java.lang.String) eventValues.getNonIndexedValues().get(1).getValue();\n"
                    + "        return typedResponse;\n"
                    + "      }\n"
                    + "    });\n"
                    + "  }\n"
                    + "\n"
                    + "  public rx.Observable<TransferEventResponse> transferEventObservable(org.web3j.protocol.core.DefaultBlockParameter startBlock, org.web3j.protocol.core.DefaultBlockParameter endBlock) {\n"
                    + "    org.web3j.protocol.core.methods.request.PlatonFilter filter = new org.web3j.protocol.core.methods.request.PlatonFilter(startBlock, endBlock, getContractAddress());\n"
                    + "    filter.addSingleTopic(org.web3j.abi.EventEncoder.encode(TRANSFER_EVENT));\n"
                    + "    return transferEventObservable(filter);\n"
                    + "  }\n"
                    + "\n"
                    + "  public static class TransferEventResponse {\n"
                    + "    public org.web3j.protocol.core.methods.response.Log log;\n"
                    + "\n"
                    + "    public byte[] id;\n"
                    + "\n"
                    + "    public java.lang.String from;\n"
                    + "\n"
                    + "    public java.lang.String to;\n"
                    + "\n"
                    + "    public java.math.BigInteger value;\n"
                    + "\n"
                    + "    public java.lang.String message;\n"
                    + "  }\n"
                    + "}\n";
    //CHECKSTYLE:ON

    assertThat(builder.build().toString(), is(expected));
}
 
Example 20
Source File: TypeInsertDelegate.java    From data-mediator with Apache License 2.0 votes vote down vote up
/**
 * override method for impl class
 * @param typeBuilder the type builder
 * @param fields the fields
 */
public void overrideMethodsForImpl(TypeSpec.Builder typeBuilder, Collection<FieldData> fields){

}