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

The following examples show how to use com.squareup.javapoet.CodeBlock#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: WasmFunctionWrapper.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
CodeBlock buildTypedResponse(String objectName, List<NamedTypeName> indexedParameters, List<NamedTypeName> nonIndexedParameters,
		boolean observable) {

	CodeBlock.Builder builder = CodeBlock.builder();
	if (observable) {
		builder.addStatement("$L.log = log", objectName);
	} else {
		builder.addStatement("$L.log = eventValues.getLog()", objectName);
	}
	for (int i = 0; i < indexedParameters.size(); i++) {
		builder.addStatement("$L.$L = ($T) eventValues.getIndexedValues().get($L)", objectName, indexedParameters.get(i).getName(), String.class,
				i);
	}
	for (int i = 0; i < nonIndexedParameters.size(); i++) {
		builder.addStatement("$L.$L = ($T) eventValues.getNonIndexedValues().get($L)", objectName, nonIndexedParameters.get(i).getName(),
				nonIndexedParameters.get(i).getTypeName(), i);
	}
	return builder.build();
}
 
Example 2
Source File: WorkingRangeGenerator.java    From litho with Apache License 2.0 6 votes vote down vote up
/** Generate a delegate to the Spec that defines this onTrigger method. */
private static MethodSpec generateWorkingRangeMethodDelegate(
    SpecModel specModel, SpecMethodModel<EventMethod, WorkingRangeDeclarationModel> methodModel) {
  final MethodSpec.Builder methodSpec =
      MethodSpec.methodBuilder(methodModel.name.toString())
          .addModifiers(Modifier.PRIVATE)
          .returns(TypeName.VOID)
          .addParameter(ClassNames.COMPONENT_CONTEXT, "c");

  final CodeBlock.Builder delegation = CodeBlock.builder();

  final String sourceDelegateAccessor = SpecModelUtils.getSpecAccessor(specModel);
  delegation.add("$L.$L(\n", sourceDelegateAccessor, methodModel.name);
  delegation.indent();
  for (int i = 0, size = methodModel.methodParams.size(); i < size; i++) {
    final MethodParamModel methodParamModel = methodModel.methodParams.get(i);

    delegation.add(
        "($T) $L", methodParamModel.getTypeName(), getImplAccessor(specModel, methodParamModel));
    delegation.add((i < methodModel.methodParams.size() - 1) ? ",\n" : ");\n");
  }
  delegation.unindent();
  methodSpec.addCode(delegation.build());

  return methodSpec.build();
}
 
Example 3
Source File: SharedPropertiesNGenerator.java    From data-mediator with Apache License 2.0 6 votes vote down vote up
public static boolean generateSharedProperties(Collection<FieldData> fields,
                                               Elements elements, Filer filer, ProcessorPrinter pp){
    final ClassName cn_sp = ClassName.get(PKG_DM_INTERNAL, SIMPLE_NAME_SHARED_PROP);
    CodeBlock.Builder staticBuilder = CodeBlock.builder();
    for(FieldData fd : fields){
        staticBuilder.add("$T.putToCache($S, $S, $L);\n", cn_sp, fd.getTypeCompat().toString(),
                fd.getPropertyName(), fd.getComplexType());
    }
    String classSimpleName = SIMPLE_NAME_SHARED_PROP + "_" + findBestIndex(elements);
    TypeSpec typeSpec = TypeSpec.classBuilder(classSimpleName)
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addStaticBlock(staticBuilder.build())
            .addJavadoc(CodeBlock.of(DOC))
            .build();

    try {
        JavaFile javaFile = JavaFile.builder(PKG_DM_INTERNAL, typeSpec)
                .build();
       // System.out.println(javaFile.toString());
        javaFile.writeTo(filer);
    } catch (IOException e) {
        pp.error(TAG, "generateSharedProperties", Util.toString(e));
        return false;
    }
    return true;
}
 
Example 4
Source File: EventStreamJsonMarshallerSpec.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public CodeBlock marshalCodeBlock(ClassName requestClassName) {
    String variableName = shapeModel.getVariable().getVariableName();
    CodeBlock.Builder builder =
        CodeBlock.builder()
                 .addStatement("$T<$T> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING)",
                               ProtocolMarshaller.class, SdkHttpFullRequest.class)
                 .add("return protocolMarshaller.marshall($L).toBuilder()", variableName)
                 .add(".putHeader(\":message-type\", \"event\")")
                 .add(".putHeader(\":event-type\", \"$L\")", getMemberNameFromEventStream());

    // Add :content-type header only if payload is present
    if (!shapeModel.hasNoEventPayload()) {
        builder.add(".putHeader(\":content-type\", \"$L\")", determinePayloadContentType());
    }

    builder.add(".build();");

    return builder.build();
}
 
Example 5
Source File: Generator.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
private void addSerializationProviderInit(final State state, final TypeSpec.Builder serviceClassBuilder) {
    final CodeBlock.Builder staticInitBlockBuilder = CodeBlock.builder()
            .addStatement("$T builder = new $T()", ProtoBufSerializationProviderBuilder,
                    ProtoBufSerializationProviderBuilder);

    concat(state.serviceProto.getMethodList().stream()
                    .filter(MethodDescriptorProto::hasInputType)
                    .map(MethodDescriptorProto::getInputType),
            state.serviceProto.getMethodList().stream()
                    .filter(MethodDescriptorProto::hasOutputType)
                    .map(MethodDescriptorProto::getOutputType))
            .distinct()
            .map(messageTypesMap::get)
            .forEach(t -> staticInitBlockBuilder.addStatement("$L.registerMessageType($T.class, $T.parser())",
                    builder, t, t));

    staticInitBlockBuilder
            .addStatement("$L = $L.build()", serializationProvider, builder)
            .build();

    serviceClassBuilder
            .addField(GrpcSerializationProvider, serializationProvider, PRIVATE, STATIC, FINAL)
            .addStaticBlock(staticInitBlockBuilder.build());
}
 
Example 6
Source File: DeepLinkInterceptorProcessor.java    From OkDeepLink with Apache License 2.0 6 votes vote down vote up
private MethodSpec.Builder geneGlobalInterceptorsBuilder(InterceptorElement interceptorElement) {
    CodeBlock.Builder builder = CodeBlock.builder();
    TypeName typeName = ParameterizedTypeName.get(ClassName.get(List.class), INTERCEPTOR);
    builder.add("$T result = ($T)joinPoint.proceed();\n", typeName, typeName);
    builder.add("result.add(new $T());\n",
            interceptorElement.getClassName());
    builder.add("return result;\n");
    return MethodSpec.methodBuilder("getGlobalInterceptors")
            .addModifiers(Modifier.PUBLIC)
            .addParameter(ProceedingJoinPoint.class, "joinPoint")
            .returns(typeName)
            .addException(Throwable.class)
            .addAnnotation(AnnotationSpec
                    .builder(Around.class)
                    .addMember("value", "$S", "execution(* " + GLOBAL_INTERCEPTORS_METHOD_NAME + ")").build())
            .addCode(builder.build());
}
 
Example 7
Source File: JsonProtocolSpec.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public CodeBlock responseHandler(IntermediateModel model, OperationModel opModel) {
    TypeName pojoResponseType = getPojoResponseType(opModel, poetExtensions);

    String protocolFactory = protocolFactoryLiteral(model, opModel);
    CodeBlock.Builder builder = CodeBlock.builder();
    builder.add("$T operationMetadata = $T.builder()\n"
                + ".hasStreamingSuccessResponse($L)\n"
                + ".isPayloadJson($L)\n"
                + ".build();", JsonOperationMetadata.class, JsonOperationMetadata.class,
                opModel.hasStreamingOutput(), !opModel.getHasBlobMemberAsPayload());
    if (opModel.hasEventStreamOutput()) {
        responseHandlersForEventStreaming(opModel, pojoResponseType, protocolFactory, builder);
    } else {
        builder.add("\n\n$T<$T> responseHandler = $L.createResponseHandler(operationMetadata, $T::builder);",
                    HttpResponseHandler.class,
                    pojoResponseType,
                    protocolFactory,
                    pojoResponseType);
    }
    return builder.build();
}
 
Example 8
Source File: DeepLinkServiceProcessor.java    From OkDeepLink with Apache License 2.0 6 votes vote down vote up
private MethodSpec generateBuildMethod(TypeElement deepLinkServiceElement) {

        CodeBlock.Builder codeBlockBuilder = CodeBlock.builder();
        codeBlockBuilder.add("$T target = ($T)joinPoint.getTarget();\n", DEEP_LINK_CLIENT, DEEP_LINK_CLIENT);
        codeBlockBuilder.beginControlFlow("if (joinPoint.getArgs() == null || joinPoint.getArgs().length != 1)");
        codeBlockBuilder.add("return joinPoint.proceed();\n");
        codeBlockBuilder.endControlFlow();
        codeBlockBuilder.add("$T arg = joinPoint.getArgs()[0];\n", Object.class);
        codeBlockBuilder.beginControlFlow("if (arg instanceof Class)");
        codeBlockBuilder.add("$T buildClass = ($T) arg;\n", Class.class, Class.class);
        codeBlockBuilder.beginControlFlow("if (buildClass.isAssignableFrom(getClass()))");
        codeBlockBuilder.add("return new $T(target);\n", getServiceProviderClassName(deepLinkServiceElement));
        codeBlockBuilder.endControlFlow();
        codeBlockBuilder.endControlFlow();
        codeBlockBuilder.add("return joinPoint.proceed();\n");

        MethodSpec.Builder initMethod = MethodSpec.methodBuilder("aroundBuildMethod")
                .addModifiers(Modifier.PUBLIC)
                .addParameter(ProceedingJoinPoint.class, "joinPoint")
                .returns(Object.class)
                .addException(Throwable.class)
                .addAnnotation(AnnotationSpec.builder(Around.class).addMember("value", "$S", "execution(* " + BUILD_METHOD_NAME + ")").build())
                .addCode(codeBlockBuilder.build());

        return initMethod.build();
    }
 
Example 9
Source File: AsyncClientClass.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private CodeBlock createEventStreamTaggedUnionJsonMarshaller(ShapeModel eventStreamShape) {
    CodeBlock.Builder builder = CodeBlock.builder().add("$1T eventMarshaller = $1T.builder()",
                                                        EventStreamTaggedUnionJsonMarshaller.class);

    List<String> eventNames = EventStreamUtils.getEventMembers(eventStreamShape)
                                              .map(m -> m.getShape().getShapeName())
                                              .collect(Collectors.toList());

    eventNames.forEach(event -> builder.add(".putMarshaller($T.class, new $T(protocolFactory))",
                                            poetExtensions.getModelClass(event),
                                            poetExtensions.getTransformClass(event + "Marshaller")));

    builder.add(".build();");
    return builder.build();
}
 
Example 10
Source File: RegionMetadataProviderGenerator.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private CodeBlock regions(Partitions partitions) {
    CodeBlock.Builder builder = CodeBlock.builder().add("$T.<Region, RegionMetadata>builder()", ImmutableMap.class);

    partitions.getPartitions()
              .forEach(p -> p.getRegions()
                             .keySet()
                             .forEach(r -> builder.add(".put(Region.$L, new $T())", regionClass(r), regionMetadataClass(r))));

    return builder.add(".build()").build();
}
 
Example 11
Source File: Utils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 构建 Reset 方法
 * @param classBuilder DevEnvironment 类构建对象
 */
public static void builderResetMethod(final TypeSpec.Builder classBuilder) {
    StringBuilder varBuilder = new StringBuilder();
    Iterator<Map.Entry<String, List<String>>> iterator = sModuleNameMap.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry<String, List<String>> entry = iterator.next();
        // Module 名
        String moduleName = entry.getKey();
        // 拼接变量设置为 null
        varBuilder.append(String.format("    %s = null;\n", VAR_SELECT_ENVIRONMENT + moduleName));
    }

    // 构建 reset 实现代码
    CodeBlock.Builder codeBlockBuilder = CodeBlock.builder();
    codeBlockBuilder.add("if ($N != null && $N($N)) {\n", VAR_CONTEXT, METHOD_DELETE_STORAGE_DIR, VAR_CONTEXT);
    codeBlockBuilder.add(varBuilder.toString());
    codeBlockBuilder.add("    return true;\n");
    codeBlockBuilder.add("}\n");

    // public static final void reset() {}
    MethodSpec resetMethod = MethodSpec
            .methodBuilder(METHOD_RESET)
            .addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
            .addParameter(TYPE_NAME_CONTEXT, VAR_CONTEXT, Modifier.FINAL)
            .addCode(codeBlockBuilder.build())
            .returns(Boolean.class)
            .addStatement("return false")
            .addJavadoc("重置操作\n")
            .addJavadoc("<p>Reset Operating\n")
            .addJavadoc("@param $N {@link Context}\n", VAR_CONTEXT)
            .addJavadoc("@return {@code true} success, {@code false} fail\n")
            .build();
    classBuilder.addMethod(resetMethod);
}
 
Example 12
Source File: XmlProtocolSpec.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public CodeBlock executionHandler(OperationModel opModel) {
    if (opModel.hasStreamingOutput()) {
        return streamingExecutionHandler(opModel);
    }

    TypeName responseType = poetExtensions.getModelClass(opModel.getReturnType().getReturnType());
    ClassName requestType = poetExtensions.getModelClass(opModel.getInput().getVariableType());
    ClassName marshaller = poetExtensions.getTransformClass(opModel.getInputShape().getShapeName() + "Marshaller");
    CodeBlock.Builder codeBlock = CodeBlock
        .builder()
        .add("\n\nreturn clientHandler.execute(new $T<$T, $T>()" +
             ".withOperationName(\"$N\")\n" +
             ".withCombinedResponseHandler($N)" +
             hostPrefixExpression(opModel) +
             discoveredEndpoint(opModel) +
             ".withInput($L)",
             software.amazon.awssdk.core.client.handler.ClientExecutionParams.class,
             requestType,
             responseType,
             opModel.getOperationName(),
             "responseHandler",
             opModel.getInput().getVariableName());
    if (opModel.hasStreamingInput()) {
        return codeBlock.add(".withRequestBody(requestBody)")
                        .add(".withMarshaller($L));", syncStreamingMarshaller(intermediateModel, opModel, marshaller))
                        .build();
    }
    return codeBlock.add(".withMarshaller(new $T(protocolFactory)) $L);", marshaller,
                         opModel.hasStreamingOutput() ? ", responseTransformer" : "").build();
}
 
Example 13
Source File: ShapeModelSpec.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private CodeBlock createXmlAttributesTrait(MemberModel model) {
    ShapeModel shape = model.getShape();
    XmlNamespace xmlNamespace = shape.getXmlNamespace();
    String uri = xmlNamespace.getUri();
    String prefix = xmlNamespace.getPrefix();
    CodeBlock.Builder codeBlockBuilder = CodeBlock.builder()
                                     .add("$T.create(", ClassName.get(XmlAttributesTrait.class));

    String namespacePrefix = "xmlns:" + prefix;
    codeBlockBuilder.add("$T.of($S, $T.builder().attributeGetter((ignore) -> $S).build())",
                         Pair.class, namespacePrefix, AttributeAccessors.class, uri);

    Optional<MemberModel> memberWithXmlAttribute = findMemberWithXmlAttribute(shape);
    memberWithXmlAttribute.ifPresent(m -> {
        String attributeLocation = m.getHttp().getMarshallLocationName();
        codeBlockBuilder
            .add(", $T.of($S, ", Pair.class, attributeLocation)
            .add("$T.builder()", AttributeAccessors.class)
            .add(".attributeGetter(t -> (($T)t).$L())\n",
                 typeProvider.fieldType(model),
                 m.getFluentGetterMethodName())
            .add(".build())");
    });

    codeBlockBuilder.add(")");

    return codeBlockBuilder.build();
}
 
Example 14
Source File: ClientClassUtils.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
static CodeBlock addEndpointTraitCode(OperationModel opModel) {
    CodeBlock.Builder builder = CodeBlock.builder();

    if (opModel.getEndpointTrait() != null && !StringUtils.isEmpty(opModel.getEndpointTrait().getHostPrefix())) {
        String hostPrefix = opModel.getEndpointTrait().getHostPrefix();
        HostPrefixProcessor processor = new HostPrefixProcessor(hostPrefix);

        builder.addStatement("String hostPrefix = $S", hostPrefix);

        if (processor.c2jNames().isEmpty()) {
            builder.addStatement("String resolvedHostExpression = $S", processor.hostWithStringSpecifier());
        } else {
            processor.c2jNames()
                     .forEach(name -> builder.addStatement("$T.paramNotBlank($L, $S)", Validate.class,
                                                          inputShapeMemberGetter(opModel, name),
                                                           name));

            builder.addStatement("String resolvedHostExpression = String.format($S, $L)",
                                 processor.hostWithStringSpecifier(),
                                 processor.c2jNames().stream()
                                          .map(n -> inputShapeMemberGetter(opModel, n))
                                          .collect(Collectors.joining(",")));
        }
    }

    return builder.build();
}
 
Example 15
Source File: DelegateMethodGenerator.java    From litho with Apache License 2.0 5 votes vote down vote up
private static CodeBlock getDelegationMethod(
    SpecModel specModel,
    CharSequence methodName,
    TypeName returnType,
    ImmutableList<ParamTypeAndName> methodParams) {
  final CodeBlock.Builder delegation = CodeBlock.builder();
  final String sourceDelegateAccessor = SpecModelUtils.getSpecAccessor(specModel);
  if (returnType.equals(TypeName.VOID)) {
    delegation.add("$L.$L(\n", sourceDelegateAccessor, methodName);
  } else {
    delegation.add("_result = ($T) $L.$L(\n", returnType, sourceDelegateAccessor, methodName);
  }

  delegation.indent();
  for (int i = 0; i < methodParams.size(); i++) {
    delegation.add("($T) $L", methodParams.get(i).type, methodParams.get(i).name);

    if (i < methodParams.size() - 1) {
      delegation.add(",\n");
    }
  }

  delegation.add(");\n");
  delegation.unindent();

  return delegation.build();
}
 
Example 16
Source File: ReactPropertyProcessor.java    From react-native-GPay with MIT License 5 votes vote down vote up
private static CodeBlock generateGetProperties(List<PropertyInfo> properties)
    throws ReactPropertyException {
  CodeBlock.Builder builder = CodeBlock.builder();
  for (PropertyInfo propertyInfo : properties) {
    try {
      String typeName = getPropertypTypeName(propertyInfo.mProperty, propertyInfo.propertyType);
      builder.addStatement("props.put($S, $S)", propertyInfo.mProperty.name(), typeName);
    } catch (IllegalArgumentException e) {
      throw new ReactPropertyException(e.getMessage(), propertyInfo);
    }
  }

  return builder.build();
}
 
Example 17
Source File: SolidityFunctionWrapper.java    From etherscan-explorer with GNU General Public License v3.0 4 votes vote down vote up
private void buildTupleResultContainer(
        MethodSpec.Builder methodBuilder, ParameterizedTypeName tupleType,
        List<TypeName> outputParameterTypes)
        throws ClassNotFoundException {

    List<TypeName> typeArguments = tupleType.typeArguments;

    CodeBlock.Builder tupleConstructor = CodeBlock.builder();
    tupleConstructor.addStatement(
            "$T results = executeCallMultipleValueReturn(function)",
            ParameterizedTypeName.get(List.class, Type.class))
            .add("return new $T(", tupleType)
            .add("$>$>");

    String resultStringSimple = "\n($T) results.get($L)";
    if (useNativeJavaTypes) {
        resultStringSimple += ".getValue()";
    }

    String resultStringNativeList =
            "\nconvertToNative(($T) results.get($L).getValue())";

    int size = typeArguments.size();
    ClassName classList = ClassName.get(List.class);

    for (int i = 0; i < size; i++) {
        TypeName param = outputParameterTypes.get(i);
        TypeName convertTo = typeArguments.get(i);

        String resultString = resultStringSimple;

        // If we use native java types we need to convert
        // elements of arrays to native java types too
        if (useNativeJavaTypes && param instanceof ParameterizedTypeName) {
            ParameterizedTypeName oldContainer = (ParameterizedTypeName)param;
            ParameterizedTypeName newContainer = (ParameterizedTypeName)convertTo;
            if (newContainer.rawType.compareTo(classList) == 0
                    && newContainer.typeArguments.size() == 1) {
                convertTo = ParameterizedTypeName.get(classList,
                        oldContainer.typeArguments.get(0));
                resultString = resultStringNativeList;
            }
        }

        tupleConstructor
            .add(resultString, convertTo, i);
        tupleConstructor.add(i < size - 1 ? ", " : ");\n");
    }
    tupleConstructor.add("$<$<");

    TypeSpec callableType = TypeSpec.anonymousClassBuilder("")
            .addSuperinterface(ParameterizedTypeName.get(
                    ClassName.get(Callable.class), tupleType))
            .addMethod(MethodSpec.methodBuilder("call")
                    .addAnnotation(Override.class)
                    .addModifiers(Modifier.PUBLIC)
                    .addException(Exception.class)
                    .returns(tupleType)
                    .addCode(tupleConstructor.build())
                    .build())
            .build();

    methodBuilder.addStatement(
            "return new $T(\n$L)", buildRemoteCall(tupleType), callableType);
}
 
Example 18
Source File: SolidityFunctionWrapper.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
private void buildTupleResultContainer0(
        MethodSpec.Builder methodBuilder,
        ParameterizedTypeName tupleType,
        List<TypeName> outputParameterTypes)
        throws ClassNotFoundException {

    List<TypeName> typeArguments = tupleType.typeArguments;

    CodeBlock.Builder codeBuilder = CodeBlock.builder();

    String resultStringSimple = "\n($T) results.get($L)";
    if (useNativeJavaTypes) {
        resultStringSimple += ".getValue()";
    }

    String resultStringNativeList = "\nconvertToNative(($T) results.get($L).getValue())";

    int size = typeArguments.size();
    ClassName classList = ClassName.get(List.class);

    for (int i = 0; i < size; i++) {
        TypeName param = outputParameterTypes.get(i);
        TypeName convertTo = typeArguments.get(i);

        String resultString = resultStringSimple;

        // If we use native java types we need to convert
        // elements of arrays to native java types too
        if (useNativeJavaTypes && param instanceof ParameterizedTypeName) {
            ParameterizedTypeName oldContainer = (ParameterizedTypeName) param;
            ParameterizedTypeName newContainer = (ParameterizedTypeName) convertTo;
            if (newContainer.rawType.compareTo(classList) == 0
                    && newContainer.typeArguments.size() == 1) {
                convertTo =
                        ParameterizedTypeName.get(classList, oldContainer.typeArguments.get(0));
                resultString = resultStringNativeList;
            }
        }

        codeBuilder.add(resultString, convertTo, i);
        codeBuilder.add(i < size - 1 ? ", " : "\n");
    }

    methodBuilder.addStatement("return new $T(\n$L)", tupleType, codeBuilder.build());
}
 
Example 19
Source File: SolidityFunctionWrapper.java    From client-sdk-java with Apache License 2.0 4 votes vote down vote up
private void addAddressesSupport(TypeSpec.Builder classBuilder,
                                 Map<String, String> addresses) {
    if (addresses != null) {

        ClassName stringType = ClassName.get(String.class);
        ClassName mapType = ClassName.get(HashMap.class);
        TypeName mapStringString = ParameterizedTypeName.get(mapType, stringType, stringType);
        FieldSpec addressesStaticField = FieldSpec
                .builder(mapStringString, "_addresses",
                        Modifier.PROTECTED, Modifier.STATIC, Modifier.FINAL)
                .build();
        classBuilder.addField(addressesStaticField);

        final CodeBlock.Builder staticInit = CodeBlock.builder();
        staticInit.addStatement("_addresses = new HashMap<String, String>()");
        addresses.forEach((k, v) ->
                staticInit.addStatement(String.format("_addresses.put(\"%1s\", \"%2s\")",
                        k, v))
        );
        classBuilder.addStaticBlock(staticInit.build());

        // See org.web3j.tx.Contract#getStaticDeployedAddress(String)
        MethodSpec getAddress = MethodSpec
                .methodBuilder("getStaticDeployedAddress")
                .addModifiers(Modifier.PROTECTED)
                .returns(stringType)
                .addParameter(stringType, "networkId")
                .addCode(
                        CodeBlock
                                .builder()
                                .addStatement("return _addresses.get(networkId)")
                                .build())
                .build();
        classBuilder.addMethod(getAddress);

        MethodSpec getPreviousAddress = MethodSpec
                .methodBuilder("getPreviouslyDeployedAddress")
                .addModifiers(Modifier.PUBLIC)
                .addModifiers(Modifier.STATIC)
                .returns(stringType)
                .addParameter(stringType, "networkId")
                .addCode(
                        CodeBlock
                                .builder()
                                .addStatement("return _addresses.get(networkId)")
                                .build())
                .build();
        classBuilder.addMethod(getPreviousAddress);

    }
}
 
Example 20
Source File: TypeInsertDelegate.java    From data-mediator with Apache License 2.0 2 votes vote down vote up
/**
 * add static code
 * @param staticBuilder the static code builder
 * @param param the extra param
 * @return true if added.
 */
public boolean addStaticCode(CodeBlock.Builder staticBuilder, Object param){
    return false;
}