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 File: TestingDIComponentProcessor.java    From litho with 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 #2
Source File: JaxbObjectExtension.java    From raml-java-tools with 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 #3
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 #4
Source File: BrewJavaFile.java    From Mockery with 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 #5
Source File: SubcomponentProcessing.java    From Auto-Dagger2 with 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 #6
Source File: DeepLinkServiceProcessor.java    From OkDeepLink with 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 #7
Source File: MethodParamModelFactoryTest.java    From litho with 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 #8
Source File: MethodParamModelFactoryTest.java    From litho with 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 #9
Source File: CodeGenerator.java    From shortbread with 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 #10
Source File: MethodParamModelFactoryTest.java    From litho with 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 #11
Source File: PropertySchemaAnnotationSupport.java    From anno4j with 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 #12
Source File: OpenApiClientGenerator.java    From spring-openapi with 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 #13
Source File: MatcherGenerator.java    From litho with Apache License 2.0 5 votes vote down vote up
private static MethodSpec sipBuilder(SpecModel specModel, final PropModel prop) {
  final AnnotationSpec spAnnotation =
      AnnotationSpec.builder(ClassNames.DIMENSION)
          .addMember("unit", "$T.SP", ClassNames.DIMENSION)
          .build();

  return builder(
      specModel,
      prop,
      prop.getName() + "Sp",
      Collections.singletonList(parameter(prop, TypeName.FLOAT, "sips", spAnnotation)),
      "$L.sipsToPixels(sips)",
      RESOURCE_RESOLVER);
}
 
Example #14
Source File: RouterComponentCodeBuilder.java    From grouter-android with 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 #15
Source File: ModelInjection.java    From vault with Apache License 2.0 5 votes vote down vote up
private void appendSetField(TypeSpec.Builder builder) {
  MethodSpec.Builder method = MethodSpec.methodBuilder("setField")
      .addAnnotation(Override.class)
      .addAnnotation(
          AnnotationSpec.builder(SuppressWarnings.class)
              .addMember("value", "$S", "unchecked")
              .build())
      .addModifiers(Modifier.PUBLIC)
      .returns(boolean.class)
      .addParameter(ParameterSpec.builder(ClassName.get(originatingElement), "resource").build())
      .addParameter(ParameterSpec.builder(ClassName.get(String.class), "name").build())
      .addParameter(ParameterSpec.builder(ClassName.get(Object.class), "value").build());

  FieldMeta[] array = fields.toArray(new FieldMeta[fields.size()]);
  for (int i = 0; i < array.length; i++) {
    FieldMeta field = array[i];
    if (i == 0) {
      method.beginControlFlow("if ($S.equals(name))", field.name());
    } else {
      method.endControlFlow().beginControlFlow("else if ($S.equals(name))", field.name());
    }
    method.addStatement("resource.$L = ($T) value", field.name(), field.type());
  }
  method.endControlFlow()
      .beginControlFlow("else")
        .addStatement("return false")
      .endControlFlow()
      .addStatement("return true");

  builder.addMethod(method.build());
}
 
Example #16
Source File: MatcherGenerator.java    From litho with Apache License 2.0 5 votes vote down vote up
private static MethodSpec dipBuilder(SpecModel specModel, final PropModel prop) {
  final AnnotationSpec dipAnnotation =
      AnnotationSpec.builder(ClassNames.DIMENSION)
          .addMember("unit", "$T.DP", ClassNames.DIMENSION)
          .build();

  return builder(
      specModel,
      prop,
      prop.getName() + "Dip",
      Collections.singletonList(parameter(prop, TypeName.FLOAT, "dips", dipAnnotation)),
      "$L.dipsToPixels(dips)",
      RESOURCE_RESOLVER);
}
 
Example #17
Source File: BuilderGenerator.java    From litho with Apache License 2.0 5 votes vote down vote up
private static ParameterSpec parameterWithoutNullableAnnotation(
    PropModel prop, TypeName type, String name, AnnotationSpec... extraAnnotations) {
  List<AnnotationSpec> externalAnnotations = new ArrayList<>();
  for (AnnotationSpec annotationSpec : prop.getExternalAnnotations()) {
    if (!annotationSpec.type.toString().contains("Nullable")) {
      externalAnnotations.add(annotationSpec);
    }
  }

  return parameter(type, name, externalAnnotations, extraAnnotations);
}
 
Example #18
Source File: BuilderGenerator.java    From litho with Apache License 2.0 5 votes vote down vote up
private static TypeSpecDataHolder regularBuilders(
    SpecModel specModel, PropModel prop, int requiredIndex, AnnotationSpec... extraAnnotations) {
  final TypeSpecDataHolder.Builder dataHolder = TypeSpecDataHolder.newBuilder();
  dataHolder.addMethod(regularBuilder(specModel, prop, requiredIndex, extraAnnotations));
  if (prop.hasVarArgs()) {
    dataHolder.addMethod(varArgBuilder(specModel, prop, requiredIndex));
  }
  return dataHolder.build();
}
 
Example #19
Source File: StateContainerGenerator.java    From litho with 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();
}
 
Example #20
Source File: DeepLinkInjectProcessor.java    From OkDeepLink with Apache License 2.0 5 votes vote down vote up
private MethodSpec geneSaveInstanceMethod(TypeElement targetElement, List<Element> fieldElements) {

        MethodSpec.Builder saveInstanceMethodBuilder = methodBuilder("onSaveInstanceState")
                .addModifiers(PUBLIC)
                .addException(Throwable.class)
                .addAnnotation(AnnotationSpec
                        .builder(After.class)
                        .addMember("value", "$S", "execution(* " + targetElement.getQualifiedName() + ".onSaveInstanceState(..))")
                        .build())
                .addParameter(JoinPoint.class, "joinPoint");

        CodeBlock.Builder saveInstanceCodeBuilder = geneSaveInstanceCodeBuilder(targetElement);

        List<String> queryKeys = new ArrayList<>();

        for (Element queryElement : fieldElements) {
            if (queryElement.getAnnotation(Query.class) != null) {

                String queryKey = queryElement.getAnnotation(Query.class).value();
                if (queryKeys.contains(queryKey)) {
                    logger.error("The inject query key cannot be Duplicate" + Query.class.getCanonicalName(), queryElement);
                }
                queryKeys.add(queryKey);
                saveInstanceCodeBuilder.add("intent.putExtra($S,target.$L);\n", queryKey, queryElement);
            }
        }

        saveInstanceCodeBuilder.add("saveBundle.putAll(intent.getExtras());\n");

        saveInstanceMethodBuilder.addCode(saveInstanceCodeBuilder.build());

        return saveInstanceMethodBuilder.build();
    }
 
Example #21
Source File: RouterActivityCodeBuilder.java    From grouter-android with 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 #22
Source File: GsonObjectExtension.java    From raml-java-tools with 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 #23
Source File: DiffValidationTest.java    From litho with 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 #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: RouteProcessor.java    From Naviganto with 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 #26
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 #27
Source File: AnnotationExtractor.java    From litho with 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 #28
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 #29
Source File: TransformationTemplateIntegrationTest.java    From Akatsuki with 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 #30
Source File: MasterProcessor.java    From soabase-halva with 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);
    }
}