Java Code Examples for com.squareup.javapoet.AnnotationSpec#builder()

The following examples show how to use com.squareup.javapoet.AnnotationSpec#builder() . 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: PsiMethodExtractorUtils.java    From litho with Apache License 2.0 6 votes vote down vote up
private static List<AnnotationSpec> getExternalAnnotations(PsiParameter param) {
  PsiAnnotation[] annotationsOnParam = AnnotationUtil.getAllAnnotations(param, false, null);
  final List<AnnotationSpec> annotations = new ArrayList<>();

  for (PsiAnnotation annotationOnParam : annotationsOnParam) {
    if (annotationOnParam.getQualifiedName().startsWith(COMPONENTS_PACKAGE)) {
      continue;
    }

    final AnnotationSpec.Builder annotationSpec =
        AnnotationSpec.builder(PsiTypeUtils.guessClassName(annotationOnParam.getQualifiedName()));

    PsiNameValuePair[] paramAttributes = annotationOnParam.getParameterList().getAttributes();
    for (PsiNameValuePair attribute : paramAttributes) {
      annotationSpec.addMember(attribute.getName(), attribute.getDetachedValue().getText());
    }

    annotations.add(annotationSpec.build());
  }

  return annotations;
}
 
Example 2
Source File: MethodExtractorUtils.java    From litho with Apache License 2.0 6 votes vote down vote up
private static List<AnnotationSpec> getExternalAnnotations(VariableElement param) {
  final List<? extends AnnotationMirror> annotationMirrors = param.getAnnotationMirrors();
  final List<AnnotationSpec> annotations = new ArrayList<>();

  for (AnnotationMirror annotationMirror : annotationMirrors) {
    if (annotationMirror.getAnnotationType().toString().startsWith(COMPONENTS_PACKAGE)) {
      continue;
    }

    final AnnotationSpec.Builder annotationSpec =
        AnnotationSpec.builder(
            ClassName.bestGuess(annotationMirror.getAnnotationType().toString()));

    Map<? extends ExecutableElement, ? extends AnnotationValue> elementValues =
        annotationMirror.getElementValues();
    for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> elementValue :
        elementValues.entrySet()) {
      annotationSpec.addMember(
          elementValue.getKey().getSimpleName().toString(), elementValue.getValue().toString());
    }

    annotations.add(annotationSpec.build());
  }

  return annotations;
}
 
Example 3
Source File: JavaClassGenerator.java    From web3j with Apache License 2.0 6 votes vote down vote up
@Override
public void writeClass() throws IOException {
    ClassName EVM_ANNOTATION = ClassName.get("org.web3j", "EVMTest");
    AnnotationSpec.Builder annotationSpec = AnnotationSpec.builder(EVM_ANNOTATION);
    if (JavaVersion.getJavaVersionAsDouble() < 11) {
        ClassName GethContainer = ClassName.get("org.web3j", "NodeType");
        annotationSpec.addMember("value", "type = $T.GETH", GethContainer);
    }
    TypeSpec testClass =
            TypeSpec.classBuilder(theContract.getSimpleName() + "Test")
                    .addMethods(MethodFilter.generateMethodSpecsForEachTest(theContract))
                    .addAnnotation((annotationSpec).build())
                    .addField(
                            theContract,
                            toCamelCase(theContract),
                            Modifier.PRIVATE,
                            Modifier.STATIC)
                    .build();
    JavaFile javaFile = JavaFile.builder(packageName, testClass).build();
    javaFile.writeTo(new File(writePath));
}
 
Example 4
Source File: CodeGeneration.java    From requery with Apache License 2.0 6 votes vote down vote up
static void addGeneratedAnnotation(ProcessingEnvironment processingEnvironment,
                                   TypeSpec.Builder builder) {
    Elements elements = processingEnvironment.getElementUtils();
    SourceVersion sourceVersion = processingEnvironment.getSourceVersion();
    AnnotationSpec.Builder annotationBuilder = null;
    if (sourceVersion.compareTo(SourceVersion.RELEASE_8) > 0) {
        ClassName name = ClassName.bestGuess("javax.annotation.processing.Generated");
        annotationBuilder = AnnotationSpec.builder(name);
    } else {
        if (elements.getTypeElement(Generated.class.getCanonicalName()) != null) {
            annotationBuilder = AnnotationSpec.builder(Generated.class);
        }
    }

    if (annotationBuilder != null) {
        builder.addAnnotation(annotationBuilder
                .addMember("value", "$S",
                        EntityProcessor.class.getCanonicalName()).build());
    }
}
 
Example 5
Source File: JRepeatableCodeGenerator.java    From jackdaw with Apache License 2.0 6 votes vote down vote up
private AnnotationSpec createAnnotation(final AnnotationMirror annotation) {
    final AnnotationSpec.Builder annotationBuilder = AnnotationSpec.builder(
        ClassName.get((TypeElement) annotation.getAnnotationType().asElement())
    );
    final Map<? extends ExecutableElement, ? extends AnnotationValue> params = annotation.getElementValues();

    for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : params.entrySet()) {
        final ExecutableElement paramMethod = entry.getKey();
        final String methodName = TypeUtils.getName(paramMethod);

        final AnnotationValue annotationValue = entry.getValue();
        final Object value = annotationValue.getValue();
        final Pair<String, Object> format = calculateValue(value);

        annotationBuilder.addMember(methodName, format.getKey(), format.getValue());
    }

    return annotationBuilder.build();
}
 
Example 6
Source File: OpenApiClientGenerator.java    From spring-openapi with 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 7
Source File: MessageMetaInfo.java    From raptor with Apache License 2.0 5 votes vote down vote up
public AnnotationSpec generateMessageSpec() {
    AnnotationSpec.Builder builder = AnnotationSpec.builder(RaptorMessage.class);
    OptionUtil.setAnnotationMember(builder, "version", "$S", protoFileMetaInfo.getVersion());
    OptionUtil.setAnnotationMember(builder, "protoFile", "$S", protoFileMetaInfo.getProtoFile());
    OptionUtil.setAnnotationMember(builder, "crc32", "$S", protoFileMetaInfo.getCrc32());
    return builder.build();
}
 
Example 8
Source File: InterfaceMetaInfo.java    From raptor with Apache License 2.0 5 votes vote down vote up
public AnnotationSpec generateInterfaceSpec() {
    AnnotationSpec.Builder builder = AnnotationSpec.builder(RaptorInterface.class);
    OptionUtil.setAnnotationMember(builder, "appId", "$S", protoFileMetaInfo.getAppId());
    OptionUtil.setAnnotationMember(builder, "appName", "$S", protoFileMetaInfo.getAppName());
    OptionUtil.setAnnotationMember(builder, "version", "$S", protoFileMetaInfo.getVersion());
    OptionUtil.setAnnotationMember(builder, "protoFile", "$S", protoFileMetaInfo.getProtoFile());
    OptionUtil.setAnnotationMember(builder, "crc32", "$S", protoFileMetaInfo.getCrc32());
    // TODO: 2018/5/16 先写死spring
    OptionUtil.setAnnotationMember(builder, "library", "$S", "spring");

    return builder.build();

}
 
Example 9
Source File: SimpleProcessorTests.java    From spring-init with 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 10
Source File: JavadocProcessor.java    From drift with Apache License 2.0 5 votes vote down vote up
private static AnnotationSpec documentationAnnotation(List<String> lines)
{
    AnnotationSpec.Builder builder = AnnotationSpec.builder(ThriftDocumentation.class);
    for (String line : lines) {
        builder.addMember("value", "$S", line);
    }
    return builder.build();
}
 
Example 11
Source File: ValueParser.java    From dataenum with Apache License 2.0 5 votes vote down vote up
private static Iterable<AnnotationSpec> parseMethodAnnotations(
    ExecutableElement methodElement, Messager messager) {
  ArrayList<AnnotationSpec> annotations = new ArrayList<>();

  for (AnnotationMirror annotationMirror : methodElement.getAnnotationMirrors()) {
    TypeName annotationTypeName =
        ClassName.get(annotationMirror.getAnnotationType().asElement().asType());

    if (!(annotationTypeName instanceof ClassName)) {
      messager.printMessage(
          Kind.ERROR,
          "Annotation is not a class; this shouldn't happen",
          methodElement,
          annotationMirror);
      continue;
    }

    Builder builder = AnnotationSpec.builder(((ClassName) annotationTypeName));

    for (Entry<? extends ExecutableElement, ? extends AnnotationValue> entry :
        annotationMirror.getElementValues().entrySet()) {

      builder.addMember(entry.getKey().getSimpleName().toString(), entry.getValue().toString());
    }

    annotations.add(builder.build());
  }

  return annotations;
}
 
Example 12
Source File: ResourceMethodExtensionPlugin.java    From raml-module-builder with Apache License 2.0 5 votes vote down vote up
private AnnotationSpec buildAnnotation(Class<?> annotationClass, Object value, String type){

    AnnotationSpec.Builder annoBuilder = AnnotationSpec.builder(annotationClass);

    if(type.equalsIgnoreCase("Size")){
      //size can contain two values (min and max) so it is unlike the other potential annotations
      String []multipleAnnos = ((String)value).split(",");
      for (int j = 0; j < multipleAnnos.length; j++) {
        if(j == 0){
          annoBuilder.addMember("min", "$L", Integer.valueOf(multipleAnnos[j].trim()));
        }
        else{
          annoBuilder.addMember("max", "$L", Integer.valueOf(multipleAnnos[j].trim()));
        }
      }
    }
    else if(!type.equalsIgnoreCase("REQUIRED")){
      //a required annotation will add a @notnull annotation
      //THERE IS CURRENTLY NO SUPPORT TO MAKE A REQUIRED PARAM NOT REQUIRED
      if(value instanceof String){
        if(type.equalsIgnoreCase("PATTERN")){
          annoBuilder.addMember("regexp", "$S", (String)value);
        }
        else{
          annoBuilder.addMember(ANNOTATION_VALUE, "$S", (String)value);
        }
      }
      else if(value instanceof Boolean){
        annoBuilder.addMember(ANNOTATION_VALUE, "$L", (Boolean)value);
      }
      else if(value instanceof Integer){
        annoBuilder.addMember(ANNOTATION_VALUE, "$L", (Integer)value);
      }
    }

    return annoBuilder.build();
  }
 
Example 13
Source File: RetainedTestField.java    From Akatsuki with Apache License 2.0 5 votes vote down vote up
@Override
protected Builder fieldSpecBuilder() {
	final Builder builder = super.fieldSpecBuilder();
	final AnnotationSpec.Builder annotationBuilder = AnnotationSpec.builder(Retained.class);
	if (skip) {
		annotationBuilder.addMember("skip", "$L", true);
	}
	if (policy != null) {
		annotationBuilder.addMember("restorePolicy", "$T.$L", RestorePolicy.class, policy);
	}
	builder.addAnnotation(annotationBuilder.build());
	return builder;
}
 
Example 14
Source File: ArgTestField.java    From Akatsuki with Apache License 2.0 5 votes vote down vote up
@Override
protected Builder fieldSpecBuilder() {
	final Builder builder = super.fieldSpecBuilder();
	final AnnotationSpec.Builder annotationBuilder = AnnotationSpec.builder(Arg.class);
	if (skip) {
		annotationBuilder.addMember("skip", "$L", true);
	}

	if (optional) {
		annotationBuilder.addMember("optional", "$L", true);
	}
	builder.addAnnotation(annotationBuilder.build());
	return builder;
}
 
Example 15
Source File: TransformationTemplateIntegrationTest.java    From Akatsuki with Apache License 2.0 5 votes vote down vote up
protected AnnotationSpec createTransformationTemplate(Bound bound, Class<?> staticClass,
		Class<?>... constraints) {
	final String objectFqcn = staticClass.getCanonicalName();
	AnnotationSpec save = AnnotationSpec
			.builder(StatementTemplate.class).addMember("value",
					"\"{{bundle}}.putString({{keyName}}, $L.wrap({{fieldName}}))\"", objectFqcn)
			.build();

	AnnotationSpec restore = AnnotationSpec.builder(StatementTemplate.class)
			.addMember("type", "$T.$L", StatementTemplate.Type.class,
					StatementTemplate.Type.ASSIGNMENT)
			.addMember("value", "\"$L.unwrap({{bundle}}.getString({{keyName}}))\"", objectFqcn)
			.addMember("variable", "\"{{fieldName}}\"").build();

	final AnnotationSpec.Builder annotationSpec = AnnotationSpec
			.builder(TransformationTemplate.class).addMember("save", "$L", save)
			.addMember("restore", "$L", restore)
			.addMember("execution", "$T.$L", Execution.class, Execution.BEFORE);

	for (Class<?> constraint : constraints) {
		final AnnotationSpec constraintsSpec = AnnotationSpec.builder(TypeConstraint.class)
				.addMember("type", "$T.class", constraint)
				.addMember("bound", "$T.$L", Bound.class, bound).build();

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

		annotationSpec.addMember("filters", "$L", filterSpec.build());

	}
	return annotationSpec.build();
}
 
Example 16
Source File: AnnotationSpecUtil.java    From kaif-android with Apache License 2.0 5 votes vote down vote up
public static AnnotationSpec generate(AnnotationMirror annotation) {
  TypeElement element = (TypeElement) annotation.getAnnotationType().asElement();
  AnnotationSpec.Builder builder = AnnotationSpec.builder(ClassName.get(element));
  Visitor visitor = new Visitor(builder);
  for (ExecutableElement executableElement : annotation.getElementValues().keySet()) {
    String name = executableElement.getSimpleName().toString();
    AnnotationValue value = annotation.getElementValues().get(executableElement);
    value.accept(visitor, new Entry(name, value));
  }
  return builder.build();
}
 
Example 17
Source File: MethodMetaInfo.java    From raptor with Apache License 2.0 4 votes vote down vote up
public AnnotationSpec generateRaptorMethod() {
    AnnotationSpec.Builder builder = AnnotationSpec.builder(RaptorMethod.class);
    return builder.build();

}
 
Example 18
Source File: InterfaceMetaInfo.java    From raptor with Apache License 2.0 4 votes vote down vote up
public AnnotationSpec generateRequestMappingSpec() {
    AnnotationSpec.Builder builder = AnnotationSpec.builder(RequestMapping.class);
     OptionUtil.setAnnotationMember(builder, "path", "$S", servicePath);
     return builder.build();
}
 
Example 19
Source File: JacksonDiscriminatorInheritanceTypeExtension.java    From raml-java-tools with Apache License 2.0 4 votes vote down vote up
@Override
public TypeSpec.Builder classCreated(ObjectPluginContext objectPluginContext, ObjectTypeDeclaration ramlType, TypeSpec.Builder typeSpec, EventType eventType) {

  if ( eventType == EventType.IMPLEMENTATION) {
    return typeSpec;
  }

  ObjectTypeDeclaration otr = ramlType;

  if (otr.discriminator() != null && objectPluginContext.childClasses(otr.name()).size() > 0) {

    typeSpec.addAnnotation(AnnotationSpec.builder(JsonTypeInfo.class)
            .addMember("use", "$T.Id.NAME", JsonTypeInfo.class)
            .addMember("include", "$T.As.EXISTING_PROPERTY", JsonTypeInfo.class)
            .addMember("property", "$S", otr.discriminator()).build());

    AnnotationSpec.Builder subTypes = AnnotationSpec.builder(JsonSubTypes.class);
    for (CreationResult result : objectPluginContext.childClasses(ramlType.name())) {

      subTypes.addMember(
              "value",
              "$L",
              AnnotationSpec
                      .builder(JsonSubTypes.Type.class)
                      .addMember("value", "$L",
                              result.getJavaName(EventType.INTERFACE) + ".class").build());
    }

    subTypes.addMember(
            "value",
            "$L",
            AnnotationSpec
                    .builder(JsonSubTypes.Type.class)
                    .addMember("value", "$L",
                            objectPluginContext.creationResult().getJavaName(EventType.INTERFACE) + ".class").build());

    typeSpec.addAnnotation(subTypes.build());

  }

  if (otr.discriminatorValue() != null) {

    typeSpec.addAnnotation(AnnotationSpec.builder(JsonTypeName.class)
            .addMember("value", "$S", otr.discriminatorValue()).build());
  }


  if (!Annotations.ABSTRACT.get(otr)) {

    typeSpec.addAnnotation(AnnotationSpec.builder(JsonDeserialize.class)
            .addMember("as", "$T.class", objectPluginContext.creationResult().getJavaName(EventType.IMPLEMENTATION))
            .build());
  }


  return typeSpec;
}
 
Example 20
Source File: JacksonDiscriminatorInheritanceTypeExtension.java    From raml-java-tools with Apache License 2.0 4 votes vote down vote up
@Override
public TypeSpec.Builder classCreated(ObjectPluginContext objectPluginContext, ObjectTypeDeclaration ramlType, TypeSpec.Builder typeSpec, EventType eventType) {

  if ( eventType == EventType.IMPLEMENTATION) {
    return typeSpec;
  }

  ObjectTypeDeclaration otr = ramlType;

  if (otr.discriminator() != null && objectPluginContext.childClasses(otr.name()).size() > 0) {

    typeSpec.addAnnotation(AnnotationSpec.builder(JsonTypeInfo.class)
            .addMember("use", "$T.Id.NAME", JsonTypeInfo.class)
            .addMember("include", "$T.As.EXISTING_PROPERTY", JsonTypeInfo.class)
            .addMember("property", "$S", otr.discriminator()).build());

    AnnotationSpec.Builder subTypes = AnnotationSpec.builder(JsonSubTypes.class);
    for (CreationResult result : objectPluginContext.childClasses(ramlType.name())) {

      subTypes.addMember(
              "value",
              "$L",
              AnnotationSpec
                      .builder(JsonSubTypes.Type.class)
                      .addMember("value", "$L",
                              result.getJavaName(EventType.INTERFACE) + ".class").build());
    }

    subTypes.addMember(
            "value",
            "$L",
            AnnotationSpec
                    .builder(JsonSubTypes.Type.class)
                    .addMember("value", "$L",
                            objectPluginContext.creationResult().getJavaName(EventType.INTERFACE) + ".class").build());

    typeSpec.addAnnotation(subTypes.build());

  }

  if (otr.discriminatorValue() != null) {

    typeSpec.addAnnotation(AnnotationSpec.builder(JsonTypeName.class)
            .addMember("value", "$S", otr.discriminatorValue()).build());
  }


  if (!Annotations.ABSTRACT.get(otr)) {

    typeSpec.addAnnotation(AnnotationSpec.builder(JsonDeserialize.class)
            .addMember("as", "$T.class", objectPluginContext.creationResult().getJavaName(EventType.IMPLEMENTATION))
            .build());
  }


  return typeSpec;
}