com.squareup.javapoet.ParameterizedTypeName Java Examples

The following examples show how to use com.squareup.javapoet.ParameterizedTypeName. 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: ModuleGenerator.java    From nalu with Apache License 2.0 6 votes vote down vote up
private void generateGetShellConfigs(TypeSpec.Builder typeSpec) {
  // generate method 'generateLoadShells()'
  MethodSpec.Builder loadShellConfigMethodBuilder = MethodSpec.methodBuilder("getShellConfigs")
                                                              .addModifiers(Modifier.PUBLIC)
                                                              .addAnnotation(Override.class)
                                                              .returns(ParameterizedTypeName.get(ClassName.get(List.class),
                                                                                                 ClassName.get(ShellConfig.class)))
                                                              .addStatement("$T<$T> list = new $T<>()",
                                                                            ClassName.get(List.class),
                                                                            ClassName.get(ShellConfig.class),
                                                                            ClassName.get(ArrayList.class));
  this.metaModel.getShells()
                .forEach(shellModel -> loadShellConfigMethodBuilder.addStatement("list.add(new $T($S, $S))",
                                                                                 ClassName.get(ShellConfig.class),
                                                                                 "/" + shellModel.getName(),
                                                                                 shellModel.getShell()
                                                                                           .getClassName()));
  loadShellConfigMethodBuilder.addStatement("return list");
  typeSpec.addMethod(loadShellConfigMethodBuilder.build());
}
 
Example #2
Source File: WasmFunctionWrapper.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
MethodSpec buildEventTransactionReceiptFunction(String responseClassName, String functionName, List<NamedTypeName> indexedParameters,
		List<NamedTypeName> nonIndexedParameters) {

	ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName.get(ClassName.get(List.class), ClassName.get("", responseClassName));

	String generatedFunctionName = "get" + Strings.capitaliseFirstLetter(functionName) + "Events";
	MethodSpec.Builder transactionMethodBuilder = MethodSpec.methodBuilder(generatedFunctionName).addModifiers(Modifier.PUBLIC)
			.addParameter(TransactionReceipt.class, "transactionReceipt").returns(parameterizedTypeName);

	transactionMethodBuilder
			.addStatement("$T valueList = extractEventParametersWithLog(" + buildEventDefinitionName(functionName) + ", " + "transactionReceipt)",
					ParameterizedTypeName.get(List.class, WasmContract.WasmEventValuesWithLog.class))
			.addStatement("$1T responses = new $1T(valueList.size())",
					ParameterizedTypeName.get(ClassName.get(ArrayList.class), ClassName.get("", responseClassName)))
			.beginControlFlow("for ($T eventValues : valueList)", WasmContract.WasmEventValuesWithLog.class)
			.addStatement("$1T typedResponse = new $1T()", ClassName.get("", responseClassName))
			.addCode(buildTypedResponse("typedResponse", indexedParameters, nonIndexedParameters, false))
			.addStatement("responses.add(typedResponse)").endControlFlow();

	transactionMethodBuilder.addStatement("return responses");
	return transactionMethodBuilder.build();
}
 
Example #3
Source File: WasmFunctionWrapper.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
MethodSpec buildEventObservableFunction(String responseClassName, String functionName, List<NamedTypeName> indexedParameters,
		List<NamedTypeName> nonIndexedParameters) {

	String generatedFunctionName = Strings.lowercaseFirstLetter(functionName) + "EventObservable";
	ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName.get(ClassName.get(rx.Observable.class),
			ClassName.get("", responseClassName));

	MethodSpec.Builder observableMethodBuilder = MethodSpec.methodBuilder(generatedFunctionName).addModifiers(Modifier.PUBLIC)
			.addParameter(PlatonFilter.class, FILTER).returns(parameterizedTypeName);

	TypeSpec converter = TypeSpec.anonymousClassBuilder("")
			.addSuperinterface(
					ParameterizedTypeName.get(ClassName.get(Func1.class), ClassName.get(Log.class), ClassName.get("", responseClassName)))
			.addMethod(MethodSpec.methodBuilder("call").addAnnotation(Override.class).addModifiers(Modifier.PUBLIC).addParameter(Log.class, "log")
					.returns(ClassName.get("", responseClassName))
					.addStatement("$T eventValues = extractEventParametersWithLog(" + buildEventDefinitionName(functionName) + ", log)",
							WasmContract.WasmEventValuesWithLog.class)
					.addStatement("$1T typedResponse = new $1T()", ClassName.get("", responseClassName))
					.addCode(buildTypedResponse("typedResponse", indexedParameters, nonIndexedParameters, true))
					.addStatement("return typedResponse").build())
			.build();

	observableMethodBuilder.addStatement("return web3j.platonLogObservable(filter).map($L)", converter);

	return observableMethodBuilder.build();
}
 
Example #4
Source File: WasmFunctionWrapper.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
private void buildConstantFunction(WasmAbiDefinition functionDefinition, MethodSpec.Builder methodBuilder, List<TypeName> outputParameterTypes,
		String inputParams, Set<String> customTypes) throws ClassNotFoundException {

	String functionName = functionDefinition.getName();

	if (outputParameterTypes.isEmpty()) {
		methodBuilder.addStatement("throw new RuntimeException" + "(\"cannot call constant function with void return type\")");
	} else {
		TypeName typeName = outputParameterTypes.get(0);

		if (typeName instanceof ParameterizedTypeName) {
			ParameterizedTypeName parameterizedTypeName = (ParameterizedTypeName) typeName;
			methodBuilder.returns(buildRemoteCall(parameterizedTypeName.rawType));
			methodBuilder.addStatement("final $T function = new $T($N, $T.asList($L), $T.class, $L)", WasmFunction.class, WasmFunction.class,
					funcNameToConst(functionName), Arrays.class, inputParams, parameterizedTypeName.rawType,
					getParameterizedType(parameterizedTypeName));

			methodBuilder.addStatement("return executeRemoteCall(function, $T.class)", parameterizedTypeName.rawType);
		} else {
			methodBuilder.returns(buildRemoteCall(typeName));
			methodBuilder.addStatement("final $T function = new $T($N, $T.asList($L), $T.class)", WasmFunction.class, WasmFunction.class,
					funcNameToConst(functionName), Arrays.class, inputParams, typeName);
			methodBuilder.addStatement("return executeRemoteCall(function, $T.class)", typeName);
		}
	}
}
 
Example #5
Source File: SolidityFunctionWrapper.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
MethodSpec buildDefaultEventObservableFunction(
        String responseClassName,
        String functionName) {

    String generatedFunctionName =
            Strings.lowercaseFirstLetter(functionName) + "EventObservable";
    ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName.get(ClassName.get(rx
            .Observable.class), ClassName.get("", responseClassName));

    MethodSpec.Builder observableMethodBuilder =
            MethodSpec.methodBuilder(generatedFunctionName)
                    .addModifiers(Modifier.PUBLIC)
                    .addParameter(DefaultBlockParameter.class, START_BLOCK)
                    .addParameter(DefaultBlockParameter.class, END_BLOCK)
                    .returns(parameterizedTypeName);

    observableMethodBuilder.addStatement("$1T filter = new $1T($2L, $3L, "
            + "getContractAddress())", PlatonFilter.class, START_BLOCK, END_BLOCK)
            .addStatement("filter.addSingleTopic($T.encode("
                    + buildEventDefinitionName(functionName) + "))", EventEncoder.class)
            .addStatement("return " + generatedFunctionName + "(filter)");

    return observableMethodBuilder
            .build();
}
 
Example #6
Source File: WasmFunctionWrapper.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
MethodSpec buildDefaultEventObservableFunction(String responseClassName, String functionName) {

		String generatedFunctionName = Strings.lowercaseFirstLetter(functionName) + "EventObservable";
		ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName.get(ClassName.get(rx.Observable.class),
				ClassName.get("", responseClassName));

		MethodSpec.Builder observableMethodBuilder = MethodSpec.methodBuilder(generatedFunctionName).addModifiers(Modifier.PUBLIC)
				.addParameter(DefaultBlockParameter.class, START_BLOCK).addParameter(DefaultBlockParameter.class, END_BLOCK)
				.returns(parameterizedTypeName);

		observableMethodBuilder.addStatement("$1T filter = new $1T($2L, $3L, " + "getContractAddress())", PlatonFilter.class, START_BLOCK, END_BLOCK)
				.addStatement("filter.addSingleTopic($T.encode(" + buildEventDefinitionName(functionName) + "))", WasmEventEncoder.class)
				.addStatement("return " + generatedFunctionName + "(filter)");

		return observableMethodBuilder.build();
	}
 
Example #7
Source File: OpenApiClientGenerator.java    From spring-openapi with MIT License 6 votes vote down vote up
private FieldSpec.Builder parseTypeBasedSchema(String fieldName, Schema innerSchema, String targetPackage,
									   TypeSpec.Builder typeSpecBuilder) {
	if (innerSchema.getEnum() != null) {
		typeSpecBuilder.addType(createEnumClass(StringUtils.capitalize(fieldName), innerSchema).build());
		return createSimpleFieldSpec(null, StringUtils.capitalize(fieldName), fieldName, typeSpecBuilder);
	}
	if (equalsIgnoreCase(innerSchema.getType(), "string")) {
		return getStringBasedSchemaField(fieldName, innerSchema, typeSpecBuilder);
	} else if (equalsIgnoreCase(innerSchema.getType(), "integer") || equalsIgnoreCase(innerSchema.getType(), "number")) {
		return getNumberBasedSchemaField(fieldName, innerSchema, typeSpecBuilder);
	} else if (equalsIgnoreCase(innerSchema.getType(), "boolean")) {
		return createSimpleFieldSpec(JAVA_LANG_PKG, "Boolean", fieldName, typeSpecBuilder);
	} else if (equalsIgnoreCase(innerSchema.getType(), "array") && innerSchema instanceof ArraySchema) {
		ArraySchema arraySchema = (ArraySchema) innerSchema;
		ParameterizedTypeName listParameterizedTypeName = ParameterizedTypeName.get(
				ClassName.get("java.util", "List"),
				determineTypeName(arraySchema.getItems(), targetPackage)
		);
		enrichWithGetSetList(typeSpecBuilder, listParameterizedTypeName, fieldName);
		return FieldSpec.builder(listParameterizedTypeName, fieldName, Modifier.PRIVATE);
	}
	return createSimpleFieldSpec(JAVA_LANG_PKG, "Object", fieldName, typeSpecBuilder);
}
 
Example #8
Source File: SolidityFunctionWrapper.java    From etherscan-explorer with GNU General Public License v3.0 6 votes vote down vote up
MethodSpec buildDefaultEventObservableFunction(
        String responseClassName,
        String functionName) {

    String generatedFunctionName =
            Strings.lowercaseFirstLetter(functionName) + "EventObservable";
    ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName.get(ClassName.get(rx
            .Observable.class), ClassName.get("", responseClassName));

    MethodSpec.Builder observableMethodBuilder =
            MethodSpec.methodBuilder(generatedFunctionName)
                    .addModifiers(Modifier.PUBLIC)
                    .addParameter(DefaultBlockParameter.class, START_BLOCK)
                    .addParameter(DefaultBlockParameter.class, END_BLOCK)
                    .returns(parameterizedTypeName);

    observableMethodBuilder.addStatement("$1T filter = new $1T($2L, $3L, "
            + "getContractAddress())", EthFilter.class, START_BLOCK, END_BLOCK)
            .addStatement("filter.addSingleTopic($T.encode("
                    + buildEventDefinitionName(functionName) + "))", EventEncoder.class)
            .addStatement("return " + generatedFunctionName + "(filter)");

    return observableMethodBuilder
            .build();
}
 
Example #9
Source File: PresenterCreator.java    From tysq-android with GNU General Public License v3.0 6 votes vote down vote up
public void create() throws IOException {
    String viewName = ClzNameHelper.getInstance().getName(ClzNameHelper.VIEW);
    ClassName viewClz = ClassName.get(pkgName, viewName);

    // 构建构造函数
    MethodSpec constructorMethod = MethodSpec.constructorBuilder()  // 构建构造函数类型
            .addModifiers(Modifier.PUBLIC)      // public
            .addAnnotation(Inject.class)    // 添加 Inject 注解:@Inject
            .addParameter(viewClz, "view")  // 添加 参数(XXXView view)
            .addStatement("super(view)")  // 添加语句: super(view)
            .build();

    // 生成接口类
    TypeSpec typeSpec = TypeSpec
            .classBuilder(clzName)      // 类名
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)  // 类型限定付
            .superclass(ParameterizedTypeName
                    .get(ClassName.get(ClzNameHelper.getInstance().getClass(ClzNameHelper.PRESENTER)),
                            viewClz))  // 继承BasePresenter类
            .addMethod(constructorMethod)
            .build();

    JavaPencil.write(path, pkgName, typeSpec);

}
 
Example #10
Source File: ModuleGenerator.java    From nalu with Apache License 2.0 6 votes vote down vote up
private void generateGetRouteConfigs(TypeSpec.Builder typeSpec) {
  // generate method 'generateLoadShells()'
  MethodSpec.Builder loadRouteConfigMethodBuilder = MethodSpec.methodBuilder("getRouteConfigs")
                                                              .addModifiers(Modifier.PUBLIC)
                                                              .addAnnotation(Override.class)
                                                              .returns(ParameterizedTypeName.get(ClassName.get(List.class),
                                                                                                 ClassName.get(RouteConfig.class)))
                                                              .addStatement("$T<$T> list = new $T<>()",
                                                                            ClassName.get(List.class),
                                                                            ClassName.get(RouteConfig.class),
                                                                            ClassName.get(ArrayList.class));
  this.metaModel.getControllers()
                .forEach(route -> loadRouteConfigMethodBuilder.addStatement("list.add(new $T($S, $T.asList(new String[]{$L}), $S, $S))",
                                                                            ClassName.get(RouteConfig.class),
                                                                            createRoute(route.getRoute()),
                                                                            ClassName.get(Arrays.class),
                                                                            createParaemter(route.getParameters()),
                                                                            route.getSelector(),
                                                                            route.getProvider()
                                                                                 .getClassName()));
  loadRouteConfigMethodBuilder.addStatement("return list");
  typeSpec.addMethod(loadRouteConfigMethodBuilder.build());
}
 
Example #11
Source File: ModuleGenerator.java    From nalu with Apache License 2.0 6 votes vote down vote up
private void generateGetCompositeReferences(TypeSpec.Builder typeSpec) {
  MethodSpec.Builder getCompositeReferencesMethod = MethodSpec.methodBuilder("getCompositeReferences")
                                                              .addModifiers(Modifier.PUBLIC)
                                                              .addAnnotation(Override.class)
                                                              .returns(ParameterizedTypeName.get(ClassName.get(List.class),
                                                                                                 ClassName.get(CompositeControllerReference.class)))
                                                              .addStatement("$T<$T> list = new $T<>()",
                                                                            ClassName.get(List.class),
                                                                            ClassName.get(CompositeControllerReference.class),
                                                                            ClassName.get(ArrayList.class));
  this.metaModel.getControllers()
                .forEach(controllerModel -> controllerModel.getComposites()
                                                           .forEach(controllerCompositeModel -> getCompositeReferencesMethod.addStatement("list.add(new $T($S, $S, $S, $S))",
                                                                                                                                          ClassName.get(CompositeControllerReference.class),
                                                                                                                                          controllerModel.getProvider()
                                                                                                                                                         .getClassName(),
                                                                                                                                          controllerCompositeModel.getName(),
                                                                                                                                          controllerCompositeModel.getComposite()
                                                                                                                                                                  .getClassName(),
                                                                                                                                          controllerCompositeModel.getSelector())));
  getCompositeReferencesMethod.addStatement("return list");
  typeSpec.addMethod(getCompositeReferencesMethod.build());
}
 
Example #12
Source File: LibraryConfigAnnotationParser.java    From aircon with MIT License 6 votes vote down vote up
private TypeName getType(boolean raw) {
	final ConfigKind kind = getKind();
	if (kind == ConfigKind.STRING_SET) {
		return ParameterizedTypeName.get(ClassName.get(Set.class), TypeVariableName.get(String.class));
	}

	final TypeName rawType = TypeName.get(Objects.requireNonNull(getAttribute(ATTRIBUTE_DEFAULT_VALUE))
	                                             .getClass());

	if (raw) {
		return rawType;
	}

	if (kind == ConfigKind.ENUM) {
		return TypeName.get(getEnumClass());
	}
	else if (kind == ConfigKind.JSON) {
		return getJsonType();
	}
	else if (kind == ConfigKind.COLOR) {
		return ColorIntClassDescriptor.CLASS_NAME;
	}

	return rawType;
}
 
Example #13
Source File: WasmFunctionWrapper.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
public static String getArgsType(ParameterizedTypeName parameterizedTypeName) {
	StringBuilder builder = new StringBuilder();
	for (int i = 0; i < parameterizedTypeName.typeArguments.size(); i++) {
		TypeName argType = parameterizedTypeName.typeArguments.get(i);
		if (argType instanceof ParameterizedTypeName) {
			builder.append(getParameterizedType((ParameterizedTypeName) argType));
		} else {
			if (argType instanceof ArrayTypeName) {
				builder.append(((ArrayTypeName) argType).toString() + ".class");
			} else {
				builder.append(((ClassName) argType).toString() + ".class");
			}
		}
		if (i < parameterizedTypeName.typeArguments.size() - 1) {
			builder.append(", ");
		}
	}
	return builder.toString();
}
 
Example #14
Source File: InjectProcessor.java    From customview-samples with Apache License 2.0 6 votes vote down vote up
private TypeSpec createRepotityTypeSpec(ClassName builderClassName,List<ClassName> factoryList) {
    ClassName list = ClassName.get("java.util", "List");
    ClassName arrayList = ClassName.get("java.util", "ArrayList");
    TypeName listType = ParameterizedTypeName.get(list, ClassName.get("java.lang","Class"));

    FieldSpec fieldSpec = FieldSpec.builder(listType, "sDataList")
            .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
            .initializer("new $T()", arrayList)
            .build();

    CodeBlock.Builder blockBuilder = CodeBlock.builder();
    for(int i =0; i< factoryList.size();i++){
        blockBuilder.addStatement("sDataList.add($T.class)",factoryList.get(i));
    }

    return TypeSpec
            .classBuilder(builderClassName)
            .addModifiers(Modifier.PUBLIC)
            .addStaticBlock(blockBuilder.build())
            .addField(fieldSpec)
            .build();
}
 
Example #15
Source File: ReactPropertyProcessor.java    From react-native-GPay with MIT License 6 votes vote down vote up
private TypeName getTargetType(TypeMirror mirror) {
  TypeName typeName = TypeName.get(mirror);
  if (typeName instanceof ParameterizedTypeName) {
    ParameterizedTypeName parameterizedTypeName = (ParameterizedTypeName) typeName;
    if (parameterizedTypeName.rawType.equals(VIEW_MANAGER_TYPE)) {
      return parameterizedTypeName.typeArguments.get(0);
    }
  } else if (isShadowNodeType(typeName)) {
    return SHADOW_NODE_IMPL_TYPE;
  } else if (typeName.equals(TypeName.OBJECT)) {
    throw new IllegalArgumentException("Could not find target type " + typeName);
  }

  List<? extends TypeMirror> types = mTypes.directSupertypes(mirror);
  return getTargetType(types.get(0));
}
 
Example #16
Source File: ResourceInterfaceGenerator.java    From spring-openapi with MIT License 6 votes vote down vote up
private ParameterSpec.Builder parseTypeBasedSchema(String parameterName, Schema innerSchema) {
	if (equalsIgnoreCase(innerSchema.getType(), "string")) {
		return ParameterSpec.builder(getStringGenericClassName(innerSchema), parameterName);
	} else if (equalsIgnoreCase(innerSchema.getType(), "integer") || equalsIgnoreCase(innerSchema.getType(), "number")) {
		return getNumberBasedSchemaParameter(parameterName, innerSchema);
	} else if (equalsIgnoreCase(innerSchema.getType(), "boolean")) {
		return createSimpleParameterSpec(JAVA_LANG_PKG, "Boolean", parameterName);
	} else if (equalsIgnoreCase(innerSchema.getType(), "array") && innerSchema instanceof ArraySchema) {
		ArraySchema arraySchema = (ArraySchema) innerSchema;
		ParameterizedTypeName listParameterizedTypeName = ParameterizedTypeName.get(
				ClassName.get("java.util", "List"),
				determineTypeName(arraySchema.getItems())
		);
		return ParameterSpec.builder(listParameterizedTypeName, parameterName);
	} else if (equalsIgnoreCase(innerSchema.getType(), "object") && isFile(innerSchema.getProperties())) {
		return ParameterSpec.builder(ClassName.get(File.class), parameterName);
	}
	return createSimpleParameterSpec(JAVA_LANG_PKG, "Object", parameterName);
}
 
Example #17
Source File: AnnotatedClass.java    From WandFix with MIT License 5 votes vote down vote up
public JavaFile generateFile() {
    //generateMethod
    MethodSpec.Builder injectMethod = MethodSpec.methodBuilder("inject")
            .addModifiers(Modifier.PUBLIC)
            .addAnnotation(Override.class)
            .addParameter(TypeName.get(mTypeElement.asType()), "host", Modifier.FINAL)
            .addParameter(TypeName.OBJECT, "source")
            .addParameter(TypeUtil.PROVIDER, "provider");

    for (InjectObjectField field : mObjectFields) {
        // find views
        injectMethod.addStatement("host.$N = ($T)(provider.make(source, \"$L\" ,$L))",
                field.getFieldName(),
                ClassName.get(field.getFieldType()),
                field.getClassName(),
                field.getmLevel());
    }

    //generaClass
    TypeSpec injectClass = TypeSpec.classBuilder(mTypeElement.getSimpleName() + "$$ObjectInject")
            .addModifiers(Modifier.PUBLIC)
            .addSuperinterface(ParameterizedTypeName.get(TypeUtil.INJET, TypeName.get(mTypeElement.asType())))
            .addMethod(injectMethod.build())
            .build();

    String packgeName = mElements.getPackageOf(mTypeElement).getQualifiedName().toString();

    return JavaFile
            .builder(packgeName, injectClass)
            .addStaticImport(ParentalEntrustmentLevel.class,
                    "NEVER", "PROJECT", "ANDROID", "JAVA"
            )
            .build();
}
 
Example #18
Source File: SolidityFunctionWrapper.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
static TypeName getNativeType(TypeName typeName) {

        if (typeName instanceof ParameterizedTypeName) {
            return getNativeType((ParameterizedTypeName) typeName);
        }

        String simpleName = ((ClassName) typeName).simpleName();

        if (simpleName.equals(Address.class.getSimpleName())) {
            return TypeName.get(String.class);
        } else if (simpleName.startsWith("Uint")) {
            return TypeName.get(BigInteger.class);
        } else if (simpleName.startsWith("Int")) {
            return TypeName.get(BigInteger.class);
        } else if (simpleName.equals(Utf8String.class.getSimpleName())) {
            return TypeName.get(String.class);
        } else if (simpleName.startsWith("Bytes")) {
            return TypeName.get(byte[].class);
        } else if (simpleName.equals(DynamicBytes.class.getSimpleName())) {
            return TypeName.get(byte[].class);
        } else if (simpleName.equals(Bool.class.getSimpleName())) {
            return TypeName.get(Boolean.class);  // boolean cannot be a parameterized type
        } else {
            throw new UnsupportedOperationException(
                    "Unsupported type: " + typeName
                            + ", no native type mapping exists.");
        }
    }
 
Example #19
Source File: SolidityFunctionWrapper.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
static TypeName getNativeType(ParameterizedTypeName parameterizedTypeName) {
    List<TypeName> typeNames = parameterizedTypeName.typeArguments;
    List<TypeName> nativeTypeNames = new ArrayList<>(typeNames.size());
    for (TypeName enclosedTypeName : typeNames) {
        nativeTypeNames.add(getNativeType(enclosedTypeName));
    }
    return ParameterizedTypeName.get(
            ClassName.get(List.class),
            nativeTypeNames.toArray(new TypeName[nativeTypeNames.size()]));
}
 
Example #20
Source File: ControllerCreatorGenerator.java    From nalu with Apache License 2.0 5 votes vote down vote up
public void generate()
    throws ProcessorException {
  TypeSpec.Builder typeSpec = TypeSpec.classBuilder(controllerModel.getController()
                                                                   .getSimpleName() + ProcessorConstants.CREATOR_IMPL)
                                      .addJavadoc(BuildWithNaluCommentProvider.get()
                                                                              .getGeneratedComment())
                                      .superclass(ParameterizedTypeName.get(ClassName.get(AbstractControllerCreator.class),
                                                                            controllerModel.getContext()
                                                                                           .getTypeName()))
                                      .addModifiers(Modifier.PUBLIC,
                                                    Modifier.FINAL)
                                      .addSuperinterface(ClassName.get(IsControllerCreator.class));
  typeSpec.addMethod(createConstructor());
  typeSpec.addMethod(createCreateMethod());
  typeSpec.addMethod(createFinishCreateMethod());
  typeSpec.addMethod(createSetParameterMethod());

  JavaFile javaFile = JavaFile.builder(controllerModel.getController()
                                                      .getPackage(),
                                       typeSpec.build())
                              .build();
  try {
    //      System.out.println(javaFile.toString());
    javaFile.writeTo(this.processingEnvironment.getFiler());
  } catch (IOException e) {
    throw new ProcessorException("Unable to write generated file: >>" +
                                 controllerModel.getController()
                                                .getSimpleName() +
                                 ProcessorConstants.CREATOR_IMPL +
                                 "<< -> exception: " +
                                 e.getMessage());
  }
}
 
Example #21
Source File: SolidityFunctionWrapperTest.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testGetEventNativeTypeParameterized() {
    assertThat(getEventNativeType(
            ParameterizedTypeName.get(
                    ClassName.get(DynamicArray.class), TypeName.get(Address.class))),
            equalTo(TypeName.get(byte[].class)));
}
 
Example #22
Source File: CompositeCreatorGenerator.java    From nalu with Apache License 2.0 5 votes vote down vote up
public void generate()
    throws ProcessorException {
  TypeSpec.Builder typeSpec = TypeSpec.classBuilder(compositeModel.getProvider()
                                                                  .getSimpleName() + ProcessorConstants.CREATOR_IMPL)
                                      .addJavadoc(BuildWithNaluCommentProvider.get()
                                                                              .getGeneratedComment())
                                      .superclass(ParameterizedTypeName.get(ClassName.get(AbstractCompositeCreator.class),
                                                                            compositeModel.getContext()
                                                                                          .getTypeName()))
                                      .addModifiers(Modifier.PUBLIC,
                                                    Modifier.FINAL)
                                      .addSuperinterface(ClassName.get(IsCompositeCreator.class));
  typeSpec.addMethod(createConstructor());
  typeSpec.addMethod(createCreateMethod());
  typeSpec.addMethod(createSetParameterMethod());

  JavaFile javaFile = JavaFile.builder(this.compositeModel.getProvider()
                                                          .getPackage(),
                                       typeSpec.build())
                              .build();
  try {
    //      System.out.println(javaFile.toString());
    javaFile.writeTo(this.processingEnvironment.getFiler());
  } catch (IOException e) {
    throw new ProcessorException("Unable to write generated file: >>" +
                                     this.compositeModel.getProvider()
                                                        .getClassName() +
                                     ProcessorConstants.CREATOR_IMPL +
                                     "<< -> exception: " +
                                     e.getMessage());
  }
}
 
Example #23
Source File: SolidityFunctionWrapperTest.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetEventNativeTypeParameterized() {
    assertThat(getEventNativeType(
            ParameterizedTypeName.get(
                    ClassName.get(DynamicArray.class), TypeName.get(Address.class))),
            equalTo(TypeName.get(byte[].class)));
}
 
Example #24
Source File: SolidityFunctionWrapper.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
private TypeName getWrapperRawType(TypeName typeName) {
    if (useNativeJavaTypes) {
        if (typeName instanceof ParameterizedTypeName) {
            return ClassName.get(List.class);
        }
        return getNativeType(typeName);
    } else {
        return typeName;
    }
}
 
Example #25
Source File: AbiTypesGenerator.java    From etherscan-explorer with 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 #26
Source File: Generator.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
private void addClientFieldsAndMethods(final State state, final TypeSpec.Builder typeSpecBuilder,
                                       final MethodSpec.Builder constructorBuilder,
                                       final boolean blocking) {

    final EnumSet<NewRpcMethodFlag> rpcMethodSpecsFlags =
            blocking ? EnumSet.of(BLOCKING, CLIENT) : EnumSet.of(CLIENT);

    state.clientMetaDatas.forEach(clientMetaData -> {
        final ClassName inClass = messageTypesMap.get(clientMetaData.methodProto.getInputType());
        final ClassName outClass = messageTypesMap.get(clientMetaData.methodProto.getOutputType());
        final String routeName = routeName(clientMetaData.methodProto);
        final String callFieldName = routeName + Call;

        typeSpecBuilder
                .addField(ParameterizedTypeName.get(clientCallClass(clientMetaData.methodProto, blocking),
                        inClass, outClass), callFieldName, PRIVATE, FINAL)
                .addMethod(newRpcMethodSpec(clientMetaData.methodProto, rpcMethodSpecsFlags,
                        (n, b) -> b.addAnnotation(Override.class)
                                .addStatement("return $L($T.$L, $L)", n, clientMetaData.className, INSTANCE,
                                        request)))
                .addMethod(newRpcMethodSpec(clientMetaData.methodProto, rpcMethodSpecsFlags,
                        (__, b) -> b.addAnnotation(Override.class)
                                .addParameter(clientMetaData.className, metadata, FINAL)
                                .addStatement("return $L.$L($L, $L)", callFieldName, request, metadata, request)));

        constructorBuilder
                .addStatement("$L = $N.$L($L, $T.class, $T.class)", callFieldName, factory,
                        newCallMethodName(clientMetaData.methodProto, blocking), serializationProvider, inClass,
                        outClass);
    });
}
 
Example #27
Source File: Generator.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
private TypeSpec newServiceFromRoutesClassSpec(final ClassName serviceFromRoutesClass,
                                               final List<RpcInterface> rpcInterfaces,
                                               final ClassName serviceClass) {
    final TypeSpec.Builder serviceFromRoutesSpecBuilder = classBuilder(serviceFromRoutesClass)
            .addModifiers(PRIVATE, STATIC, FINAL)
            .addSuperinterface(serviceClass)
            .addField(AsyncCloseable, closeable, PRIVATE, FINAL);

    final MethodSpec.Builder serviceFromRoutesConstructorBuilder = constructorBuilder()
            .addModifiers(PRIVATE)
            .addParameter(AllGrpcRoutes, routes, FINAL)
            .addStatement("$L = $L", closeable, routes);

    rpcInterfaces.stream().filter(rpcInterface -> !rpcInterface.blocking).forEach(rpc -> {
        MethodDescriptorProto methodProto = rpc.methodProto;
        final ClassName inClass = messageTypesMap.get(methodProto.getInputType());
        final ClassName outClass = messageTypesMap.get(methodProto.getOutputType());
        final String routeName = routeName(methodProto);

        serviceFromRoutesSpecBuilder.addField(ParameterizedTypeName.get(routeInterfaceClass(methodProto),
                inClass, outClass), routeName, PRIVATE, FINAL);

        serviceFromRoutesConstructorBuilder.addStatement("$L = $L.$L($T.$L)", routeName, routes,
                routeFactoryMethodName(methodProto), rpc.className, RPC_PATH);

        serviceFromRoutesSpecBuilder.addMethod(newRpcMethodSpec(methodProto, noneOf(NewRpcMethodFlag.class),
                (name, builder) ->
                        builder.addAnnotation(Override.class)
                                .addParameter(GrpcServiceContext, ctx, FINAL)
                                .addStatement("return $L.handle($L, $L)", routeName, ctx, request)));
    });

    serviceFromRoutesSpecBuilder
            .addMethod(serviceFromRoutesConstructorBuilder.build())
            .addMethod(newDelegatingCompletableMethodSpec(closeAsync, closeable))
            .addMethod(newDelegatingCompletableMethodSpec(closeAsyncGracefully, closeable));

    return serviceFromRoutesSpecBuilder.build();
}
 
Example #28
Source File: Generator.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
private void addClientInterfaces(final State state, final TypeSpec.Builder serviceClassBuilder) {
    state.clientClass = ClassName.bestGuess(sanitizeIdentifier(state.serviceProto.getName(), false) + "Client");
    state.filterableClientClass = state.clientClass.peerClass("Filterable" + state.clientClass.simpleName());
    state.blockingClientClass = state.clientClass.peerClass(Blocking + state.clientClass.simpleName());

    final TypeSpec.Builder clientSpecBuilder = interfaceBuilder(state.clientClass)
            .addModifiers(PUBLIC)
            .addSuperinterface(state.filterableClientClass)
            .addSuperinterface(ParameterizedTypeName.get(GrpcClient, state.blockingClientClass));

    final TypeSpec.Builder filterableClientSpecBuilder = interfaceBuilder(state.filterableClientClass)
            .addModifiers(PUBLIC)
            .addSuperinterface(FilterableGrpcClient);

    final TypeSpec.Builder blockingClientSpecBuilder = interfaceBuilder(state.blockingClientClass)
            .addModifiers(PUBLIC)
            .addSuperinterface(ParameterizedTypeName.get(BlockingGrpcClient, state.clientClass));

    state.clientMetaDatas.forEach(clientMetaData -> {
        clientSpecBuilder
                .addMethod(newRpcMethodSpec(clientMetaData.methodProto, EnumSet.of(INTERFACE, CLIENT),
                        (__, b) -> b.addModifiers(ABSTRACT)));

        filterableClientSpecBuilder
                .addMethod(newRpcMethodSpec(clientMetaData.methodProto, EnumSet.of(INTERFACE, CLIENT),
                        (__, b) -> b.addModifiers(ABSTRACT)
                                .addParameter(clientMetaData.className, metadata)));

        blockingClientSpecBuilder
                .addMethod(newRpcMethodSpec(clientMetaData.methodProto, EnumSet.of(BLOCKING, INTERFACE, CLIENT),
                        (__, b) -> b.addModifiers(ABSTRACT)))
                .addMethod(newRpcMethodSpec(clientMetaData.methodProto, EnumSet.of(BLOCKING, INTERFACE, CLIENT),
                        (__, b) -> b.addModifiers(ABSTRACT)
                                .addParameter(clientMetaData.className, metadata)));
    });

    serviceClassBuilder.addType(clientSpecBuilder.build())
            .addType(filterableClientSpecBuilder.build())
            .addType(blockingClientSpecBuilder.build());
}
 
Example #29
Source File: Generator.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
private void addServiceFilterFactory(final State state, final TypeSpec.Builder serviceClassBuilder) {
    state.serviceFilterFactoryClass = state.serviceFilterClass.peerClass(state.serviceFilterClass.simpleName() +
            Factory);

    serviceClassBuilder.addType(interfaceBuilder(state.serviceFilterFactoryClass)
            .addModifiers(PUBLIC)
            .addSuperinterface(ParameterizedTypeName.get(GrpcServiceFilterFactory, state.serviceFilterClass,
                    state.serviceClass))
            .build());
}
 
Example #30
Source File: Generator.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
private void addClientFilterFactory(final State state, final TypeSpec.Builder serviceClassBuilder) {
    state.clientFilterFactoryClass = state.clientFilterClass.peerClass(state.clientFilterClass.simpleName() +
            Factory);

    serviceClassBuilder.addType(interfaceBuilder(state.clientFilterFactoryClass)
            .addModifiers(PUBLIC)
            .addSuperinterface(ParameterizedTypeName.get(GrpcClientFilterFactory, state.clientFilterClass,
                    state.filterableClientClass))
            .build());
}