com.squareup.javapoet.MethodSpec Java Examples

The following examples show how to use com.squareup.javapoet.MethodSpec. 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: CodeGenerator.java    From Barricade with Apache License 2.0 6 votes vote down vote up
private static MethodSpec.Builder generateConstructorBuilder(
    HashMap<String, BarricadeResponseSet> values, Messager messager) {
  MethodSpec.Builder methodBuilder = MethodSpec.constructorBuilder().addModifiers(PUBLIC);
  methodBuilder.addStatement("configs = new HashMap<>()");

  for (Map.Entry<String, BarricadeResponseSet> entry : values.entrySet()) {
    BarricadeResponseSet barricadeResponseSet = entry.getValue();

    String listName = "barricadeResponsesFor" + entry.getKey();

    methodBuilder.addStatement("$T<$T> " + listName + " = new $T<>()", List.class,
        BarricadeResponse.class, ArrayList.class);

    for (BarricadeResponse barricadeResponse : barricadeResponseSet.responses) {
      methodBuilder.addStatement(listName + ".add(new $T($L, $S, $S))", BarricadeResponse.class,
          barricadeResponse.statusCode, barricadeResponse.responseFileName,
          barricadeResponse.contentType);
    }

    methodBuilder.addStatement(
        "configs.put($S, new $T(" + listName + ", " + barricadeResponseSet.defaultIndex + "))",
        entry.getKey(), TYPE_BARRICADE_RESPONSE_SET);
  }
  return methodBuilder;
}
 
Example #2
Source File: AutoMatterProcessor.java    From auto-matter with Apache License 2.0 6 votes vote down vote up
private MethodSpec collectionVarargSetter(final Descriptor d, final ExecutableElement field) {
  String fieldName = fieldName(field);
  TypeName itemType = genericArgument(d, field, 0);

  MethodSpec.Builder setter = MethodSpec.methodBuilder(fieldName)
      .addModifiers(PUBLIC)
      .addParameter(ArrayTypeName.of(itemType), fieldName)
      .varargs()
      .returns(builderType(d));

  ensureSafeVarargs(setter);

  collectionNullGuard(setter, field);

  setter.addStatement("return $N($T.asList($N))", fieldName, ClassName.get(Arrays.class), fieldName);
  return setter.build();
}
 
Example #3
Source File: AutoCodecProcessor.java    From bazel with Apache License 2.0 6 votes vote down vote up
private String buildDeserializeBodyWithBuilder(
    TypeElement encodedType,
    TypeElement builderType,
    MethodSpec.Builder builder,
    List<ExecutableElement> fields,
    ExecutableElement builderCreationMethod)
    throws SerializationProcessingFailedException {
  String builderVarName = "objectBuilder";
  builder.addStatement(
      "$T $L = $T.$L()",
      builderCreationMethod.getReturnType(),
      builderVarName,
      encodedType,
      builderCreationMethod.getSimpleName());
  for (ExecutableElement getter : fields) {
    String paramName = getNameFromGetter(getter) + "_";
    marshallers.writeDeserializationCode(
        new Marshaller.Context(builder, getter.getReturnType(), paramName));
    setValueInBuilder(builderType, getter, paramName, builderVarName, builder);
  }
  return builderVarName;
}
 
Example #4
Source File: AwsServiceModel.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private Stream<MethodSpec> memberGetters(MemberModel member) {
    List<MethodSpec> result = new ArrayList<>();

    if (shouldGenerateEnumGetter(member)) {
        result.add(enumMemberGetter(member));
    }

    member.getAutoConstructClassIfExists()
          .ifPresent(autoConstructClass -> result.add(existenceCheckGetter(member, autoConstructClass)));

    if (shouldGenerateDeprecatedNameGetter(member)) {
        result.add(deprecatedMemberGetter(member));
    }

    result.add(memberGetter(member));

    return result.stream();
}
 
Example #5
Source File: SolidityFunctionWrapperTest.java    From web3j with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildFunctionConstantSingleValueReturn() throws Exception {
    AbiDefinition functionDefinition =
            new AbiDefinition(
                    true,
                    Arrays.asList(new AbiDefinition.NamedType("param", "uint8")),
                    "functionName",
                    Arrays.asList(new AbiDefinition.NamedType("result", "int8")),
                    "type",
                    false);

    MethodSpec methodSpec = solidityFunctionWrapper.buildFunction(functionDefinition);

    String expected =
            "public org.web3j.protocol.core.RemoteFunctionCall<java.math.BigInteger> functionName(java.math.BigInteger param) {\n"
                    + "  final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(FUNC_FUNCTIONNAME, \n"
                    + "      java.util.Arrays.<org.web3j.abi.datatypes.Type>asList(new org.web3j.abi.datatypes.generated.Uint8(param)), \n"
                    + "      java.util.Arrays.<org.web3j.abi.TypeReference<?>>asList(new org.web3j.abi.TypeReference<org.web3j.abi.datatypes.generated.Int8>() {}));\n"
                    + "  return executeRemoteCallSingleValueReturn(function, java.math.BigInteger.class);\n"
                    + "}\n";

    assertEquals(methodSpec.toString(), (expected));
}
 
Example #6
Source File: ToStringMethod.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
static MethodSpec generate(TypeElement element) {
  ClassName.get(element).reflectionName();
  Builder result =
      MethodSpec.methodBuilder("toString")
          .addModifiers(Modifier.PUBLIC)
          .returns(String.class)
          .addAnnotation(Override.class)
          .addCode(
              CodeBlock.builder()
                  .add(
                      "StringBuilder sb = new StringBuilder(\"@$L\");\n",
                      ClassName.get(element).reflectionName().replace('$', '.'))
                  .build());
  List<ExecutableElement> methods = ElementFilter.methodsIn(element.getEnclosedElements());
  if (!methods.isEmpty()) {
    result.addCode("sb.append('(');\n");
  }
  for (ExecutableElement method : methods) {
    result.addCode("sb.append(\"$1L=\").append($1L);\n", method.getSimpleName());
  }
  if (!methods.isEmpty()) {
    result.addCode("sb.append(')');\n");
  }
  result.addCode("return sb.toString();\n");
  return result.build();
}
 
Example #7
Source File: AbstractMapperGenerator.java    From domino-jackson with Apache License 2.0 6 votes vote down vote up
/**
 * <p>makeNewDeserializerMethod.</p>
 * <p>
 * Creates method for build corresponding deserializer for  given beanType. If beanType is
 * basic type, generated code utilize existing deserializers. Otherwise, it creates instances
 * of newly generated ones.
 *
 * @param element
 * @param beanType
 * @return
 */
protected MethodSpec makeNewDeserializerMethod(Element element, TypeMirror beanType) {
    CodeBlock.Builder builder = CodeBlock.builder();
    if (Type.isBasicType(typeUtils.erasure(beanType))) {
        builder.addStatement("return $L", new FieldDeserializersChainBuilder(packageName, getElementType(element)).getInstance(getElementType(element)));
    } else {
        builder.addStatement("return new " + deserializerName(beanType));
    }

    return MethodSpec.methodBuilder("newDeserializer")
            .addModifiers(Modifier.PROTECTED)
            .addAnnotation(Override.class)
            .returns(ParameterizedTypeName.get(ClassName.get(JsonDeserializer.class),
                    ClassName.get(getElementType(element))))
            .addCode(builder.build())
            .build();

}
 
Example #8
Source File: TriggerGenerator.java    From litho with Apache License 2.0 6 votes vote down vote up
private static MethodSpec generateDeprecatedStaticGetTrigger(
    ClassName contextClassName,
    SpecMethodModel<EventMethod, EventDeclarationModel> eventMethodModel) {

  MethodSpec.Builder triggerMethod =
      MethodSpec.methodBuilder(
              ComponentBodyGenerator.getEventTriggerInstanceName(eventMethodModel.name))
          .returns(ClassNames.EVENT_TRIGGER)
          .addModifiers(Modifier.PUBLIC, Modifier.STATIC);

  triggerMethod
      .addJavadoc("@Deprecated Do not use this method to trigger events.")
      .addAnnotation(java.lang.Deprecated.class)
      .addParameter(contextClassName, "c")
      .addParameter(ClassNames.STRING, "key")
      .addStatement(
          "return $L(c, key, null)",
          ComponentBodyGenerator.getEventTriggerInstanceName(eventMethodModel.name));

  return triggerMethod.build();
}
 
Example #9
Source File: AutoMatterProcessor.java    From auto-matter with Apache License 2.0 6 votes vote down vote up
private MethodSpec optionalSetter(final Descriptor d, final ExecutableElement field) {
  String fieldName = fieldName(field);
  TypeName valueType = genericArgument(d, field, 0);
  ClassName optionalType = ClassName.bestGuess(optionalType(field));
  TypeName parameterType = ParameterizedTypeName.get(optionalType, subtypeOf(valueType));

  AnnotationSpec suppressUncheckedAnnotation = AnnotationSpec.builder(SuppressWarnings.class)
      .addMember("value", "$S", "unchecked")
      .build();

  MethodSpec.Builder setter = MethodSpec.methodBuilder(fieldName)
      .addAnnotation(suppressUncheckedAnnotation)
      .addModifiers(PUBLIC)
      .addParameter(parameterType, fieldName)
      .returns(builderType(d));

  if (shouldEnforceNonNull(field)) {
    assertNotNull(setter, fieldName);
  }

  setter.addStatement("this.$N = ($T)$N", fieldName, fieldType(d, field), fieldName);

  return setter.addStatement("return this").build();
}
 
Example #10
Source File: JUnitGeneratorHelper.java    From evosql with Apache License 2.0 6 votes vote down vote up
/**
 * Builds a utility function for building a Map from a list of strings.
 *
 * @return An instance of a method specification for mapMaker.
 */
public MethodSpec buildMapMaker() {
    MethodSpec.Builder mapMaker = MethodSpec.methodBuilder(METHOD_MAP_MAKER)
            .addModifiers(Modifier.PRIVATE, Modifier.STATIC)
            .returns(ParameterizedTypeName.get(HashMap.class, String.class, String.class))
            .addParameter(String[].class, "strings")
            .varargs()
            .addJavadoc("Generates a string map from a list of strings.\n");

    mapMaker.addStatement("$T<$T, $T> result = new $T<>()", HashMap.class, String.class, String.class, HashMap.class)
            .beginControlFlow("for(int i = 0; i < strings.length; i += 2)")
            .addStatement("result.put(strings[i], strings[i + 1])")
            .endControlFlow()
            .addStatement("return result");
    return mapMaker.build();
}
 
Example #11
Source File: SolidityFunctionWrapperTest.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildFunctionConstantSingleValueReturn() throws Exception {
    AbiDefinition functionDefinition = new AbiDefinition(
            true,
            Arrays.asList(
                    new AbiDefinition.NamedType("param", "uint8")),
            "functionName",
            Arrays.asList(
                    new AbiDefinition.NamedType("result", "int8")),
            "type",
            false);

    MethodSpec methodSpec = solidityFunctionWrapper.buildFunction(functionDefinition);

    //CHECKSTYLE:OFF
    String expected =
            "public org.web3j.protocol.core.RemoteCall<java.math.BigInteger> functionName(java.math.BigInteger param) {\n"
                    + "  final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(FUNC_FUNCTIONNAME, \n"
                    + "      java.util.Arrays.<org.web3j.abi.datatypes.Type>asList(new org.web3j.abi.datatypes.generated.Uint8(param)), \n"
                    + "      java.util.Arrays.<org.web3j.abi.TypeReference<?>>asList(new org.web3j.abi.TypeReference<org.web3j.abi.datatypes.generated.Int8>() {}));\n"
                    + "  return executeRemoteCallSingleValueReturn(function, java.math.BigInteger.class);\n"
                    + "}\n";
    //CHECKSTYLE:ON

    assertThat(methodSpec.toString(), is(expected));
}
 
Example #12
Source File: MatcherGenerator.java    From litho with Apache License 2.0 6 votes vote down vote up
private static TypeSpecDataHolder generateFactoryMethods(final SpecModel specModel) {
  final TypeSpecDataHolder.Builder dataHolder = TypeSpecDataHolder.newBuilder();

  final MethodSpec.Builder factoryMethod =
      MethodSpec.methodBuilder("matcher")
          .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
          .returns(getMatcherType(specModel))
          .addParameter(specModel.getContextClass(), "c")
          .addStatement("return new $T(c)", BUILDER_CLASS_NAME);

  if (!specModel.getTypeVariables().isEmpty()) {
    factoryMethod.addTypeVariables(specModel.getTypeVariables());
  }

  return dataHolder.addMethod(factoryMethod.build()).build();
}
 
Example #13
Source File: GremlinDslProcessor.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
private MethodSpec constructMethod(final Element element, final ClassName returnClazz, final String parent,
                                   final Modifier... modifiers) {
    final ExecutableElement templateMethod = (ExecutableElement) element;
    final String methodName = templateMethod.getSimpleName().toString();

    final TypeName returnType = getReturnTypeDefinition(returnClazz, templateMethod);
    final MethodSpec.Builder methodToAdd = MethodSpec.methodBuilder(methodName)
            .addModifiers(modifiers)
            .addAnnotation(Override.class)
            .addExceptions(templateMethod.getThrownTypes().stream().map(TypeName::get).collect(Collectors.toList()))
            .returns(returnType);

    templateMethod.getTypeParameters().forEach(tp -> methodToAdd.addTypeVariable(TypeVariableName.get(tp)));

    final String parentCall = parent.isEmpty() ? "" : parent + ".";
    final String body = "return ($T) " + parentCall + "super.$L(";
    addMethodBody(methodToAdd, templateMethod, body, ")", returnClazz, methodName);

    return methodToAdd.build();
}
 
Example #14
Source File: InitializerSpec.java    From spring-init with Apache License 2.0 6 votes vote down vote up
private void addBeanMethods(MethodSpec.Builder builder, TypeElement type) {
	boolean conditional = utils.hasAnnotation(type, SpringClassNames.CONDITIONAL.toString());
	if (this.hasEnabled) {
		builder.beginControlFlow("if ($T.enabled)", this.className);
	}
	if (conditional) {
		builder.addStatement("$T conditions = context.getBeanFactory().getBean($T.class)",
				SpringClassNames.CONDITION_SERVICE, SpringClassNames.CONDITION_SERVICE);
		builder.beginControlFlow("if (conditions.matches($T.class))", type);
	}
	builder.beginControlFlow("if (context.getBeanFactory().getBeanNamesForType($T.class).length==0)", type);
	boolean conditionsAvailable = addScannedComponents(builder, conditional);
	addNewBeanForConfig(builder, type);
	for (ExecutableElement method : getBeanMethods(type)) {
		conditionsAvailable |= createBeanMethod(builder, method, type, conditionsAvailable);
	}
	addResources(builder);
	addRegistrarInvokers(builder);
	builder.endControlFlow();
	if (conditional) {
		builder.endControlFlow();
	}
	if (this.hasEnabled) {
		builder.endControlFlow();
	}
}
 
Example #15
Source File: ModelPersistingGenerator.java    From sqlitemagic with Apache License 2.0 6 votes vote down vote up
static void addTransactionEndBlock(@NonNull MethodSpec.Builder builder,
                                   @NonNull Set<TableElement> allTableTriggers,
                                   @NonNull CodeBlock successStatement,
                                   @NonNull CodeBlock returnStatement,
                                   @NonNull String failReturnStatement,
                                   boolean closeOpHelper) {
  builder.addStatement("$L.markSuccessful()", TRANSACTION_VARIABLE)
      .addCode(successStatement)
      .addCode(returnStatement)
      .nextControlFlow("catch ($T e)", OPERATION_FAILED_EXCEPTION);
  addOperationFailedLoggingStatement(builder);
  if (!Strings.isNullOrEmpty(failReturnStatement)) {
    builder.addStatement(failReturnStatement);
  }
  builder.nextControlFlow("finally")
      .addStatement("$L.end()", TRANSACTION_VARIABLE)
      .beginControlFlow("if (success)");
  addTableTriggersSendingStatement(builder, allTableTriggers);
  builder.endControlFlow();
  if (closeOpHelper) {
    builder.addStatement("$L.close()", OPERATION_HELPER_VARIABLE);
  }
  builder.endControlFlow();
}
 
Example #16
Source File: BeanJsonDeserializerCreator.java    From gwt-jackson with Apache License 2.0 6 votes vote down vote up
private Optional<MethodSpec> buildInitAnySetterDeserializerMethod( PropertyInfo anySetterPropertyInfo )
        throws UnableToCompleteException {

    FieldAccessor fieldAccessor = anySetterPropertyInfo.getSetterAccessor().get();
    JType type = fieldAccessor.getMethod().get().getParameterTypes()[1];

    JDeserializerType deserializerType;
    try {
        deserializerType = getJsonDeserializerFromType( type );
    } catch ( UnsupportedTypeException e ) {
        logger.log( Type.WARN, "Method '" + fieldAccessor.getMethod().get()
                .getName() + "' annotated with @JsonAnySetter has an unsupported type" );
        return Optional.absent();
    }

    return Optional.of( MethodSpec.methodBuilder( "initAnySetterDeserializer" )
            .addModifiers( Modifier.PROTECTED )
            .addAnnotation( Override.class )
            .returns( ParameterizedTypeName.get(
                    ClassName.get( AnySetterDeserializer.class ), typeName( beanInfo.getType() ), DEFAULT_WILDCARD ) )
            .addStatement( "return $L", buildDeserializer( anySetterPropertyInfo, type, deserializerType ) )
            .build() );
}
 
Example #17
Source File: RDFSPropertySpecTest.java    From anno4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetter() throws Exception {
    BuildableRDFSProperty loadCap = getPropertyFromModel("http://example.de/ont#load_capacity");
    assertNotNull(loadCap);

    MethodSpec loadCapSpec = loadCap.buildSetter(declaringClass, generationConfig);

    // Test signature:
    assertEquals("setMaximumLoadCapacities", loadCapSpec.name);
    assertTrue(loadCapSpec.modifiers.contains(Modifier.PUBLIC));
    assertEquals(1, loadCapSpec.parameters.size());
    ClassName setClass = ClassName.get("java.util", "Set");
    assertEquals(ParameterizedTypeName.get(setClass, ClassName.get(Float.class)), loadCapSpec.parameters.get(0).type);

    // Test JavaDoc:
    assertNotNull(loadCapSpec.javadoc);
    assertTrue(loadCapSpec.javadoc.toString().startsWith("Ladung in Tonnen"));

    // Test annotation:
    assertEquals(1, loadCapSpec.annotations.size()); // @Iri annotation was moved to private field. Setters must not have an annotation.
}
 
Example #18
Source File: GeneratedMethod.java    From AnnotationProcessorStarter with Apache License 2.0 6 votes vote down vote up
private void appendBody(final MethodSpec.Builder pMethodBuilder) {
    pMethodBuilder.addCode("$T.d(", Log.class);
    pMethodBuilder.addCode("$S, $S", mClassElement.getQualifiedName() + "." + mMethodElement.getSimpleName(), "called");

    if (!mIsStaticMethod) {
        pMethodBuilder.addCode(" + $S + $N", " on ", "instance");
    }

    pMethodBuilder.addCode(" + $S", " with ");

    final Iterator<? extends VariableElement> lIterator = mMethodElement.getParameters().iterator();
    while (lIterator.hasNext()) {
        final VariableElement lParamElement = lIterator.next();
        // add "key=" + value
        pMethodBuilder.addCode(" + $S + $N", lParamElement.getSimpleName() + "=", lParamElement.getSimpleName());
        // add "," for next parameter
        if (lIterator.hasNext()) {
            pMethodBuilder.addCode(" + $S", ", ");
        }
    }

    pMethodBuilder.addCode(");\n");
}
 
Example #19
Source File: ViewStateClassGenerator.java    From Moxy with MIT License 6 votes vote down vote up
private TypeSpec generateCommandClass(ViewMethod method, TypeName viewTypeName) {
	MethodSpec applyMethod = MethodSpec.methodBuilder("apply")
			.addAnnotation(Override.class)
			.addModifiers(Modifier.PUBLIC)
			.addParameter(viewTypeName, "mvpView")
			.addExceptions(method.getExceptions())
			.addStatement("mvpView.$L($L)", method.getName(), method.getArgumentsString())
			.build();

	TypeSpec.Builder classBuilder = TypeSpec.classBuilder(method.getCommandClassName())
			.addModifiers(Modifier.PUBLIC) // TODO: private and static
			.addTypeVariables(method.getTypeVariables())
			.superclass(ParameterizedTypeName.get(ClassName.get(ViewCommand.class), viewTypeName))
			.addMethod(generateCommandConstructor(method))
			.addMethod(applyMethod);

	for (ParameterSpec parameter : method.getParameterSpecs()) {
		// TODO: private field
		classBuilder.addField(parameter.type, parameter.name, Modifier.PUBLIC, Modifier.FINAL);
	}

	return classBuilder.build();
}
 
Example #20
Source File: SimpleNameDelegateGenerator.java    From litho with Apache License 2.0 6 votes vote down vote up
public static TypeSpecDataHolder generate(LayoutSpecModel specModel) {
  final String delegatesToPropName = specModel.getSimpleNameDelegate();
  final TypeSpecDataHolder.Builder builder = TypeSpecDataHolder.newBuilder();
  if (delegatesToPropName == null || delegatesToPropName.isEmpty()) {
    return builder.build();
  }

  MethodSpec.Builder getDelegateComponentBuilder =
      MethodSpec.methodBuilder("getSimpleNameDelegate")
          .addAnnotation(Override.class)
          .addModifiers(Modifier.PROTECTED)
          .returns(ClassNames.COMPONENT)
          .addStatement("return $L", delegatesToPropName);
  builder.addMethod(getDelegateComponentBuilder.build());

  return builder.build();
}
 
Example #21
Source File: WasmFunctionWrapper.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
private static MethodSpec buildDeployWithParams(MethodSpec.Builder methodBuilder, String className, String inputParams, String authName,
		boolean isPayable, boolean withGasProvider) {
	methodBuilder.addStatement("$T encodedConstructor = $T.encodeConstructor($L, $T.asList($L))", String.class, WasmFunctionEncoder.class, BINARY,
			Arrays.class, inputParams);

	if (isPayable && !withGasProvider) {
		methodBuilder.addStatement("return deployRemoteCall($L.class, $L, $L, $L, $L, encodedConstructor, $L)", className, WEB3J, authName,
				GAS_PRICE, GAS_LIMIT, INITIAL_VALUE);
		methodBuilder.addAnnotation(Deprecated.class);
	} else if (isPayable && withGasProvider) {
		methodBuilder.addStatement("return deployRemoteCall($L.class, $L, $L, $L, encodedConstructor, $L)", className, WEB3J, authName,
				CONTRACT_GAS_PROVIDER, INITIAL_VALUE);
	} else if (!isPayable && !withGasProvider) {
		methodBuilder.addStatement("return deployRemoteCall($L.class, $L, $L, $L, $L, encodedConstructor)", className, WEB3J, authName, GAS_PRICE,
				GAS_LIMIT);
		methodBuilder.addAnnotation(Deprecated.class);
	} else {
		methodBuilder.addStatement("return deployRemoteCall($L.class, $L, $L, $L, encodedConstructor)", className, WEB3J, authName,
				CONTRACT_GAS_PROVIDER);
	}
	return methodBuilder.build();
}
 
Example #22
Source File: AbiTypesGenerator.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
private <T extends Type> void generateBytesTypes(
        Class<T> superclass, String path) throws IOException {
    String packageName = createPackageName(superclass);
    ClassName className;

    for (int byteSize = 1; byteSize <= 32; byteSize++) {

        MethodSpec constructorSpec = MethodSpec.constructorBuilder()
                .addModifiers(Modifier.PUBLIC)
                .addParameter(byte[].class, "value")
                .addStatement("super($L, $N)", byteSize, "value")
                .build();

        className = ClassName.get(packageName, superclass.getSimpleName() + byteSize);

        FieldSpec defaultFieldSpec = FieldSpec
                .builder(className, DEFAULT, Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
                .initializer("new $T(new byte[$L])", className, byteSize)
                .build();

        TypeSpec bytesType = TypeSpec
                .classBuilder(className.simpleName())
                .addJavadoc(CODEGEN_WARNING)
                .superclass(superclass)
                .addModifiers(Modifier.PUBLIC)
                .addField(defaultFieldSpec)
                .addMethod(constructorSpec)
                .build();

        write(packageName, bytesType, path);
    }
}
 
Example #23
Source File: RegionMetadataProviderGenerator.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private MethodSpec getter() {
    return MethodSpec.methodBuilder("regionMetadata")
                     .addModifiers(PUBLIC)
                     .addParameter(ClassName.get(regionBasePackage, "Region"), "region")
                     .returns(ClassName.get(regionBasePackage, "RegionMetadata"))
                     .addStatement("return $L.get($L)", "REGION_METADATA", "region")
                     .build();
}
 
Example #24
Source File: TupleGenerator.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
private MethodSpec generateSizeSpec() {
    return MethodSpec.methodBuilder(
            "getSize")
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC)
            .returns(int.class)
            .addStatement("return $L", SIZE)
            .build();
}
 
Example #25
Source File: AbiTypesGenerator.java    From client-sdk-java with 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 #26
Source File: SyncClientInterface.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private MethodSpec.Builder operationSimpleMethodSignature(IntermediateModel model,
                                                          OperationModel opModel,
                                                          String methodName) {
    TypeName returnType = ClassName.get(model.getMetadata().getFullModelPackageName(),
                                        opModel.getReturnType().getReturnType());

    return MethodSpec.methodBuilder(methodName)
                     .returns(returnType)
                     .addModifiers(Modifier.PUBLIC)
                     .addModifiers(Modifier.DEFAULT)
                     .addExceptions(getExceptionClasses(model, opModel));
}
 
Example #27
Source File: AnnotationCreatorClassPoolVisitor.java    From reflection-no-reflection with Apache License 2.0 5 votes vote down vote up
private MethodSpec createSetterMethod(TypeName type, String fieldName) {
    return createPrefixedMethod("set", fieldName)
        .addModifiers(Modifier.PUBLIC)
        .addParameter(type, fieldName)
        .addStatement("this.$L = $L", fieldName, fieldName)
        .build();
}
 
Example #28
Source File: OutInterfaceManager.java    From data-mediator with Apache License 2.0 5 votes vote down vote up
/**
 * get field builder.
 *
 * @param pkgName   the package name
 * @param classname the class name
 * @param tc        the type element wrapper.
 * @param map       the map.
 * @param superFlagsForParent the flags for super interface/class
 * @return the field builders.
 */
public static MethodSpec.Builder[] getImplClassConstructBuilders(String pkgName, String classname,
                                                                 FieldData.TypeCompat tc, Map<String, List<FieldData>> map,
                                                                 boolean hasSuperClass, int superFlagsForParent) {
    final TypeElement te = tc.getElementAsType();
    String interfaceIname = te.getQualifiedName().toString();
    final TypeInterfaceFiller filler = sFillerMap.get(interfaceIname);
    if (filler != null) {
        final List<FieldData> datas = map.get(filler.getInterfaceName());
        final String interName = te.getSimpleName().toString();
        return filler.createConstructBuilder(pkgName, interName, classname,
                datas, hasSuperClass, superFlagsForParent);
    }
    return null;
}
 
Example #29
Source File: StateGenerator.java    From litho with Apache License 2.0 5 votes vote down vote up
static TypeSpecDataHolder generateHasState(SpecModel specModel) {
  final TypeSpecDataHolder.Builder typeSpecDataHolder = TypeSpecDataHolder.newBuilder();

  if (specModel.shouldGenerateHasState() && !specModel.getStateValues().isEmpty()) {
    typeSpecDataHolder.addMethod(
        MethodSpec.methodBuilder("hasState")
            .addAnnotation(Override.class)
            .addModifiers(Modifier.PROTECTED)
            .returns(TypeName.BOOLEAN)
            .addStatement("return true")
            .build());
  }

  return typeSpecDataHolder.build();
}
 
Example #30
Source File: PreferenceWriter.java    From simple-preferences with Apache License 2.0 5 votes vote down vote up
private MethodSpec writeFactory(TypeName generatingClass) {
  MethodSpec.Builder createMethod = MethodSpec.methodBuilder("create")
      .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
      .addParameter(
          ParameterSpec.builder(Context.class, "context").addAnnotation(NonNull.class).build())
      .returns(generatingClass);

  createMethod.beginControlFlow("if (context == null)")
      .addStatement("throw new NullPointerException($S)", "Context is Null!")
      .endControlFlow();
  createMethod.addStatement("return new $T(context)", generatingClass);

  return createMethod.build();
}