com.squareup.javapoet.FieldSpec Java Examples

The following examples show how to use com.squareup.javapoet.FieldSpec. 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: Jsr303ExtensionTest.java    From raml-java-tools with Apache License 2.0 6 votes vote down vote up
@Test
public void forArrays() throws Exception {

    when(array.minItems()).thenReturn(3);
    when(array.maxItems()).thenReturn(5);

    FieldSpec.Builder builder =
            FieldSpec.builder(ParameterizedTypeName.get(List.class, String.class), "champ",
                    Modifier.PUBLIC);
    Jsr303Extension ext = new Jsr303Extension();
    ext.fieldBuilt(objectPluginContext, array, builder, EventType.IMPLEMENTATION);
    assertEquals(1, builder.build().annotations.size());
    assertEquals(Size.class.getName(), builder.build().annotations.get(0).type.toString());
    assertEquals("3", builder.build().annotations.get(0).members.get("min").get(0).toString());
    assertEquals("5", builder.build().annotations.get(0).members.get("max").get(0).toString());
}
 
Example #2
Source File: RegionMetadataProviderGenerator.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public TypeSpec poetClass() {
    TypeName mapOfRegionMetadata = ParameterizedTypeName.get(ClassName.get(Map.class),
                                                             ClassName.get(regionBasePackage, "Region"),
                                                             ClassName.get(regionBasePackage, "RegionMetadata"));
    return TypeSpec.classBuilder(className())
                   .addModifiers(PUBLIC)
                   .addSuperinterface(ClassName.get(regionBasePackage, "RegionMetadataProvider"))
                   .addAnnotation(AnnotationSpec.builder(Generated.class)
                                                .addMember("value", "$S", "software.amazon.awssdk:codegen")
                                                .build())
                   .addAnnotation(SdkPublicApi.class)
                   .addModifiers(FINAL)
                   .addField(FieldSpec.builder(mapOfRegionMetadata, "REGION_METADATA")
                                      .addModifiers(PRIVATE, FINAL, STATIC)
                                      .initializer(regions(partitions))
                                      .build())
                   .addMethod(getter())
                   .build();
}
 
Example #3
Source File: TargetViewBinder.java    From Witch-Android with Apache License 2.0 6 votes vote down vote up
private TypeSpec createViewHolder() {
    TypeSpec.Builder viewHolder =
            TypeSpec.classBuilder(viewHolderClassName)
                    .addModifiers(Modifier.PUBLIC, Modifier.FINAL);

    List<FieldSpec> views = new ArrayList<>();
    for (ViewBinder.Builder viewBinder : viewBinders) {
        if(!(viewBinder.getGetView() instanceof GetNoView)) {
            FieldSpec view = FieldSpec.builder(
                    ANDROID_VIEW,
                    viewBinder.getViewHolderViewName(),
                    Modifier.PUBLIC).build();
            if (!views.contains(view)) {
                views.add(view);
            }
        }
    }
    viewHolder.addFields(views);

    return viewHolder.build();
}
 
Example #4
Source File: DynamicEntityBuilder.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private void createDateTimeField(Builder builder, Field field) {

		AnnotationSpec column = AnnotationSpec.builder(Column.class)
				.addMember("name", "ColumnNamePrefix + " + field.fieldName()).build();

		AnnotationSpec temporal = AnnotationSpec.builder(Temporal.class)
				.addMember("value", "javax.persistence.TemporalType.TIMESTAMP").build();

		FieldSpec fieldSpec = FieldSpec.builder(Date.class, field.getName(), Modifier.PRIVATE)
				.addAnnotation(this.fieldDescribe(field)).addAnnotation(this.index(field))
				.addAnnotation(this.checkPersist(field)).addAnnotation(column).addAnnotation(temporal).build();
		MethodSpec get = MethodSpec.methodBuilder("get" + StringUtils.capitalize(field.getName()))
				.addModifiers(Modifier.PUBLIC).returns(Date.class).addStatement("return this." + field.getName())
				.build();
		MethodSpec set = MethodSpec.methodBuilder("set" + StringUtils.capitalize(field.getName()))
				.addModifiers(Modifier.PUBLIC).returns(void.class).addParameter(Date.class, field.getName())
				.addStatement("this." + field.getName() + " = " + field.getName()).build();
		builder.addField(this.fieldName(field)).addField(fieldSpec).addMethod(get).addMethod(set);

	}
 
Example #5
Source File: SolidityFunctionWrapper.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
Iterable<FieldSpec> buildFuncNameConstants(List<AbiDefinition> functionDefinitions) {
    List<FieldSpec> fields = new ArrayList<>();
    Set<String> fieldNames = new HashSet<>();
    fieldNames.add(Contract.FUNC_DEPLOY);

    for (AbiDefinition functionDefinition : functionDefinitions) {
        if (functionDefinition.getType().equals("function")) {
            String funcName = functionDefinition.getName();

            if (!fieldNames.contains(funcName)) {
                FieldSpec field =
                        FieldSpec.builder(
                                        String.class,
                                        funcNameToConst(funcName),
                                        Modifier.PUBLIC,
                                        Modifier.STATIC,
                                        Modifier.FINAL)
                                .initializer("$S", funcName)
                                .build();
                fields.add(field);
                fieldNames.add(funcName);
            }
        }
    }
    return fields;
}
 
Example #6
Source File: ConstantGenerator.java    From greycat with Apache License 2.0 6 votes vote down vote up
private static JavaFile generateGlobalConstant(String packageName, Constant[] globalConstants) {
    TypeSpec.Builder javaClass = TypeSpec.classBuilder(CONSTANT_CLASS_NAME);
    javaClass.addModifiers(PUBLIC, FINAL);
    for (Constant constant : globalConstants) {
        String value = constant.value();
        if (constant.type().equals("Task") && value != null) {
            value = "greycat.Tasks.newTask().parse(\"" + value.replaceAll("\"", "'").trim() + "\",null);";
        } else if (constant.type().equals("String") && value != null) {
            value = "\""+value+"\"";
        }
        FieldSpec.Builder field = FieldSpec.builder(clazz(constant.type()), constant.name())
                .addModifiers(PUBLIC, STATIC);
        if (value != null) {
            field.addModifiers(FINAL).initializer(value);
        }
        javaClass.addField(field.build());
    }
    return JavaFile.builder(packageName, javaClass.build()).build();
}
 
Example #7
Source File: AwsServiceBaseResponseSpec.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private void addResponseMetadataToImpl(TypeSpec.Builder classBuilder) {
    classBuilder.addField(FieldSpec.builder(responseMetadata, "responseMetadata", Modifier.PRIVATE).build());

    classBuilder.addMethod(MethodSpec.methodBuilder("responseMetadata")
                                     .returns(responseMetadata)
                                     .addAnnotation(Override.class)
                                     .addModifiers(Modifier.PUBLIC)
                                     .addStatement("return responseMetadata")
                                     .build());

    classBuilder.addMethod(MethodSpec.methodBuilder("responseMetadata")
                                     .addParameter(AwsResponseMetadata.class, "responseMetadata")
                                     .returns(builderInterfaceName())
                                     .addAnnotation(Override.class)
                                     .addModifiers(Modifier.PUBLIC)
                                     .addCode(CodeBlock.builder()
                                                       .add("this.responseMetadata = $T.create(responseMetadata);\n",
                                                            responseMetadata)
                                                       .add("return this;")
                                                       .build())
                                     .build());
}
 
Example #8
Source File: WasmFunctionWrapper.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
public TypeSpec buildStruct(WasmAbiDefinition functionDefinition, Set<String> customTypes) {
	String className = Strings.capitaliseFirstLetter(functionDefinition.getName());
	TypeSpec.Builder typeBuilder = TypeSpec.classBuilder(className).addModifiers(Modifier.PUBLIC, Modifier.STATIC);
	List<FieldSpec> fieldSpecs = new ArrayList<>();

	if (null != functionDefinition.getBaseclass() && !functionDefinition.getBaseclass().isEmpty()) {
		String baseClass = Strings.capitaliseFirstLetter(functionDefinition.getBaseclass().get(0));
		FieldSpec field = FieldSpec.builder(ClassName.get("", baseClass), "baseClass", Modifier.PUBLIC).build();
		fieldSpecs.add(field);
	}
	for (int i = 0; i < functionDefinition.getFields().size(); i++) {
		WasmAbiDefinition.NamedType namedType = functionDefinition.getFields().get(i);
		String name = namedType.getName();
		String type = namedType.getType();
		fieldSpecs.add(FieldSpec.builder(buildTypeName(type, customTypes), name, Modifier.PUBLIC).build());
	}
	typeBuilder.addFields(fieldSpecs);

	return typeBuilder.build();
}
 
Example #9
Source File: OpenApiClientGenerator.java    From spring-openapi with MIT License 6 votes vote down vote up
private FieldSpec.Builder parseTypeBasedSchema(String fieldName, Schema innerSchema, String targetPackage,
									   TypeSpec.Builder typeSpecBuilder) {
	if (innerSchema.getEnum() != null) {
		typeSpecBuilder.addType(createEnumClass(StringUtils.capitalize(fieldName), innerSchema).build());
		return createSimpleFieldSpec(null, StringUtils.capitalize(fieldName), fieldName, typeSpecBuilder);
	}
	if (equalsIgnoreCase(innerSchema.getType(), "string")) {
		return getStringBasedSchemaField(fieldName, innerSchema, typeSpecBuilder);
	} else if (equalsIgnoreCase(innerSchema.getType(), "integer") || equalsIgnoreCase(innerSchema.getType(), "number")) {
		return getNumberBasedSchemaField(fieldName, innerSchema, typeSpecBuilder);
	} else if (equalsIgnoreCase(innerSchema.getType(), "boolean")) {
		return createSimpleFieldSpec(JAVA_LANG_PKG, "Boolean", fieldName, typeSpecBuilder);
	} else if (equalsIgnoreCase(innerSchema.getType(), "array") && innerSchema instanceof ArraySchema) {
		ArraySchema arraySchema = (ArraySchema) innerSchema;
		ParameterizedTypeName listParameterizedTypeName = ParameterizedTypeName.get(
				ClassName.get("java.util", "List"),
				determineTypeName(arraySchema.getItems(), targetPackage)
		);
		enrichWithGetSetList(typeSpecBuilder, listParameterizedTypeName, fieldName);
		return FieldSpec.builder(listParameterizedTypeName, fieldName, Modifier.PRIVATE);
	}
	return createSimpleFieldSpec(JAVA_LANG_PKG, "Object", fieldName, typeSpecBuilder);
}
 
Example #10
Source File: DynamicEntityBuilder.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private void createIdField(Builder builder) {
//		public String getId() {
//			return id;
//		}
//		public void setId(String id) {
//			this.id = id;
//		}
//		@FieldDescribe("数据库主键,自动生成.")
//		@Id
//		@Column(length = length_id, name = ColumnNamePrefix + id_FIELDNAME)
//		private String id = createId();
		AnnotationSpec fieldDescribe = AnnotationSpec.builder(FieldDescribe.class).addMember("value", "\"数据库主键,自动生成.\"")
				.build();
		AnnotationSpec id = AnnotationSpec.builder(Id.class).build();
		AnnotationSpec column = AnnotationSpec.builder(Column.class).addMember("length", "length_id")
				.addMember("name", "ColumnNamePrefix + id_FIELDNAME").build();
		MethodSpec get = MethodSpec.methodBuilder("getId").addModifiers(Modifier.PUBLIC).returns(String.class)
				.addStatement("return this.id").build();
		MethodSpec set = MethodSpec.methodBuilder("setId").addModifiers(Modifier.PUBLIC).returns(void.class)
				.addParameter(String.class, "id").addStatement("this.id = id").build();
		FieldSpec fieldSpec = FieldSpec.builder(String.class, JpaObject.id_FIELDNAME, Modifier.PRIVATE)
				.initializer("createId()").addAnnotation(fieldDescribe).addAnnotation(id).addAnnotation(column).build();
		builder.addField(fieldSpec).addMethod(set).addMethod(get);
	}
 
Example #11
Source File: StateContainerGenerator.java    From litho with Apache License 2.0 6 votes vote down vote up
private static TypeSpecDataHolder generateTransitionStuff(SpecModel specModel) {
  final TypeSpecDataHolder.Builder typeSpecDataHolder = TypeSpecDataHolder.newBuilder();

  final TypeName transitionClass = specModel.getTransitionClass().box();

  typeSpecDataHolder.addField(
      FieldSpec.builder(transitionClass, GeneratorConstants.STATE_TRANSITION_FIELD_NAME).build());

  final String transitionCopyVarName = "transitionCopy";
  typeSpecDataHolder.addMethod(
      MethodSpec.methodBuilder(METHOD_NAME_CONSUME_TRANSITION)
          .addModifiers(Modifier.PUBLIC)
          .addAnnotation(Override.class)
          .addAnnotation(Nullable.class)
          .returns(transitionClass)
          .addStatement(
              "$T $N = $N",
              specModel.getTransitionClass(),
              transitionCopyVarName,
              GeneratorConstants.STATE_TRANSITION_FIELD_NAME)
          .addStatement("$N = null", GeneratorConstants.STATE_TRANSITION_FIELD_NAME)
          .addStatement("return $N", transitionCopyVarName)
          .build());

  return typeSpecDataHolder.build();
}
 
Example #12
Source File: JavaWriter.java    From lazythreetenbp with Apache License 2.0 6 votes vote down vote up
private FieldSpec regionId(Set<String> allRegionIds) {
    CodeBlock.Builder builder = CodeBlock.builder()
            .add("$T.asList(\n$>$>", Arrays.class);
    Iterator<String> iterator = allRegionIds.iterator();
    while (iterator.hasNext()) {
        builder.add("$S", iterator.next());
        if (iterator.hasNext()) {
            builder.add(",\n");
        }
    }
    builder.add("$<$<)");
    TypeName listType = ParameterizedTypeName.get(List.class, String.class);
    return FieldSpec.builder(listType, "REGION_IDS", STATIC, FINAL)
            .initializer(builder.build())
            .build();
}
 
Example #13
Source File: EventValidationTest.java    From litho with Apache License 2.0 6 votes vote down vote up
@Test
public void testFinalFields() {
  FieldModel fieldModel1 =
      new FieldModel(
          FieldSpec.builder(TypeName.INT, "field1", Modifier.PUBLIC, Modifier.FINAL).build(),
          mRepresentedObject1);

  when(mSpecModel.getEventDeclarations())
      .thenReturn(
          ImmutableList.of(
              new EventDeclarationModel(
                  ClassName.OBJECT,
                  ClassName.OBJECT,
                  ImmutableList.of(fieldModel1),
                  mRepresentedObject5)));

  List<SpecModelValidationError> validationErrors =
      EventValidation.validate(mSpecModel, RunMode.normal());
  assertThat(validationErrors).hasSize(1);
  assertThat(validationErrors.get(0).element).isEqualTo(mRepresentedObject1);
  assertThat(validationErrors.get(0).message)
      .isEqualTo("Event fields must be declared as public non-final.");
}
 
Example #14
Source File: GsonClassBuilder.java    From json2java4idea with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
protected List<FieldSpec> buildFields() {
    return getProperties()
            .entrySet()
            .stream()
            .map(property -> {
                final String name = property.getKey();
                final TypeName type = property.getValue();

                final String fieldName = fieldNamePolicy.convert(name, type);
                return FieldSpec.builder(type, fieldName)
                        .addModifiers(Modifier.PRIVATE, Modifier.FINAL)
                        .addAnnotation(AnnotationSpec.builder(SerializedName.class)
                                .addMember("value", "$S", name)
                                .build())
                        .build();
            })
            .collect(Collectors.toList());
}
 
Example #15
Source File: FinalRClassBuilder.java    From Briefness with Apache License 2.0 6 votes vote down vote up
private static void addResourceField(TypeSpec.Builder resourceType, VariableDeclarator variable,
                                     ClassName annotation) {
  String fieldName = variable.getNameAsString();
  String fieldValue = variable.getInitializer()
      .map(Node::toString)
      .orElseThrow(
          () -> new IllegalStateException("Field " + fieldName + " missing initializer"));
  FieldSpec.Builder fieldSpecBuilder = FieldSpec.builder(int.class, fieldName)
      .addModifiers(PUBLIC, STATIC, FINAL)
      .initializer(fieldValue);

  if (annotation != null) {
    fieldSpecBuilder.addAnnotation(annotation);
  }

  resourceType.addField(fieldSpecBuilder.build());
}
 
Example #16
Source File: PsiEventDeclarationsExtractor.java    From litho with Apache License 2.0 6 votes vote down vote up
static ImmutableList<FieldModel> getFields(@Nullable PsiClass psiClass) {
  if (psiClass == null) {
    return ImmutableList.of();
  }
  final List<FieldModel> fieldModels = new ArrayList<>();
  for (PsiField psiField : psiClass.getFields()) {
    fieldModels.add(
        new FieldModel(
            FieldSpec.builder(
                    PsiTypeUtils.getTypeName(psiField.getType()),
                    psiField.getName(),
                    PsiModifierExtractor.extractModifiers(psiField))
                .build(),
            psiField));
  }

  return ImmutableList.copyOf(fieldModels);
}
 
Example #17
Source File: InjectProcessor.java    From customview-samples with Apache License 2.0 6 votes vote down vote up
private TypeSpec createRepotityTypeSpec(ClassName builderClassName,List<ClassName> factoryList) {
    ClassName list = ClassName.get("java.util", "List");
    ClassName arrayList = ClassName.get("java.util", "ArrayList");
    TypeName listType = ParameterizedTypeName.get(list, ClassName.get("java.lang","Class"));

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

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

    return TypeSpec
            .classBuilder(builderClassName)
            .addModifiers(Modifier.PUBLIC)
            .addStaticBlock(blockBuilder.build())
            .addField(fieldSpec)
            .build();
}
 
Example #18
Source File: SyncClientInterface.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public TypeSpec poetSpec() {
    TypeSpec.Builder result = PoetUtils.createInterfaceBuilder(className);

    result.addSuperinterface(SdkClient.class)
          .addField(FieldSpec.builder(String.class, "SERVICE_NAME")
                             .addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
                             .initializer("$S", model.getMetadata().getSigningName())
                             .build());

    PoetUtils.addJavadoc(result::addJavadoc, getJavadoc());

    if (!model.getCustomizationConfig().isExcludeClientCreateMethod()) {
        result.addMethod(create());
    }

    result.addMethod(builder())
          .addMethods(operations())
          .addMethod(serviceMetadata());

    if (model.getCustomizationConfig().getUtilitiesMethod() != null) {
        result.addMethod(utilitiesMethod());
    }

    return result.build();
}
 
Example #19
Source File: Utils.java    From DevUtils with Apache License 2.0 6 votes vote down vote up
/**
 * 创建 Module Environment 数据
 * @param classBuilder       DevEnvironment 类构建对象
 * @param moduleElement      使用注解修饰的 Module Element
 * @param environmentElement 使用注解修饰的 Environment Element
 */
public static void builderModuleEnvironment_DATA(final TypeSpec.Builder classBuilder, final Element moduleElement,
                                                 final Element environmentElement) {
    // Module 信息
    String moduleName = moduleElement.getSimpleName().toString();
    // Environment 信息
    Environment environmentAnnotation = environmentElement.getAnnotation(Environment.class);
    String environmentName = environmentElement.getSimpleName().toString();
    String environmentValue = environmentAnnotation.value();
    String environmentAlias = environmentAnnotation.alias();

    // 创建私有常量变量
    // private static final EnvironmentBean ENVIRONMENT_MODULENAME_XXX = new EnvironmentBean();
    FieldSpec environmentField = FieldSpec
            .builder(EnvironmentBean.class, _getEnvironmentVarName_UpperCase(moduleName, environmentName))
            .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
            .initializer("new $T($S, $S, $S, $N)", EnvironmentBean.class, environmentName,
                    environmentValue, environmentAlias, _getModuleVarName_UpperCase(moduleName))
            .addJavadoc(String.format("[ Environment ] name: %s, alias: %s, [ Module ] name: %s\n",
                    environmentName, environmentAlias, moduleName))
            .build();
    classBuilder.addField(environmentField);

    // 记录 Environment 变量名 ( 传入的 environmentElement ) 属于 Release Environment Element 存储在 index 0
    sModuleNameMap.get(moduleName).add(_getEnvironmentVarName_UpperCase(moduleName, environmentName));
}
 
Example #20
Source File: AsyncClientInterface.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Override
public TypeSpec poetSpec() {
    TypeSpec.Builder result = PoetUtils.createInterfaceBuilder(className);

    result.addSuperinterface(SdkClient.class)
          .addField(FieldSpec.builder(String.class, "SERVICE_NAME")
                             .addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
                             .initializer("$S", model.getMetadata().getSigningName())
                             .build());

    PoetUtils.addJavadoc(result::addJavadoc, getJavadoc());

    if (!model.getCustomizationConfig().isExcludeClientCreateMethod()) {
        result.addMethod(create());
    }

    result.addMethod(builder())
          .addMethods(operationsAndSimpleMethods());

    if (model.getCustomizationConfig().getUtilitiesMethod() != null) {
        result.addMethod(utilitiesMethod());
    }

    return result.build();
}
 
Example #21
Source File: Utils.java    From DevUtils with Apache License 2.0 6 votes vote down vote up
/**
 * 创建 Module Environment 数据
 * @param classBuilder       DevEnvironment 类构建对象
 * @param moduleElement      使用注解修饰的 Module Element
 * @param environmentElement 使用注解修饰的 Environment Element
 */
public static void builderModuleEnvironment_DATA(final TypeSpec.Builder classBuilder, final Element moduleElement,
                                                 final Element environmentElement) {
    // Module 信息
    String moduleName = moduleElement.getSimpleName().toString();
    // Environment 信息
    Environment environmentAnnotation = environmentElement.getAnnotation(Environment.class);
    String environmentName = environmentElement.getSimpleName().toString();
    String environmentValue = environmentAnnotation.value();
    String environmentAlias = environmentAnnotation.alias();

    // 创建私有常量变量
    // private static final EnvironmentBean ENVIRONMENT_MODULENAME_XXX = new EnvironmentBean();
    FieldSpec environmentField = FieldSpec
            .builder(EnvironmentBean.class, _getEnvironmentVarName_UpperCase(moduleName, environmentName))
            .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL)
            .initializer("new $T($S, $S, $S, $N)", EnvironmentBean.class, environmentName,
                    environmentValue, environmentAlias, _getModuleVarName_UpperCase(moduleName))
            .addJavadoc(String.format("[ Environment ] name: %s, alias: %s, [ Module ] name: %s\n",
                    environmentName, environmentAlias, moduleName))
            .build();
    classBuilder.addField(environmentField);

    // 记录 Environment 变量名 ( 传入的 environmentElement ) 属于 Release Environment Element 存储在 index 0
    sModuleNameMap.get(moduleName).add(_getEnvironmentVarName_UpperCase(moduleName, environmentName));
}
 
Example #22
Source File: SurgeonProcessor.java    From Surgeon with Apache License 2.0 5 votes vote down vote up
private Iterable<FieldSpec> buildRouterModuleFields() {
    ArrayList<FieldSpec> fieldSpecs = new ArrayList<>();
    FieldSpec f_mapping = FieldSpec.builder(HashMap.class, "mapping")
            .addModifiers(Modifier.PRIVATE, Modifier.FINAL)
            .build();
    fieldSpecs.add(f_mapping);
    return fieldSpecs;
}
 
Example #23
Source File: Jsr303ExtensionTest.java    From raml-java-tools with Apache License 2.0 5 votes vote down vote up
@Test
public void forArraysOfStrings() throws Exception {

    when(array.minItems()).thenReturn(null);
    when(array.maxItems()).thenReturn(null);

    FieldSpec.Builder builder =
            FieldSpec.builder(ParameterizedTypeName.get(List.class, String.class), "champ",
                    Modifier.PUBLIC);
    Jsr303Extension ext = new Jsr303Extension();
    ext.fieldBuilt(objectPluginContext, array, builder, EventType.IMPLEMENTATION);
    assertEquals(0, builder.build().annotations.size());
}
 
Example #24
Source File: JacksonScalarTypeSerialization.java    From raml-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration typeDeclaration, FieldSpec.Builder builder, EventType eventType) {
  if (typeDeclaration instanceof DateTimeOnlyTypeDeclaration) {

    builder.addAnnotation(AnnotationSpec.builder(JsonFormat.class)
            .addMember("shape", "$T.STRING", JsonFormat.Shape.class)
            .addMember("pattern", "$S", "yyyy-MM-dd'T'HH:mm:ss").build());
  }

  if (typeDeclaration instanceof TimeOnlyTypeDeclaration) {

    builder.addAnnotation(AnnotationSpec.builder(JsonFormat.class)
            .addMember("shape", "$T.STRING", JsonFormat.Shape.class)
            .addMember("pattern", "$S", "HH:mm:ss").build());
  }

  if (typeDeclaration instanceof DateTypeDeclaration) {

    builder.addAnnotation(AnnotationSpec.builder(JsonFormat.class)
            .addMember("shape", "$T.STRING", JsonFormat.Shape.class)
            .addMember("pattern", "$S", "yyyy-MM-dd").build());
  }

  if (typeDeclaration instanceof DateTimeTypeDeclaration) {

    String format = ((DateTimeTypeDeclaration) typeDeclaration).format();
    if (format != null && "rfc2616".equals(format)) {

      builder.addAnnotation(AnnotationSpec.builder(JsonFormat.class)
              .addMember("shape", "$T.STRING", JsonFormat.Shape.class)
              .addMember("pattern", "$S", "EEE, dd MMM yyyy HH:mm:ss z").build());
    } else {
      builder.addAnnotation(AnnotationSpec.builder(JsonFormat.class)
              .addMember("shape", "$T.STRING", JsonFormat.Shape.class)
              .addMember("pattern", "$S", "yyyy-MM-dd'T'HH:mm:ssZ").build());
    }
  }

  return builder;
}
 
Example #25
Source File: Jsr303ExtensionTest.java    From raml-java-tools with Apache License 2.0 5 votes vote down vote up
public void assertForIntegerNumber(FieldSpec.Builder builder) {

        assertEquals(3, builder.build().annotations.size());
        assertEquals(NotNull.class.getName(), builder.build().annotations.get(0).type.toString());
        assertEquals(Min.class.getName(), builder.build().annotations.get(1).type.toString());
        assertEquals("13", builder.build().annotations.get(1).members.get("value").get(0).toString());
        assertEquals(Max.class.getName(), builder.build().annotations.get(2).type.toString());
        assertEquals("17", builder.build().annotations.get(2).members.get("value").get(0).toString());
    }
 
Example #26
Source File: CodeGenerator.java    From Barricade with Apache License 2.0 5 votes vote down vote up
/**
 * Generates the code for the Barricade configuration based on the annotations found.
 *
 * @param processingEnv Processing environment
 * @param configs Configuration detected by annotation processing
 * @param messager Messager to print logs
 * @throws IOException
 */
static void generateClass(ProcessingEnvironment processingEnv,
    HashMap<String, BarricadeResponseSet> configs, Messager messager) throws IOException {

  messager.printMessage(Diagnostic.Kind.NOTE, "Generating configuration code...");

  TypeSpec.Builder classBuilder = classBuilder(CLASS_NAME).addModifiers(PUBLIC, FINAL);

  FieldSpec valuesField = FieldSpec.builder(TYPE_CONFIG, "configs").addModifiers(PRIVATE).build();
  FieldSpec instanceField =
      FieldSpec.builder(ClassName.get(PACKAGE_NAME, CLASS_NAME), "barricadeConfig")
          .addModifiers(PRIVATE, STATIC)
          .build();

  MethodSpec.Builder instanceMethodBuilder = generateGetInstanceMethodBuilder();
  MethodSpec.Builder constructorMethodBuilder = generateConstructorBuilder(configs, messager);
  MethodSpec.Builder valuesMethod = generateGetConfigsMethodBuilder();
  MethodSpec.Builder getResponseMethodBuilder = generateGetResponseMethodBuilder();

  classBuilder.addType(generateEndpointsInnerClass(configs.keySet()));
  classBuilder.addType(generateResponsesInnerClass(configs));
  classBuilder.addField(instanceField);
  classBuilder.addField(valuesField);
  classBuilder.addMethod(instanceMethodBuilder.build());
  classBuilder.addMethod(constructorMethodBuilder.build());
  classBuilder.addMethod(valuesMethod.build());
  classBuilder.addMethod(getResponseMethodBuilder.build());

  classBuilder.addSuperinterface(IBarricadeConfig.class);

  JavaFile.Builder javaFileBuilder = builder(PACKAGE_NAME, classBuilder.build());
  JavaFile javaFile = javaFileBuilder.build();
  javaFile.writeTo(processingEnv.getFiler());

  messager.printMessage(Diagnostic.Kind.NOTE, "Code generation complete!");
}
 
Example #27
Source File: UnionTypeHandlerPlugin.java    From raml-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public FieldSpec.Builder fieldBuilt(UnionPluginContext context, TypeDeclaration ramlType, FieldSpec.Builder fieldSpec, EventType eventType) {
    for (UnionTypeHandlerPlugin plugin : plugins) {
        if (fieldSpec == null) {
            break;
        }
        fieldSpec = plugin.fieldBuilt(context, ramlType, fieldSpec, eventType);
    }
    return fieldSpec;
}
 
Example #28
Source File: FieldSpecMatchers.java    From raml-java-tools with Apache License 2.0 5 votes vote down vote up
public static <T extends TypeName> Matcher<FieldSpec> fieldType(Matcher<T> match) {

        return new FeatureMatcher<FieldSpec, T>(match, "type name", "type name") {

            @Override
            protected T featureValueOf(FieldSpec actual) {
                return (T) actual.type;
            }
        };
    }
 
Example #29
Source File: EventStreamVisitorBuilderImplSpec.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Override
protected MethodSpec.Builder applyOnSubTypeMethodSpecUpdates(TypeSpec.Builder typeBuilder,
                                                             MethodSpec.Builder methodBuilder,
                                                             ShapeModel eventSubTypeShape) {
    ClassName eventSubType = poetExt.getModelClass(eventSubTypeShape.getShapeName());
    TypeName eventConsumerType = consumerType(eventSubType);
    FieldSpec consumerField = FieldSpec.builder(eventConsumerType, "on" + eventSubType.simpleName())
                                       .addModifiers(Modifier.PRIVATE)
                                       .build();
    typeBuilder.addField(consumerField);
    return methodBuilder
        .addAnnotation(Override.class)
        .addStatement("this.$L = c", consumerField.name)
        .addStatement("return this");
}
 
Example #30
Source File: ModelClassBuilderTest.java    From json2java4idea with Apache License 2.0 5 votes vote down vote up
@Test
public void buildFields() throws Exception {
    // setup
    underTest.addProperty("foo", TypeName.INT)
            .addProperty("bar", TypeName.OBJECT)
            .addProperty("baz", TypeName.BOOLEAN);

    // exercise
    final List<FieldSpec> actual = underTest.buildFields();

    // verify
    assertThat(actual)
            .hasSize(3)
            .doesNotContainNull();

    assertThat(actual.get(0))
            .hasType(TypeName.INT)
            .hasName("foo")
            .hasNoJavadoc()
            .hasNoAnnotation()
            .hasModifier(Modifier.PRIVATE, Modifier.FINAL)
            .hasNoInitializer();

    assertThat(actual.get(1))
            .hasType(TypeName.OBJECT)
            .hasName("bar")
            .hasNoJavadoc()
            .hasNoAnnotation()
            .hasModifier(Modifier.PRIVATE, Modifier.FINAL)
            .hasNoInitializer();

    assertThat(actual.get(2))
            .hasType(TypeName.BOOLEAN)
            .hasName("baz")
            .hasNoJavadoc()
            .hasNoAnnotation()
            .hasModifier(Modifier.PRIVATE, Modifier.FINAL)
            .hasNoInitializer();
}