Java Code Examples for com.squareup.javapoet.TypeSpec#classBuilder()

The following examples show how to use com.squareup.javapoet.TypeSpec#classBuilder() . 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: DelombokTest.java    From gradle-plugins with MIT License 6 votes vote down vote up
@Test
public void simpleDelombokTest() {
    createGradleConfiguration()
            .applyPlugin("java")
            .applyPlugin("io.freefair.lombok")
            .addCustomConfigurationBlock("delombok.target = file('src/main-delombok/java/')")
            .write();

    TypeSpec.Builder builder = TypeSpec.classBuilder("SimpleLombokFile");
    builder.addField(FieldSpec.builder(String.class, "name", Modifier.PRIVATE).build());
    builder.addField(FieldSpec.builder(String.class, "firstName", Modifier.PRIVATE).build());
    builder.addField(FieldSpec.builder(TypeName.INT, "age", Modifier.PRIVATE).build());
    builder.addAnnotation(AnnotationSpec.builder(lombok.Data.class).build());

    createJavaClass("main", "io.freefair.gradle.plugins.lombok.test", builder.build());

    executeTask("build", "delombok", "--debug");
    String simpleLombokFile = readJavaClass("main-delombok", "io.freefair.gradle.plugins.lombok.test", "SimpleLombokFile");
    assertThat(simpleLombokFile, not(containsString("lombok.Data")));
}
 
Example 2
Source File: ModelDeletingGenerator.java    From sqlitemagic with Apache License 2.0 6 votes vote down vote up
private TypeSpec deleteTable(EntityEnvironment entityEnvironment) {
  final String className = CLASS_DELETE_TABLE;
  final TypeName createdClassTypeName = getHandlerInnerClassName(entityEnvironment, className);
  final MethodSpec deleteTableExecute = deleteTableExecute(entityEnvironment);
  final TypeSpec.Builder builder = TypeSpec.classBuilder(className);
  builder.addSuperinterface(ENTITY_DELETE_TABLE_BUILDER)
      .addModifiers(PUBLIC_STATIC_FINAL)
      .addField(FieldSpec.builder(DB_CONNECTION_IMPL, DB_CONNECTION_VARIABLE, PRIVATE)
          .addAnnotation(NULLABLE)
          .build())
      .addMethod(MethodSpec.constructorBuilder()
          .addModifiers(Modifier.PRIVATE)
          .build())
      .addMethod(WriterUtil.createMagicInvokableMethod(EntityEnvironment.getGeneratedHandlerInnerClassName(entityEnvironment.getTableElement(), className), METHOD_CREATE)
          .addModifiers(STATIC_METHOD_MODIFIERS)
          .addAnnotation(CHECK_RESULT)
          .addStatement("return new $N()", className)
          .returns(createdClassTypeName)
          .build())
      .addMethod(connectionProviderMethod(ENTITY_DELETE_TABLE_BUILDER))
      .addMethod(deleteTableExecute)
      .addMethod(deleteTableObserve(builder, deleteTableExecute));
  return builder.build();
}
 
Example 3
Source File: DelombokTest.java    From gradle-plugins with MIT License 6 votes vote down vote up
@Test
public void simpleDelombokTest() {
    createGradleConfiguration()
            .applyPlugin("java")
            .applyPlugin("io.freefair.lombok")
            .addCustomConfigurationBlock("delombok.target = file('src/main-delombok/java/')")
            .write();

    TypeSpec.Builder builder = TypeSpec.classBuilder("SimpleLombokFile");
    builder.addField(FieldSpec.builder(String.class, "name", Modifier.PRIVATE).build());
    builder.addField(FieldSpec.builder(String.class, "firstName", Modifier.PRIVATE).build());
    builder.addField(FieldSpec.builder(TypeName.INT, "age", Modifier.PRIVATE).build());
    builder.addAnnotation(AnnotationSpec.builder(lombok.Data.class).build());

    createJavaClass("main", "io.freefair.gradle.plugins.lombok.test", builder.build());

    executeTask("build", "delombok", "--debug");
    String simpleLombokFile = readJavaClass("main-delombok", "io.freefair.gradle.plugins.lombok.test", "SimpleLombokFile");
    assertThat(simpleLombokFile, not(containsString("lombok.Data")));
}
 
Example 4
Source File: GeneratedAnnotationsTest.java    From auto with Apache License 2.0 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
  if (first) {
    TypeSpec.Builder type = TypeSpec.classBuilder("G");
    GeneratedAnnotationSpecs.generatedAnnotationSpec(
            processingEnv.getElementUtils(),
            processingEnv.getSourceVersion(),
            TestProcessor.class)
        .ifPresent(type::addAnnotation);
    JavaFile javaFile = JavaFile.builder("", type.build()).build();
    try {
      javaFile.writeTo(processingEnv.getFiler());
    } catch (IOException e) {
      throw new UncheckedIOException(e);
    }
    first = false;
  }
  return false;
}
 
Example 5
Source File: SolidityFunctionWrapperTest.java    From web3j with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildFuncNameConstants() throws Exception {
    AbiDefinition functionDefinition =
            new AbiDefinition(
                    false,
                    Arrays.asList(new AbiDefinition.NamedType("param", "uint8")),
                    "functionName",
                    Collections.emptyList(),
                    "function",
                    true);
    TypeSpec.Builder builder = TypeSpec.classBuilder("testClass");

    builder.addFields(
            solidityFunctionWrapper.buildFuncNameConstants(
                    Collections.singletonList(functionDefinition)));

    String expected =
            "class testClass {\n"
                    + "  public static final java.lang.String FUNC_FUNCTIONNAME = \"functionName\";\n"
                    + "}\n";

    assertEquals(builder.build().toString(), (expected));
}
 
Example 6
Source File: Jsr303ExtensionTest.java    From raml-java-tools with Apache License 2.0 5 votes vote down vote up
@Test
public void forUnion() throws Exception {

    Jsr303Extension ext = new Jsr303Extension();
    TypeSpec.Builder typeBuilder =
            TypeSpec.classBuilder(ClassName.get("xx.bb", "Foo"));

    FieldSpec.Builder builder =
            FieldSpec.builder(ClassName.get(Double.class), "champ", Modifier.PUBLIC);

    ext.anyFieldCreated(unionPluginContext, union, typeBuilder, builder, EventType.IMPLEMENTATION);

    assertEquals(1, builder.build().annotations.size());
    assertEquals(Valid.class.getName(), builder.build().annotations.get(0).type.toString());
}
 
Example 7
Source File: ExperimentListWriter.java    From siberi-android with MIT License 5 votes vote down vote up
public void writer(Filer filer) throws IOException {
    TypeSpec.Builder outClassBuilder = TypeSpec.classBuilder(model.getClassName().simpleName());
    outClassBuilder.addModifiers(Modifier.PUBLIC);
    HashMap<String, String> experimentsHashMap = model.getExperimentsHashMap();

    outClassBuilder
            .addFields(createField(experimentsHashMap))
            .addMethod(createGetParams(experimentsHashMap))
            .addMethod(createGetList(experimentsHashMap));

    TypeSpec outClass = outClassBuilder.build();
    JavaFile.builder(model.getClassName().packageName(), outClass)
            .build()
            .writeTo(filer);
}
 
Example 8
Source File: GeneratedAnnotationPolicyTest.java    From json2java4idea with Apache License 2.0 5 votes vote down vote up
@Test
public void applyShouldAddGeneratedAnnotation() throws Exception {
    // setup
    final TypeSpec.Builder builder = TypeSpec.classBuilder("Test");

    // exercise
    underTest.apply(builder);

    // verify
    assertThat(builder.build())
            .hasName("Test")
            .hasAnnotation(AnnotationSpec.builder(Generated.class)
                    .addMember("value", "$S", this.getClass().getCanonicalName())
                    .build());
}
 
Example 9
Source File: SuppressWarningsAnnotationPolicyTest.java    From json2java4idea with Apache License 2.0 5 votes vote down vote up
@Test
public void applyShouldAddGeneratedAnnotation() throws Exception {
    // setup
    final TypeSpec.Builder builder = TypeSpec.classBuilder("Test");

    // exercise
    underTest.apply(builder);

    // verify
    assertThat(builder.build())
            .hasName("Test")
            .hasAnnotation(AnnotationSpec.builder(SuppressWarnings.class)
                    .addMember("value", "$S", "all")
                    .build());
}
 
Example 10
Source File: ClassBuilder.java    From json2java4idea with Apache License 2.0 5 votes vote down vote up
@Nonnull
@CheckReturnValue
public TypeSpec build(@Nonnull String name) {
    final TypeSpec.Builder classBuilder = TypeSpec.classBuilder(name);
    buildAnnotations().forEach(classBuilder::addAnnotation);
    buildModifiers().forEach(classBuilder::addModifiers);
    buildSuperClass().ifPresent(classBuilder::superclass);
    buildInterfaces().forEach(classBuilder::addSuperinterface);
    buildFields().forEach(classBuilder::addField);
    buildMethods().forEach(classBuilder::addMethod);
    buildInnerTypes().forEach(classBuilder::addType);
    return classBuilder.build();
}
 
Example 11
Source File: IndexableEnumCodecGenerator.java    From fastjgame with Apache License 2.0 5 votes vote down vote up
@Override
public void execute() {
    final TypeName instanceRawTypeName = TypeName.get(typeUtils.erasure(typeElement.asType()));
    final DeclaredType superDeclaredType = typeUtils.getDeclaredType(processor.serializerTypeElement, typeUtils.erasure(typeElement.asType()));

    // 获取实例方法
    final MethodSpec getEncoderClassMethod = processor.newGetEncoderClassMethod(superDeclaredType);

    // 写入number即可 outputStream.writeObject(WireType.INT, instance.getNumber())
    final MethodSpec.Builder writeMethodBuilder = processor.newWriteMethodBuilder(superDeclaredType);
    writeMethodBuilder.addStatement("writer.writeInt(instance.$L())", GET_NUMBER_METHOD_NAME);

    // 读取number即可 return A.forNumber(inputStream.readObject(WireType.INT))
    final MethodSpec.Builder readMethodBuilder = processor.newReadObjectMethodBuilder(superDeclaredType);
    readMethodBuilder.addStatement("return $T.$L(reader.readInt())", instanceRawTypeName, FOR_NUMBER_METHOD_NAME);

    final TypeSpec.Builder typeBuilder = TypeSpec.classBuilder(getCodecClassName(typeElement));
    typeBuilder.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addAnnotation(AutoUtils.SUPPRESS_UNCHECKED_ANNOTATION)
            .addAnnotation(processorInfoAnnotation)
            .addSuperinterface(TypeName.get(superDeclaredType))
            .addMethod(getEncoderClassMethod)
            .addMethod(writeMethodBuilder.build())
            .addMethod(readMethodBuilder.build());

    // 写入文件
    AutoUtils.writeToFile(typeElement, typeBuilder, elementUtils, messager, filer);
}
 
Example 12
Source File: AutoCodecUtil.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes a builder for a class of the appropriate type.
 *
 * @param encodedType type being serialized
 */
static TypeSpec.Builder initializeCodecClassBuilder(
    TypeElement encodedType, ProcessingEnvironment env) {
  TypeSpec.Builder builder = TypeSpec.classBuilder(getCodecName(encodedType));
  builder.addAnnotation(
      AnnotationSpec.builder(ClassName.get(SuppressWarnings.class))
          .addMember("value", "$S", "unchecked")
          .addMember("value", "$S", "rawtypes")
          .build());
  return builder.addSuperinterface(
      ParameterizedTypeName.get(
          ClassName.get(ObjectCodec.class),
          TypeName.get(env.getTypeUtils().erasure(encodedType.asType()))));
}
 
Example 13
Source File: InitializerSpec.java    From spring-init with Apache License 2.0 5 votes vote down vote up
private TypeSpec createInitializer(TypeElement type) {
	Builder builder = TypeSpec.classBuilder(getClassName());
	builder.addSuperinterface(SpringClassNames.INITIALIZER_TYPE);
	builder.addModifiers(Modifier.PUBLIC);
	this.hasEnabled = maybeAddEnabled(builder);
	builder.addMethod(createInitializer());
	return builder.build();
}
 
Example 14
Source File: GeneratedCodeGenerator.java    From jackdaw with Apache License 2.0 5 votes vote down vote up
private TypeSpec.Builder createTypeSpecBuilder(final ClassType classType, final String className) {
    switch (classType) {
        case ANNOTATION:
            return TypeSpec.annotationBuilder(className);
        case INTERFACE:
            return TypeSpec.interfaceBuilder(className);
        default:
            return TypeSpec.classBuilder(className);
    }
}
 
Example 15
Source File: GenerateYamlLoaderSupportClasses.java    From camel-k-runtime with Apache License 2.0 5 votes vote down vote up
public final TypeSpec generateReifiers() {
    TypeSpec.Builder type = TypeSpec.classBuilder("YamlReifiers");
    type.addModifiers(Modifier.PUBLIC, Modifier.FINAL);

    MethodSpec.Builder mb = MethodSpec.methodBuilder("registerReifiers")
        .addModifiers(Modifier.PUBLIC)
        .addModifiers(Modifier.STATIC);

    annotated(YAML_NODE_DEFINITION_ANNOTATION).forEach(i -> {
        final AnnotationInstance annotation = i.classAnnotation(YAML_NODE_DEFINITION_ANNOTATION);
        final AnnotationValue reifiers = annotation.value("reifiers");

        if (reifiers != null) {
            String name = i.toString();
            if (i.nestingType() == ClassInfo.NestingType.INNER) {
                name = i.enclosingClass().toString() + "." + i.simpleName();
            }

            for (String reifier: reifiers.asStringArray()) {
                mb.addStatement("org.apache.camel.reifier.ProcessorReifier.registerReifier($L.class, $L::new)", name, reifier);
            }
        }
    });

    type.addMethod(mb.build());

    return type.build();
}
 
Example 16
Source File: IndexableObjectCodecGenerator.java    From fastjgame with Apache License 2.0 5 votes vote down vote up
@Override
public void execute() {
    final TypeName instanceRawTypeName = TypeName.get(typeUtils.erasure(typeElement.asType()));
    final DeclaredType superDeclaredType = typeUtils.getDeclaredType(processor.serializerTypeElement, typeUtils.erasure(typeElement.asType()));

    final TypeSpec.Builder typeBuilder = TypeSpec.classBuilder(getCodecClassName(typeElement));

    // 获取实例方法
    final MethodSpec getEncoderClassMethod = processor.newGetEncoderClassMethod(superDeclaredType);

    // 写入索引即可 outputStream.writeObject(instance.getIndex())
    final MethodSpec.Builder writeMethodBuilder = processor.newWriteMethodBuilder(superDeclaredType);
    writeMethodBuilder.addStatement("writer.writeObject(instance.$L())", GET_INDEX_METHOD_NAME);

    // 读取索引即可 return A.forIndex(InputStream.readObject());
    final MethodSpec.Builder readMethodBuilder = processor.newReadObjectMethodBuilder(superDeclaredType);
    readMethodBuilder.addStatement("return $T.$L(reader.readObject())", instanceRawTypeName, FOR_INDEX_METHOD_NAME);

    typeBuilder.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addAnnotation(AutoUtils.SUPPRESS_UNCHECKED_ANNOTATION)
            .addAnnotation(processorInfoAnnotation)
            .addSuperinterface(TypeName.get(superDeclaredType))
            .addMethod(getEncoderClassMethod)
            .addMethod(writeMethodBuilder.build())
            .addMethod(readMethodBuilder.build());

    // 写入文件
    AutoUtils.writeToFile(typeElement, typeBuilder, elementUtils, messager, filer);
}
 
Example 17
Source File: SolidityFunctionWrapperTest.java    From web3j with Apache License 2.0 4 votes vote down vote up
@Test
public void testBuildEventConstantMultipleValueReturn() throws Exception {

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

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

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

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

    assertEquals(builder.build().toString(), (expected));
}
 
Example 18
Source File: SolidityFunctionWrapperTest.java    From etherscan-explorer with GNU General Public License v3.0 4 votes vote down vote up
@Test
public void testBuildEventConstantMultipleValueReturn() throws Exception {

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

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

    solidityFunctionWrapper.buildEventFunctions(functionDefinition, builder);

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

    assertThat(builder.build().toString(), is(expected));
}
 
Example 19
Source File: SolidityFunctionWrapperTest.java    From client-sdk-java with Apache License 2.0 4 votes vote down vote up
@Test
public void testBuildEventConstantMultipleValueReturn() throws Exception {

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

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

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

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

    assertThat(builder.build().toString(), is(expected));
}
 
Example 20
Source File: GenerateYamlLoaderSupportClasses.java    From camel-k-runtime with Apache License 2.0 4 votes vote down vote up
public final TypeSpec generateJacksonModule() {
    TypeSpec.Builder type = TypeSpec.classBuilder("YamlModule");
    type.addModifiers(Modifier.PUBLIC, Modifier.FINAL);
    type.superclass(Module.class);
    type.addMethod(
        MethodSpec.methodBuilder("getModuleName")
            .addModifiers(Modifier.PUBLIC)
            .addAnnotation(Override.class)
            .returns(String.class)
            .addCode(CodeBlock.builder().addStatement("return $S", "camel-yaml").build())
            .build()
    );
    type.addMethod(
        MethodSpec.methodBuilder("version")
            .addModifiers(Modifier.PUBLIC)
            .addAnnotation(Override.class)
            .returns(Version.class)
            .addCode(CodeBlock.builder().addStatement("return $L", "Version.unknownVersion()").build())
            .build()
    );

    MethodSpec.Builder mb = MethodSpec.methodBuilder("setupModule")
        .addModifiers(Modifier.PUBLIC)
        .addParameter(Module.SetupContext.class, "context");

    definitions(EXPRESSION_DEFINITION_CLASS).forEach(
        (k, v) -> mb.addStatement("context.registerSubtypes(new com.fasterxml.jackson.databind.jsontype.NamedType($L.class, $S))", v.getName(), k)
    );
    definitions(DATAFORMAT_DEFINITION_CLASS).forEach(
        (k, v) -> mb.addStatement("context.registerSubtypes(new com.fasterxml.jackson.databind.jsontype.NamedType($L.class, $S))", v.getName(), k)
    );
    definitions(LOAD_BALANCE_DEFINITION_CLASS).forEach(
        (k, v) -> mb.addStatement("context.registerSubtypes(new com.fasterxml.jackson.databind.jsontype.NamedType($L.class, $S))", v.getName(), k)
    );

    annotated(YAML_MIXIN_ANNOTATION).forEach(i -> {
        final AnnotationInstance annotation = i.classAnnotation(YAML_MIXIN_ANNOTATION);
        final AnnotationValue targets = annotation.value("value");

        String name = i.toString();
        if (i.nestingType() == ClassInfo.NestingType.INNER) {
            name = i.enclosingClass().toString() + "." + i.simpleName();
        }

        if (targets != null) {
            for (String target: targets.asStringArray()) {
                mb.addStatement("context.setMixInAnnotations($L.class, $L.class);", target, name);
            }
        }
    });


    type.addMethod(mb.build());

    return type.build();
}