Java Code Examples for com.squareup.javapoet.ParameterizedTypeName

The following examples show how to use com.squareup.javapoet.ParameterizedTypeName. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: spring-openapi   Author: jrcodeza   File: OpenApiClientGenerator.java    License: 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 #2
Source Project: spring-openapi   Author: jrcodeza   File: ResourceInterfaceGenerator.java    License: 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 #3
Source Project: aircon   Author: ironSource   File: LibraryConfigAnnotationParser.java    License: 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 #4
Source Project: tysq-android   Author: tysqapp   File: PresenterCreator.java    License: 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 #5
Source Project: client-sdk-java   Author: PlatONnetwork   File: WasmFunctionWrapper.java    License: 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 #6
Source Project: client-sdk-java   Author: PlatONnetwork   File: WasmFunctionWrapper.java    License: 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 #7
Source Project: client-sdk-java   Author: PlatONnetwork   File: WasmFunctionWrapper.java    License: 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 #8
Source Project: client-sdk-java   Author: PlatONnetwork   File: WasmFunctionWrapper.java    License: 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 #9
Source Project: client-sdk-java   Author: PlatONnetwork   File: WasmFunctionWrapper.java    License: 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 #10
Source Project: client-sdk-java   Author: PlatONnetwork   File: SolidityFunctionWrapper.java    License: 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 #11
Source Project: etherscan-explorer   Author: bing-chou   File: SolidityFunctionWrapper.java    License: 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 #12
Source Project: nalu   Author: NaluKit   File: ModuleGenerator.java    License: 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 #13
Source Project: nalu   Author: NaluKit   File: ModuleGenerator.java    License: 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 #14
Source Project: nalu   Author: NaluKit   File: ModuleGenerator.java    License: 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 #15
Source Project: customview-samples   Author: hyhdy   File: InjectProcessor.java    License: 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 #16
Source Project: react-native-GPay   Author: hellochirag   File: ReactPropertyProcessor.java    License: 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 #17
Source Project: spring-openapi   Author: jrcodeza   File: OpenApiClientGenerator.java    License: MIT License 5 votes vote down vote up
private void enrichWithGetSetList(TypeSpec.Builder typeSpecBuilder, ParameterizedTypeName parameterizedTypeName, String fieldName) {
	typeSpecBuilder.addMethod(MethodSpec.methodBuilder("set" + StringUtils.capitalize(fieldName))
			.addParameter(ParameterSpec.builder(parameterizedTypeName, fieldName).build())
			.addModifiers(Modifier.PUBLIC)
			.addStatement(String.format("this.%s = %s", fieldName, fieldName))
			.returns(TypeName.VOID)
			.build());
	typeSpecBuilder.addMethod(MethodSpec.methodBuilder("get" + StringUtils.capitalize(fieldName))
			.addModifiers(Modifier.PUBLIC)
			.addStatement(String.format("return this.%s", fieldName))
			.returns(parameterizedTypeName)
			.build());
}
 
Example #18
Source Project: aircon   Author: ironSource   File: LibraryConfigAnnotationParser.java    License: MIT License 5 votes vote down vote up
private TypeName getJsonType() {
	final TypeMirror jsonType = getAnnotationJsonType();
	final List<? extends TypeMirror> jsonGenericTypes = getJsonGenericTypes();
	if (jsonGenericTypes != null && !jsonGenericTypes.isEmpty()) {
		return ParameterizedTypeName.get(ClassName.bestGuess(jsonType.toString()), getGenericTypeNames(jsonGenericTypes));
	}
	else {
		return TypeName.get(jsonType);
	}
}
 
Example #19
Source Project: SmartEventBus   Author: JeremyLiao   File: InvokingMessageProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private String generateEventInterfaceClass(List<EventInfo> events, String originalPackageName, String originalClassName) {
    String interfaceName = generateClassName(originalClassName);
    TypeSpec.Builder builder = TypeSpec.interfaceBuilder(interfaceName)
            .addModifiers(Modifier.PUBLIC)
            .addSuperinterface(IEventsDefine.class)
            .addJavadoc("Auto generate code, do not modify!!!");
    for (EventInfo event : events) {
        ClassName lebClassName = ClassName.get(LEB_PACKAGE_NAME, LEB_CLASS_NAME);
        ClassName obsClassName = lebClassName.nestedClass(LEB_OBSERVER_CLASS_NAME);
        TypeName returnType;
        String eventTypeStr = event.getType();
        if (eventTypeStr == null || eventTypeStr.length() == 0) {
            returnType = ParameterizedTypeName.get(obsClassName, ClassName.get(Object.class));
        } else {
            Type eventType = getType(eventTypeStr);
            if (eventType != null) {
                returnType = ParameterizedTypeName.get(obsClassName, ClassName.get(eventType));
            } else {
                returnType = ParameterizedTypeName.get(obsClassName, TypeVariableName.get(eventTypeStr));
            }
        }
        MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(event.getName())
                .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
                .returns(returnType);
        builder.addMethod(methodBuilder.build());
    }
    TypeSpec typeSpec = builder.build();
    String packageName = originalPackageName + GEN_PKG;
    try {
        JavaFile.builder(packageName, typeSpec)
                .build()
                .writeTo(filer);
    } catch (IOException e) {
        e.printStackTrace();
    }
    String className = packageName + "." + interfaceName;
    System.out.println(TAG + "generateEventInterfaceClass: " + className);
    return className;
}
 
Example #20
Source Project: SmartEventBus   Author: JeremyLiao   File: SmartEventProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private void generateBusCode() {
    if (eventInfos == null || eventInfos.size() == 0) {
        return;
    }
    if (packageName == null || packageName.length() == 0) {
        packageName = defaultPackageName;
    }
    String className = (busName != null && busName.length() > 0) ? busName : DEFAULT_BUS_NAME;
    TypeSpec.Builder builder = TypeSpec.classBuilder(className)
            .addModifiers(Modifier.PUBLIC)
            .addJavadoc("Auto generate code, do not modify!!!");
    for (EventInfo eventInfo : eventInfos) {
        //添加每一个方法
        MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(eventInfo.getKey())
                .addModifiers(Modifier.PUBLIC, Modifier.STATIC);
        //添加return
        ClassName baseClassName = ClassName.get(OBSERVABLE_PACKAGE_NAME, OBSERVABLE_CLASS_NAME);
        TypeName typeName = getTypeName(eventInfo.getType());
        TypeName returnType = ParameterizedTypeName.get(baseClassName, typeName);
        methodBuilder.returns(returnType);
        //添加方法体
        ClassName lebClass = ClassName.get(EVENTBUS_PACKAGE_NAME, EVENTBUS_CLASS_NAME);
        methodBuilder.addStatement("return $T.get($S, $T.class)",
                lebClass, eventInfo.getKey(), typeName);

        builder.addMethod(methodBuilder.build());
    }

    TypeSpec typeSpec = builder.build();
    try {
        JavaFile.builder(packageName, typeSpec)
                .build()
                .writeTo(filer);
        isGenerateTargetClass = true;
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #21
Source Project: client-sdk-java   Author: PlatONnetwork   File: AbiTypesGenerator.java    License: Apache License 2.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 #22
Source Project: client-sdk-java   Author: PlatONnetwork   File: SolidityFunctionWrapper.java    License: Apache License 2.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 #23
Source Project: client-sdk-java   Author: PlatONnetwork   File: SolidityFunctionWrapper.java    License: Apache License 2.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 #24
Source Project: client-sdk-java   Author: PlatONnetwork   File: SolidityFunctionWrapper.java    License: Apache License 2.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 #25
Source Project: client-sdk-java   Author: PlatONnetwork   File: SolidityFunctionWrapper.java    License: Apache License 2.0 5 votes vote down vote up
static TypeName getEventNativeType(TypeName typeName) {
    if (typeName instanceof ParameterizedTypeName) {
        return TypeName.get(byte[].class);
    }

    String simpleName = ((ClassName) typeName).simpleName();
    if (simpleName.equals(Utf8String.class.getSimpleName())) {
        return TypeName.get(byte[].class);
    } else {
        return getNativeType(typeName);
    }
}
 
Example #26
Source Project: client-sdk-java   Author: PlatONnetwork   File: SolidityFunctionWrapper.java    License: Apache License 2.0 5 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,
            Contract.EventValuesWithLog.class))
            .addStatement("$1T responses = new $1T(valueList.size())",
                    ParameterizedTypeName.get(ClassName.get(ArrayList.class),
                            ClassName.get("", responseClassName)))
            .beginControlFlow("for ($T eventValues : valueList)",
                    Contract.EventValuesWithLog.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 #27
Source Project: client-sdk-java   Author: PlatONnetwork   File: AbiTypesMapperGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void generate(String destinationDir) throws IOException {

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

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

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

        MethodSpec methodSpec = builder.build();

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

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

        write(autoGeneratedTypesPackageName, typeSpec, destinationDir);
    }
 
Example #28
Source Project: client-sdk-java   Author: PlatONnetwork   File: SolidityFunctionWrapperTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildTypeName() {
    assertThat(buildTypeName("uint256"),
            is(ClassName.get(Uint256.class)));
    assertThat(buildTypeName("uint64"),
            is(ClassName.get(Uint64.class)));
    assertThat(buildTypeName("string"),
            is(ClassName.get(Utf8String.class)));

    assertThat(buildTypeName("uint256[]"),
            is(ParameterizedTypeName.get(DynamicArray.class, Uint256.class)));

    assertThat(buildTypeName("uint256[] storage"),
            is(ParameterizedTypeName.get(DynamicArray.class, Uint256.class)));

    assertThat(buildTypeName("uint256[] memory"),
            is(ParameterizedTypeName.get(DynamicArray.class, Uint256.class)));

    assertThat(buildTypeName("uint256[10]"),
            is(ParameterizedTypeName.get(StaticArray10.class, Uint256.class)));

    assertThat(buildTypeName("uint256[33]"),
            is(ParameterizedTypeName.get(StaticArray.class, Uint256.class)));

    assertThat(buildTypeName("uint256[10][3]"),
            is(ParameterizedTypeName.get(ClassName.get(StaticArray3.class),
                    ParameterizedTypeName.get(StaticArray10.class, Uint256.class))));

    assertThat(buildTypeName("uint256[2][]"),
            is(ParameterizedTypeName.get(ClassName.get(DynamicArray.class),
                    ParameterizedTypeName.get(StaticArray2.class, Uint256.class))));

    assertThat(buildTypeName("uint256[33][]"),
            is(ParameterizedTypeName.get(ClassName.get(DynamicArray.class),
                    ParameterizedTypeName.get(StaticArray.class, Uint256.class))));

    assertThat(buildTypeName("uint256[][]"),
            is(ParameterizedTypeName.get(ClassName.get(DynamicArray.class),
                    ParameterizedTypeName.get(DynamicArray.class, Uint256.class))));
}
 
Example #29
Source Project: client-sdk-java   Author: PlatONnetwork   File: SolidityFunctionWrapperTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetNativeTypeParameterized() {
    assertThat(getNativeType(
            ParameterizedTypeName.get(
                    ClassName.get(DynamicArray.class), TypeName.get(Address.class))),
            equalTo(ParameterizedTypeName.get(
                    ClassName.get(List.class), TypeName.get(String.class))));
}
 
Example #30
Source Project: client-sdk-java   Author: PlatONnetwork   File: SolidityFunctionWrapperTest.java    License: 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)));
}