com.squareup.javapoet.AnnotationSpec Java Examples

The following examples show how to use com.squareup.javapoet.AnnotationSpec. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: spring-openapi   Author: jrcodeza   File: OpenApiClientGenerator.java    License: MIT License 6 votes vote down vote up
private FieldSpec.Builder getNumberBasedSchemaField(String fieldName, Schema innerSchema, TypeSpec.Builder typeSpecBuilder) {
	FieldSpec.Builder fieldBuilder = createNumberBasedFieldWithFormat(fieldName, innerSchema, typeSpecBuilder);
	if (innerSchema.getMinimum() != null) {
		fieldBuilder.addAnnotation(AnnotationSpec.builder(DecimalMin.class)
				.addMember("value", "$S", innerSchema.getMinimum().toString())
				.build()
		);
	}
	if (innerSchema.getMaximum() != null) {
		fieldBuilder.addAnnotation(AnnotationSpec.builder(DecimalMax.class)
				.addMember("value", "$S", innerSchema.getMaximum().toString())
				.build()
		);
	}
	return fieldBuilder;
}
 
Example #2
Source Project: o2oa   Author: o2oa   File: DynamicEntityBuilder.java    License: 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 #3
Source Project: OkDeepLink   Author: jjerry   File: DeepLinkServiceProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private MethodSpec generateBuildMethod(TypeElement deepLinkServiceElement) {

        CodeBlock.Builder codeBlockBuilder = CodeBlock.builder();
        codeBlockBuilder.add("$T target = ($T)joinPoint.getTarget();\n", DEEP_LINK_CLIENT, DEEP_LINK_CLIENT);
        codeBlockBuilder.beginControlFlow("if (joinPoint.getArgs() == null || joinPoint.getArgs().length != 1)");
        codeBlockBuilder.add("return joinPoint.proceed();\n");
        codeBlockBuilder.endControlFlow();
        codeBlockBuilder.add("$T arg = joinPoint.getArgs()[0];\n", Object.class);
        codeBlockBuilder.beginControlFlow("if (arg instanceof Class)");
        codeBlockBuilder.add("$T buildClass = ($T) arg;\n", Class.class, Class.class);
        codeBlockBuilder.beginControlFlow("if (buildClass.isAssignableFrom(getClass()))");
        codeBlockBuilder.add("return new $T(target);\n", getServiceProviderClassName(deepLinkServiceElement));
        codeBlockBuilder.endControlFlow();
        codeBlockBuilder.endControlFlow();
        codeBlockBuilder.add("return joinPoint.proceed();\n");

        MethodSpec.Builder initMethod = MethodSpec.methodBuilder("aroundBuildMethod")
                .addModifiers(Modifier.PUBLIC)
                .addParameter(ProceedingJoinPoint.class, "joinPoint")
                .returns(Object.class)
                .addException(Throwable.class)
                .addAnnotation(AnnotationSpec.builder(Around.class).addMember("value", "$S", "execution(* " + BUILD_METHOD_NAME + ")").build())
                .addCode(codeBlockBuilder.build());

        return initMethod.build();
    }
 
Example #4
Source Project: shortbread   Author: MatthiasRobbers   File: CodeGenerator.java    License: Apache License 2.0 6 votes vote down vote up
void generate() {
    TypeSpec shortbread = TypeSpec.classBuilder("ShortbreadGenerated")
            .addAnnotation(AnnotationSpec.builder(suppressLint)
                    .addMember("value", "$S", "NewApi")
                    .addMember("value", "$S", "ResourceType")
                    .build())
            .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addMethod(createShortcuts())
            .addMethod(callMethodShortcut())
            .build();

    JavaFile javaFile = JavaFile.builder("shortbread", shortbread)
            .indent("    ")
            .build();

    try {
        javaFile.writeTo(filer);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #5
Source Project: anno4j   Author: anno4j   File: PropertySchemaAnnotationSupport.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Builds an annotation which {@code value} is an array of the IRIs (as strings) of the given resources.
 * @param annotationType The type of the annotation to generate.
 * @param resources The resources which IRIs should be part of the array.
 * @return The JavaPoet annotation specification of the above annotation.
 */
private AnnotationSpec buildIriArrayAnnotation(Class<?> annotationType, Collection<? extends ResourceObject> resources) {
    CodeBlock.Builder inner = CodeBlock.builder().add("{");
    Iterator<? extends ResourceObject> resourceIter = resources.iterator();
    while (resourceIter.hasNext()) {
        inner.add("$S", resourceIter.next().getResourceAsString());

        if(resourceIter.hasNext()) {
            inner.add(", ");
        }
    }
    inner.add("}");

    return AnnotationSpec.builder(annotationType)
                         .addMember("value", inner.build())
                         .build();
}
 
Example #6
Source Project: litho   Author: facebook   File: TestingDIComponentProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public TypeSpecDataHolder generateInjectedFields(
    SpecModel specModel, ImmutableList<InjectPropModel> injectPropParams) {
  final TypeSpecDataHolder.Builder builder = TypeSpecDataHolder.newBuilder();

  for (MethodParamModel injectedParam : injectPropParams) {
    final FieldSpec.Builder fieldBuilder =
        FieldSpec.builder(injectedParam.getTypeName(), injectedParam.getName());
    for (AnnotationSpec extAnnotation : injectedParam.getExternalAnnotations()) {
      fieldBuilder.addAnnotation(extAnnotation);
    }

    builder.addField(fieldBuilder.build());
  }

  return builder.build();
}
 
Example #7
Source Project: litho   Author: facebook   File: MethodParamModelFactoryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCreatePropModel() {
  final List<Annotation> annotations = new ArrayList<>();
  annotations.add(mock(Prop.class));
  MethodParamModel methodParamModel =
      MethodParamModelFactory.create(
          new TypeSpec(TypeName.BOOLEAN),
          "testParam",
          annotations,
          new ArrayList<AnnotationSpec>(),
          ImmutableList.<Class<? extends Annotation>>of(),
          true,
          null);

  assertThat(methodParamModel).isInstanceOf(PropModel.class);
}
 
Example #8
Source Project: litho   Author: facebook   File: MethodParamModelFactoryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateDiffModel() {
  final List<Annotation> annotations = new ArrayList<>();
  Annotation annotation =
      new Annotation() {
        @Override
        public Class<? extends Annotation> annotationType() {
          return OnCreateTransition.class;
        }
      };
  annotations.add(annotation);

  MethodParamModel methodParamModel =
      MethodParamModelFactory.create(
          mDiffTypeSpecWrappingInt,
          "testParam",
          annotations,
          new ArrayList<AnnotationSpec>(),
          ImmutableList.<Class<? extends Annotation>>of(),
          true,
          null);

  assertThat(methodParamModel).isInstanceOf(RenderDataDiffModel.class);
}
 
Example #9
Source Project: litho   Author: facebook   File: MethodParamModelFactoryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDontCreateDiffForShouldUpdate() {
  final List<Annotation> annotations = new ArrayList<>();
  Annotation annotation =
      new Annotation() {
        @Override
        public Class<? extends Annotation> annotationType() {
          return ShouldUpdate.class;
        }
      };
  annotations.add(annotation);

  MethodParamModel methodParamModel =
      MethodParamModelFactory.create(
          mDiffTypeSpecWrappingInt,
          "testParam",
          annotations,
          new ArrayList<AnnotationSpec>(),
          ImmutableList.<Class<? extends Annotation>>of(),
          false,
          null);

  assertThat(methodParamModel).isNotInstanceOf(RenderDataDiffModel.class);
}
 
Example #10
Source Project: Auto-Dagger2   Author: lukaspili   File: SubcomponentProcessing.java    License: MIT License 6 votes vote down vote up
@Override
protected SubcomponentSpec build() {
    SubcomponentSpec subcomponentSpec = new SubcomponentSpec(AutoComponentClassNameUtil.getComponentClassName(extractor.getElement()));

    if (extractor.getScopeAnnotationTypeMirror() != null) {
        subcomponentSpec.setScopeAnnotationSpec(AnnotationSpec.get(extractor.getScopeAnnotationTypeMirror()));
    }

    // modules
    subcomponentSpec.setModulesTypeNames(ProcessingUtil.getTypeNames(extractor.getModulesTypeMirrors()));

    // superinterfaces
    subcomponentSpec.setSuperinterfacesTypeNames(ProcessingUtil.getTypeNames(extractor.getSuperinterfacesTypeMirrors()));

    // exposed
    subcomponentSpec.setExposeSpecs(ProcessingUtil.getAdditions(extractor.getElement(), state.getExposeExtractors()));

    // injector
    subcomponentSpec.setInjectorSpecs(ProcessingUtil.getAdditions(extractor.getElement(), state.getInjectorExtractors()));

    return subcomponentSpec;
}
 
Example #11
Source Project: Mockery   Author: VictorAlbertos   File: BrewJavaFile.java    License: Apache License 2.0 6 votes vote down vote up
private MethodSpec methodOneIllegalParam(ClassName className,
    Method method, Param param, int orderTest) {
  String methodName = String
      .format("When_Call_%s_With_Illegal_%s_Then_Get_Exception", method.name, param.name);

  MethodSpec.Builder builder = MethodSpec.methodBuilder(methodName)
      .addAnnotation(Test.class)
      .addAnnotation(AnnotationSpec.builder(Order.class)
          .addMember("value", "$L", orderTest)
          .build())
      .addModifiers(Modifier.PUBLIC)
      .returns(void.class);

  initializeRobot(className, method, builder);
  variablesForParams(method.params, param, builder);
  response(className, method, true, builder);
  return builder.build();
}
 
Example #12
Source Project: raml-java-tools   Author: mulesoft-labs   File: JaxbObjectExtension.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public TypeSpec.Builder classCreated(ObjectPluginContext objectPluginContext, ObjectTypeDeclaration type, TypeSpec.Builder builder, EventType eventType) {

    String namespace = type.xml() != null && type.xml().namespace() != null ? type.xml().namespace() : "##default";
    String name = type.xml() != null && type.xml().name() != null ? type.xml().name() : type.name();

    if (eventType == EventType.IMPLEMENTATION) {
        builder.addAnnotation(AnnotationSpec.builder(XmlAccessorType.class)
                .addMember("value", "$T.$L", XmlAccessType.class, "FIELD").build());

        AnnotationSpec.Builder annotation = AnnotationSpec.builder(XmlRootElement.class)
                .addMember("namespace", "$S", namespace)
                .addMember("name", "$S", name);

        builder.addAnnotation(annotation.build());
    } else {

        builder.addAnnotation(AnnotationSpec.builder(XmlRootElement.class)
                .addMember("namespace", "$S", namespace)
                .addMember("name", "$S", name).build());
    }

    return builder;
}
 
Example #13
Source Project: spring-openapi   Author: jrcodeza   File: OpenApiClientGenerator.java    License: MIT License 5 votes vote down vote up
private FieldSpec.Builder getStringBasedSchemaField(String fieldName, Schema innerSchema, TypeSpec.Builder typeSpecBuilder) {
	if (innerSchema.getFormat() == null) {
		ClassName stringClassName = ClassName.get(JAVA_LANG_PKG, "String");
		FieldSpec.Builder fieldBuilder = FieldSpec.builder(stringClassName, fieldName, Modifier.PRIVATE);
		if (innerSchema.getPattern() != null) {
			fieldBuilder.addAnnotation(AnnotationSpec.builder(Pattern.class)
					.addMember("regexp", "$S", innerSchema.getPattern())
					.build()
			);
		}
		if (innerSchema.getMinLength() != null || innerSchema.getMaxLength() != null) {
			AnnotationSpec.Builder sizeAnnotationBuilder = AnnotationSpec.builder(Size.class);
			if (innerSchema.getMinLength() != null) {
				sizeAnnotationBuilder.addMember("min", "$L", innerSchema.getMinLength());
			}
			if (innerSchema.getMaxLength() != null) {
				sizeAnnotationBuilder.addMember("max", "$L", innerSchema.getMaxLength());
			}
			fieldBuilder.addAnnotation(sizeAnnotationBuilder.build());
		}
		enrichWithGetSet(typeSpecBuilder, stringClassName, fieldName);
		return fieldBuilder;
	} else if (equalsIgnoreCase(innerSchema.getFormat(), "date")) {
		ClassName localDateClassName = ClassName.get(JAVA_TIME_PKG, "LocalDate");
		enrichWithGetSet(typeSpecBuilder, localDateClassName, fieldName);
		return FieldSpec.builder(localDateClassName, fieldName, Modifier.PRIVATE);
	} else if (equalsIgnoreCase(innerSchema.getFormat(), "date-time")) {
		ClassName localDateTimeClassName = ClassName.get(JAVA_TIME_PKG, "LocalDateTime");
		enrichWithGetSet(typeSpecBuilder, localDateTimeClassName, fieldName);
		return FieldSpec.builder(localDateTimeClassName, fieldName, Modifier.PRIVATE);
	}
	throw new IllegalArgumentException(String.format("Error parsing string based property [%s]", fieldName));
}
 
Example #14
Source Project: spring-openapi   Author: jrcodeza   File: OpenApiClientGenerator.java    License: MIT License 5 votes vote down vote up
private void parseDiscriminator(TypeSpec.Builder typeSpecBuilder, Discriminator discriminator, String targetPackage,
								boolean generateDiscriminatorProperty) {
	if (discriminator.getPropertyName() != null) {
		AnnotationSpec.Builder annotationSpecBuilder = AnnotationSpec.builder(JsonTypeInfo.class)
				.addMember("use", "JsonTypeInfo.Id.NAME")
				.addMember("include", "JsonTypeInfo.As.PROPERTY")
				.addMember("property", "$S", discriminator.getPropertyName());
		if (generateDiscriminatorProperty) {
			annotationSpecBuilder.addMember("visible", "true");
		}
		typeSpecBuilder.addAnnotation(annotationSpecBuilder.build());
	}
	if (discriminator.getMapping() != null) {
		List<AnnotationSpec> annotationSpecs = discriminator.getMapping().entrySet().stream()
				.map(discriminatorMappingEntry ->
						AnnotationSpec.builder(Type.class)
								.addMember("value", "$T.class", ClassName.get(targetPackage, discriminatorMappingEntry.getValue()))
								.addMember("name", "$S", discriminatorMappingEntry.getKey())
								.build())
				.collect(Collectors.toList());

		AnnotationSpec jsonSubTypesAnnotation = AnnotationSpec.builder(JsonSubTypes.class)
				.addMember("value", wrapAnnotationsIntoArray(annotationSpecs))
				.build();

		typeSpecBuilder.addAnnotation(jsonSubTypesAnnotation);
	}
}
 
Example #15
Source Project: tysq-android   Author: tysqapp   File: ComponentCreator.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void creator() throws IOException {

        String viewName;
        if (isFragment) {
            viewName = ClzNameHelper.getInstance().getName(ClzNameHelper.FRAGMENT);
        } else {
            viewName = ClzNameHelper.getInstance().getName(ClzNameHelper.ACTIVITY);
        }
        ClassName viewClz = ClassName.get(pkgName, viewName);

        String moduleName = ClzNameHelper.getInstance().getName(ClzNameHelper.MODULE);
        ClassName moduleClz = ClassName.get(pkgName + MVPFactory.DI, moduleName);

        MethodSpec injectMethod = MethodSpec.methodBuilder(INJECT)
                .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
                .addParameter(viewClz, viewName.substring(0, 1).toLowerCase() + viewName.substring(1))
                .build();

        AnnotationSpec componentAnnotation = AnnotationSpec
                .builder(Component.class)
                .addMember(MODULES, "{$T.class}", moduleClz)
                .addMember(DEPENDENCIES, "$T.class", ClzNameHelper.getInstance().getClass(ClzNameHelper.COMPONENT))
                .build();

        TypeSpec typeSpec = TypeSpec
                .interfaceBuilder(clzName)        // 类名
                .addModifiers(Modifier.PUBLIC)    // 类型限定付
                .addAnnotation(ClzNameHelper.getInstance().getClass(ClzNameHelper.SCOPE))
                .addAnnotation(componentAnnotation)
                .addMethod(injectMethod)          // 添加 injectXXX 方法
                .build();

        JavaPencil.write(path, pkgName + MVPFactory.DI, typeSpec);
    }
 
Example #16
Source Project: anno4j   Author: anno4j   File: SupportTypeSpecTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void buildSupportTypeSpec() throws Exception {
    TypeSpec typeSpec = clazz.buildSupportTypeSpec(generationConfig);

    // Test @Partial annotation:
    AnnotationSpec partialAnnotation = AnnotationSpec.builder(Partial.class).build();
    assertEquals(1, typeSpec.annotations.size());
    assertEquals(partialAnnotation, typeSpec.annotations.get(0));

    // Test superclass:
    TypeName sanitizingObjectSupport = ClassName.get(SchemaSanitizingObjectSupport.class);
    assertEquals(sanitizingObjectSupport, typeSpec.superclass);

    // Test superinterface:
    ClassName superInterface = clazz.getJavaPoetClassName(generationConfig);
    assertEquals(1, typeSpec.superinterfaces.size());
    assertEquals(superInterface, typeSpec.superinterfaces.get(0));

    // Test methods:
    Set<String> methodNames = getMethodNames(typeSpec);
    assertEquals(5, methodNames.size());
    assertTrue(methodNames.contains("setFoos"));
    assertTrue(methodNames.contains("addFoo"));
    assertTrue(methodNames.contains("addAllFoos"));
    assertTrue(methodNames.contains("removeFoo"));
    assertTrue(methodNames.contains("removeAllFoos"));
}
 
Example #17
Source Project: spring-init   Author: spring-projects-experimental   File: SimpleProcessorTests.java    License: Apache License 2.0 5 votes vote down vote up
private static TypeSpec.Builder importAnnotation(TypeSpec.Builder type, String... fullyQualifiedImports) {
	ClassName[] array = new ClassName[fullyQualifiedImports.length];
	for (int i = 0; i < fullyQualifiedImports.length; i++) {
		array[i] = ClassName.bestGuess(fullyQualifiedImports[i]);
	}
	AnnotationSpec.Builder builder = AnnotationSpec.builder(IMPORT);
	builder.addMember("value", array.length > 1 ? ("{" + typeParams(array.length) + "}") : "$T.class",
			(Object[]) array);
	return type.addAnnotation(builder.build());
}
 
Example #18
Source Project: Mockery   Author: VictorAlbertos   File: BrewJavaFile.java    License: Apache License 2.0 5 votes vote down vote up
private TypeSpec classTest(ClassName className, List<MethodSpec> methodSpecs) {
  String methodName = Introspector
      .decapitalize(className.simpleName());

  MethodSpec abstractMethodInstanceToTest = methodBuilder(methodName)
      .addModifiers(Modifier.ABSTRACT, Modifier.PROTECTED)
      .returns(className)
      .build();

  FieldSpec exception = FieldSpec.builder(ExpectedException.class, "exception")
      .addAnnotation(Rule.class)
      .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
      .initializer("$T.none()", ExpectedException.class)
      .build();

  return TypeSpec.classBuilder(className.simpleName() + "Test_")
      .addModifiers(Modifier.ABSTRACT, Modifier.PUBLIC)
      .addMethod(abstractMethodInstanceToTest)
      .addField(exception)
      .addAnnotation(AnnotationSpec.builder(Generated.class)
          .addMember("value", "$S", MockeryProcessor.class.getCanonicalName())
          .addMember("comments", "$S", CMessages.codeGenerateWarning())
          .build())
      .addAnnotation(AnnotationSpec.builder(RunWith.class)
          .addMember("value", "$T.class", OrderedRunner.class)
          .build())
      .addMethods(methodSpecs)
      .build();
}
 
Example #19
Source Project: OkDeepLink   Author: jjerry   File: DeepLinkInterceptorProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {

    List<InterceptorElement> interceptorElements = generateInterceptorElements(roundEnv);
    if (ElementUtils.isEmpty(interceptorElements)) {
        return false;
    }

    for (InterceptorElement interceptorElement : interceptorElements) {
        String path = interceptorElement.getPath();
        MethodSpec.Builder methodBuilder;
        if (path == null || path.length() == 0) {
            methodBuilder = geneGlobalInterceptorsBuilder(interceptorElement);
        }else {
            methodBuilder = genePathInterceptorsBuilder(interceptorElement);
        }

        try {
            TypeSpec.Builder interceptorInitBuilder = TypeSpec.classBuilder(interceptorElement.getInitClassName())
                    .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
                    .addAnnotation(AnnotationSpec
                            .builder(Aspect.class)
                            .build())
                    .addMethod(methodBuilder.build());
            JavaFile.builder(interceptorElement.getPackageName(), interceptorInitBuilder.build())
                    .build()
                    .writeTo(filer);
        } catch (IOException e) {
            logger.error("Error creating matcher file", interceptorElement.getElement());
        }
    }


    return true;
}
 
Example #20
Source Project: aws-sdk-java-v2   Author: aws   File: PartitionMetadataGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public TypeSpec poetClass() {
    return TypeSpec.classBuilder(className())
                   .addModifiers(FINAL, PUBLIC)
                   .addSuperinterface(ClassName.get(regionBasePackage, "PartitionMetadata"))
                   .addAnnotation(SdkPublicApi.class)
                   .addAnnotation(AnnotationSpec.builder(Generated.class)
                                                .addMember("value",
                                                           "$S",
                                                           "software.amazon.awssdk:codegen")
                                                .build())
                   .addField(FieldSpec.builder(String.class, "DNS_SUFFIX")
                                      .addModifiers(PRIVATE, FINAL, STATIC)
                                      .initializer("$S", partition.getDnsSuffix())
                                      .build())
                   .addField(FieldSpec.builder(String.class, "HOSTNAME")
                                      .addModifiers(PRIVATE, FINAL, STATIC)
                                      .initializer("$S", partition.getDefaults().getHostname())
                                      .build())
                   .addField(FieldSpec.builder(String.class, "ID")
                                      .addModifiers(PRIVATE, FINAL, STATIC)
                                      .initializer("$S", partition.getPartition())
                                      .build())
                   .addField(FieldSpec.builder(String.class, "NAME")
                                      .addModifiers(PRIVATE, FINAL, STATIC)
                                      .initializer("$S", partition.getPartitionName())
                                      .build())
                   .addField(FieldSpec.builder(String.class, "REGION_REGEX")
                                      .addModifiers(PRIVATE, FINAL, STATIC)
                                      .initializer("$S", partition.getRegionRegex())
                                      .build())
                   .addMethod(getter("dnsSuffix", "DNS_SUFFIX"))
                   .addMethod(getter("hostname", "HOSTNAME"))
                   .addMethod(getter("id", "ID"))
                   .addMethod(getter("name", "NAME"))
                   .addMethod(getter("regionRegex", "REGION_REGEX"))
                   .build();
}
 
Example #21
Source Project: Akatsuki   Author: tom91136   File: TransformationTemplateIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
protected void testTypeConverter(boolean registered) {
	final TestField retainedField = new TestField(StringObject.class, "a",
			"new " + StringObject.class.getCanonicalName() + "(\"A\")");
	final Builder fieldBuilder = retainedField.fieldSpecBuilder();
	final ArrayList<TestSource> sources = new ArrayList<>();
	if (registered) {
		fieldBuilder.addAnnotation(Retained.class);
		final AnnotationSpec constraintSpec = AnnotationSpec.builder(TypeConstraint.class)
				.addMember("type", "$T.class", StringObject.class).build();

		final AnnotationSpec.Builder filterSpec = AnnotationSpec.builder(TypeFilter.class)
				.addMember("type", "$L", constraintSpec);

		final AnnotationSpec converterSpec = AnnotationSpec.builder(DeclaredConverter.class)
				.addMember("value", "$L", filterSpec.build()).build();

		final String converterName = generateClassName();
		TestSource converter = new TestSource(TEST_PACKAGE, converterName, Modifier.PUBLIC)
				.appendTransformation(
						(builder, source) -> builder.superclass(StringObjectTypeConverter.class)
								.addAnnotation(converterSpec));
		sources.add(converter);

	} else {
		fieldBuilder.addAnnotation(AnnotationSpec.builder(Retained.class).build());
		fieldBuilder.addAnnotation(AnnotationSpec.builder(With.class)
				.addMember("value", "$T.class", StringObjectTypeConverter.class).build());
	}
	final TestSource testClass = new TestSource(TEST_PACKAGE, generateClassName(),
			Modifier.PUBLIC).appendFields(fieldBuilder.build());
	// out test class always goes in front
	sources.add(0, testClass);
	final RetainedStateTestEnvironment environment = new RetainedStateTestEnvironment(this,
			sources);
	environment.tester().invokeSaveAndRestore();
}
 
Example #22
Source Project: litho   Author: facebook   File: AnnotationExtractor.java    License: Apache License 2.0 5 votes vote down vote up
public static ImmutableList<AnnotationSpec> extractValidAnnotations(TypeElement element) {
  final List<AnnotationSpec> annotations = new ArrayList<>();
  for (AnnotationMirror annotationMirror : element.getAnnotationMirrors()) {
    if (isValidAnnotation(annotationMirror)) {
      annotations.add(AnnotationSpec.get(annotationMirror));
    }
  }

  return ImmutableList.copyOf(annotations);
}
 
Example #23
Source Project: Naviganto   Author: FireZenk   File: RouteProcessor.java    License: MIT License 5 votes vote down vote up
private TypeSpec createRoute(TypeElement typeElement, ArrayList<MethodSpec> methods) {
    messager.printMessage(Diagnostic.Kind.NOTE, "Saving route file...");
    return TypeSpec.classBuilder(typeElement.getSimpleName() + "Route")
            .addAnnotation(AnnotationSpec.builder(Generated.class)
                    .addMember("value", "$S", this.getClass().getName())
                    .build())
            .addModifiers(Modifier.PUBLIC)
            .addSuperinterface(org.firezenk.naviganto.processor.interfaces.Routable.class)
            .addMethods(methods)
            .build();
}
 
Example #24
Source Project: raml-java-tools   Author: mulesoft-labs   File: JacksonScalarTypeSerialization.java    License: 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 Project: litho   Author: facebook   File: DiffValidationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDiffModelHasDifferentParameterFromState() {
  when(mDiffModel.getTypeName())
      .thenReturn(
          ParameterizedTypeName.get(ClassNames.DIFF, TypeName.BOOLEAN.box())
              .annotated(AnnotationSpec.builder(State.class).build()));

  List<SpecModelValidationError> validationErrors = DiffValidation.validate(mSpecModel);
  assertSingleError(validationErrors, DiffValidation.STATE_MISMATCH_ERROR);
}
 
Example #26
Source Project: raml-java-tools   Author: mulesoft-labs   File: GsonObjectExtension.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public FieldSpec.Builder fieldBuilt(ObjectPluginContext objectPluginContext, TypeDeclaration declaration, FieldSpec.Builder incoming, EventType eventType) {
    return incoming
            .addAnnotation(
                    AnnotationSpec.builder(SerializedName.class)
                            .addMember("value", "$S", objectPluginContext.creationResult().getJavaName(EventType.IMPLEMENTATION)).build())
            .addAnnotation(AnnotationSpec.builder(Expose.class).build());
}
 
Example #27
Source Project: soabase-halva   Author: soabase   File: MasterProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private void internalCreateSourceFile(String packageName, ClassName templateQualifiedClassName, ClassName generatedQualifiedClassName, String annotationType, TypeSpec.Builder builder, TypeElement element)
{
    AnnotationSpec generated = AnnotationSpec
        .builder(Generated.class)
        .addMember("value", "\"" + annotationType + "\"")
        .build();
    builder.addAnnotation(generated);

    TypeSpec classSpec = builder.build();
    JavaFile javaFile = JavaFile.builder(packageName, classSpec)
        .addFileComment("Auto generated from $L by Soabase " + annotationType + " annotation processor", templateQualifiedClassName)
        .indent("    ")
        .build();

    Filer filer = processingEnv.getFiler();
    try
    {
        JavaFileObject sourceFile = filer.createSourceFile(generatedQualifiedClassName.toString());
        try ( Writer writer = sourceFile.openWriter() )
        {
            javaFile.writeTo(writer);
        }
    }
    catch ( IOException e )
    {
        String message = "Could not create source file";
        if ( e.getMessage() != null )
        {
            message = message + ": " + e.getMessage();
        }
        processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, message, element);
    }
}
 
Example #28
Source Project: grouter-android   Author: taoweiji   File: RouterComponentCodeBuilder.java    License: Apache License 2.0 5 votes vote down vote up
public static JavaFile getJavaFile(String centerName, List<ComponentModel> componentModels) {
    TypeSpec.Builder componentHelper = TypeSpec.classBuilder(centerName)
            .addModifiers(Modifier.PUBLIC);
    ClassName ComponentUtils = ClassName.bestGuess("com.grouter.ComponentUtils");

    for (ComponentModel component : componentModels) {
        ClassName protocol = ClassName.bestGuess(component.protocol);
        ClassName implement = ClassName.bestGuess(component.implement);


        for (ComponentModel.ConstructorBean constructor : component.constructors) {
            MethodSpec.Builder methodSpec = MethodSpec.methodBuilder(implement.simpleName())
                    .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                    .returns(protocol);
            if (constructor.parameterTypes.size() > 0) {
                methodSpec.addStatement("Class[] classes = new Class[$L]", constructor.parameterTypes.size());
                methodSpec.addStatement("Object[] objects = new Object[$L]", constructor.parameterTypes.size());
                for (int i = 0; i < constructor.parameterTypes.size(); i++) {
                    String clazz = constructor.parameterTypes.get(i);
                    String name = constructor.parameterNames.get(i);
                    TypeName typeName = TypeUtils.getTypeNameFull(clazz);
                    methodSpec.addParameter(typeName, name);
                    if (typeName instanceof ParameterizedTypeName) {
                        methodSpec.addStatement("classes[$L] = $T.class", i, ((ParameterizedTypeName) typeName).rawType);
                    } else {
                        methodSpec.addStatement("classes[$L] = $T.class", i, typeName);
                    }
                    methodSpec.addStatement("objects[$L] = $N", i, name);
                }
                methodSpec.addStatement("return $T.getInstance($T.class,$S,classes,objects)", ComponentUtils, protocol, TypeUtils.reflectionName(implement));
            } else {
                methodSpec.addStatement("return $T.getInstance($T.class,$S)", ComponentUtils, protocol, TypeUtils.reflectionName(implement));
            }
            componentHelper.addMethod(methodSpec.build());
        }
    }
    AnnotationSpec annotationSpec = AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "\"unused\"").build();
    componentHelper.addAnnotation(annotationSpec);
    return JavaFile.builder("com.grouter", componentHelper.build()).build();
}
 
Example #29
Source Project: grouter-android   Author: taoweiji   File: RouterActivityCodeBuilder.java    License: Apache License 2.0 5 votes vote down vote up
public static JavaFile getJavaFile(String centerName,List<ActivityModel> activityModels) {
    TypeSpec.Builder RouterHelper = TypeSpec.classBuilder(centerName)
            .addModifiers(Modifier.PUBLIC);
    TypeSpec.Builder BuilderSet = TypeSpec.classBuilder("BuilderSet")
            .addModifiers(Modifier.PUBLIC, Modifier.STATIC);
    for (ActivityModel item : activityModels) {
        addTypeSpec(centerName,RouterHelper, BuilderSet, item);
    }
    RouterHelper.addType(BuilderSet.build());
    // 增加 unused 注解
    AnnotationSpec annotationSpec = AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "\"unused\"").build();
    RouterHelper.addAnnotation(annotationSpec);
    return JavaFile.builder("com.grouter", RouterHelper.build()).build();
}
 
Example #30
Source Project: litho   Author: facebook   File: StateContainerGenerator.java    License: Apache License 2.0 5 votes vote down vote up
static TypeSpec generate(SpecModel specModel, EnumSet<RunMode> runMode) {
  final TypeSpec.Builder stateContainerClassBuilder =
      TypeSpec.classBuilder(getStateContainerClassName(specModel))
          .superclass(specModel.getStateContainerClass())
          .addAnnotation(
              AnnotationSpec.builder(VisibleForTesting.class)
                  .addMember("otherwise", "$L", VisibleForTesting.PRIVATE)
                  .build())
          .addModifiers(Modifier.STATIC)
          .addTypeVariables(specModel.getTypeVariables());

  final boolean hasUpdateStateWithTransition = hasUpdateStateWithTransition(specModel);
  if (hasUpdateStateWithTransition) {
    stateContainerClassBuilder.addSuperinterface(specModel.getTransitionContainerClass());
  }

  for (StateParamModel stateValue : specModel.getStateValues()) {
    stateContainerClassBuilder.addField(
        FieldSpec.builder(stateValue.getTypeName(), stateValue.getName())
            .addAnnotation(State.class)
            .addAnnotation(
                AnnotationSpec.builder(Comparable.class)
                    .addMember("type", "$L", getComparableType(stateValue, runMode))
                    .build())
            .build());
  }

  if (hasUpdateStateWithTransition) {
    generateTransitionStuff(specModel).addToTypeSpec(stateContainerClassBuilder);
  }

  generateApplyStateUpdateMethod(specModel).addToTypeSpec(stateContainerClassBuilder);

  return stateContainerClassBuilder.build();
}