Java Code Examples for com.squareup.javapoet.AnnotationSpec

The following are top voted examples for showing how to use com.squareup.javapoet.AnnotationSpec. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: LifecycleAware   File: LifecycleObserverGenerator.java   Source Code and License 7 votes vote down vote up
private MethodSpec defineLifecycleHook() {

        final String methodName = "onLifecycleEvent";

        Lifecycle.Event lifecycleEvent = annotatedElement.getAnnotation(LifecycleAware.class).value();

        AnnotationSpec archLifeCycleSpec = AnnotationSpec.builder(OnLifecycleEvent.class)
                .addMember(ANNOT_DEFAULT_NAME, "$T.$L", Lifecycle.Event.class, lifecycleEvent)
                .build();

        return MethodSpec.methodBuilder(lifecycleEvent.name())
                .addAnnotation(archLifeCycleSpec)
                .addModifiers(Modifier.PUBLIC)
                .addStatement("$L.$L($T.$L)", FIELD_OBSERVER, methodName, Lifecycle.Event.class, lifecycleEvent)
                .build();
    }
 
Example 2
Project: shoebill   File: ShoebillProcessor.java   Source Code and License 6 votes vote down vote up
private MethodSpec getSingletonSetterMethod(ClassName className, FieldSpec singletonField) {
    ParameterSpec parameter = ParameterSpec
            .builder(className, "wrapper")
            .build();

    AnnotationSpec visibleForTesting = AnnotationSpec
            .builder(VisibleForTesting.class)
            .addMember("otherwise", "VisibleForTesting.NONE")
            .build();

    return MethodSpec
            .methodBuilder("setInstance")
            .addAnnotation(visibleForTesting)
            .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
            .addParameter(parameter)
            .addStatement("$N = $N", singletonField, parameter)
            .build();
}
 
Example 3
Project: GitHub   File: IndexerGenerator.java   Source Code and License 6 votes vote down vote up
private static TypeSpec generate(List<TypeElement> libraryModules,
    Class<? extends Annotation> annotation) {
  AnnotationSpec.Builder annotationBuilder =
      AnnotationSpec.builder(Index.class);

  String value = getAnnotationValue(annotation);
  for (TypeElement childModule : libraryModules) {
    annotationBuilder.addMember(value, "$S", ClassName.get(childModule).toString());
  }

  String indexerName = INDEXER_NAME_PREFIX + annotation.getSimpleName() + "_";
  for (TypeElement element : libraryModules) {
    indexerName += element.getQualifiedName().toString().replace(".", "_");
    indexerName += "_";
  }
  indexerName = indexerName.substring(0, indexerName.length() - 1);

  return TypeSpec.classBuilder(indexerName)
      .addAnnotation(annotationBuilder.build())
      .addModifiers(Modifier.PUBLIC)
      .build();
}
 
Example 4
Project: GitHub   File: RequestManagerGenerator.java   Source Code and License 6 votes vote down vote up
private MethodSpec generateAsMethod(String generatedCodePackageName, TypeSpec requestBuilder) {
  TypeVariableName resourceType = TypeVariableName.get("ResourceType");
  ParameterizedTypeName classOfResouceType = ParameterizedTypeName
      .get(ClassName.get(Class.class), resourceType);

  ClassName generatedRequestBuilderClassName =
      ClassName.get(generatedCodePackageName, requestBuilder.name);

  ParameterizedTypeName requestBuilderOfResourceType = ParameterizedTypeName
      .get(generatedRequestBuilderClassName, resourceType);

  return MethodSpec.methodBuilder("as")
      .addModifiers(Modifier.PUBLIC)
      .addAnnotation(Override.class)
      .addTypeVariable(TypeVariableName.get("ResourceType"))
      .addParameter(classOfResouceType, "resourceClass")
      .addAnnotation(AnnotationSpec.builder(CHECK_RESULT_CLASS_NAME).build())
      .returns(requestBuilderOfResourceType)
      .addStatement("return new $T<>(glide, this, resourceClass, context)",
          this.generatedRequestBuilderClassName)
      .build();
}
 
Example 5
Project: GitHub   File: RequestManagerGenerator.java   Source Code and License 6 votes vote down vote up
/**
 * Generates overrides of existing RequestManager methods so that they return our generated
 * RequestBuilder subtype.
 */
private MethodSpec generateRequestManagerRequestBuilderMethodOverride(
    ExecutableElement methodToOverride) {
   // We've already verified that this method returns a RequestBuilder and RequestBuilders have
  // exactly one type argument, so this is safe unless those assumptions change.
  TypeMirror typeArgument =
      ((DeclaredType) methodToOverride.getReturnType()).getTypeArguments().get(0);

  ParameterizedTypeName generatedRequestBuilderOfType =
      ParameterizedTypeName.get(generatedRequestBuilderClassName, ClassName.get(typeArgument));

  MethodSpec.Builder builder = ProcessorUtil.overriding(methodToOverride)
      .returns(generatedRequestBuilderOfType)
      .addCode(
          ProcessorUtil.generateCastingSuperCall(
              generatedRequestBuilderOfType, methodToOverride));

  for (AnnotationMirror mirror : methodToOverride.getAnnotationMirrors()) {
    builder.addAnnotation(AnnotationSpec.get(mirror));
  }
  return builder.build();
}
 
Example 6
Project: GitHub   File: IndexerGenerator.java   Source Code and License 6 votes vote down vote up
private static TypeSpec generate(List<TypeElement> libraryModules,
    Class<? extends Annotation> annotation) {
  AnnotationSpec.Builder annotationBuilder =
      AnnotationSpec.builder(Index.class);

  String value = getAnnotationValue(annotation);
  for (TypeElement childModule : libraryModules) {
    annotationBuilder.addMember(value, "$S", ClassName.get(childModule).toString());
  }

  StringBuilder indexerName = new StringBuilder(
      INDEXER_NAME_PREFIX + annotation.getSimpleName() + "_");
  for (TypeElement element : libraryModules) {
    indexerName.append(element.getQualifiedName().toString().replace(".", "_"));
    indexerName.append("_");
  }
  indexerName = new StringBuilder(indexerName.substring(0, indexerName.length() - 1));

  return TypeSpec.classBuilder(indexerName.toString())
      .addAnnotation(annotationBuilder.build())
      .addModifiers(Modifier.PUBLIC)
      .build();
}
 
Example 7
Project: raml-java-tools   File: AnnotationSpecMatchers.java   Source Code and License 6 votes vote down vote up
public static Matcher<AnnotationSpec> hasMember(final String member) {

    return new TypeSafeMatcher<AnnotationSpec>() {

      @Override
      protected boolean matchesSafely(AnnotationSpec item) {
        return item.members.containsKey(member);
      }

      @Override
      public void describeTo(Description description) {

        description.appendText("has member " + member);
      }
    };
  }
 
Example 8
Project: shortbread   File: CodeGenerator.java   Source Code and License 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 9
Project: DUnit   File: InitMethodUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 创建init方法,用于数据初始化
 *
 * @param methodName        方法名
 * @param genericTypesClass ArrayList泛型的类型
 * @param gsonDataString    ArrayList被Gson转换出的字符串
 * @param modelListVariableName      GsonData被还原后的临时变量名
 * @return 初始化方法的构造器
 */
public static MethodSpec.Builder createInitMethodSpecBuilder(String methodName, Class genericTypesClass, String gsonDataString, String modelListVariableName) {
	String tmpStr;

	//Override注解
	AnnotationSpec annotation = createOverrideAnnotation();

	//return type,返回值
	ParameterizedType returnType = GenericTypesUtil.type(ArrayList.class, genericTypesClass);

	//protected ArrayList<DUnitModel> initUnitModels(),函数声明
	MethodSpec.Builder initMethodBuilder = MethodSpec
			.methodBuilder(methodName)
			.addModifiers(Modifier.PROTECTED)
			.addAnnotation(annotation)
			.returns(returnType);

	//Gson gson = new Gson();
	initMethodBuilder.addStatement("$T gson = new $T()", Gson.class, Gson.class);
	//ParameterizedType type = GenericTypesUtil.type(ArrayList.class,DUnitModel.class);
	initMethodBuilder.addStatement("$T type = $T.type($T.class,$T.class)", ParameterizedType.class, GenericTypesUtil.class, ArrayList.class, genericTypesClass);
	//ArrayList<DUnitModel> unitModels = gson.fromJson(unitModelsString_c,type);
	tmpStr = String.format("$T<$T> %s = gson.fromJson($S,type)", modelListVariableName);
	initMethodBuilder.addStatement(tmpStr, ArrayList.class, genericTypesClass, gsonDataString);
	return initMethodBuilder;
}
 
Example 10
Project: json2java4idea   File: GsonClassBuilder.java   Source Code and License 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 11
Project: jso-builder   File: JSOBuilderProcessor.java   Source Code and License 6 votes vote down vote up
private TypeSpec createJsArrayInterface() {
    TypeVariableName variableName = TypeVariableName.get("T");
    return TypeSpec.classBuilder("JsArray")
            .addModifiers(Modifier.STATIC, Modifier.FINAL)
            .addTypeVariable(variableName)
            .addAnnotation(AnnotationSpec.builder(ClassNames.JSINTEROP_JSTYPE)
                    .addMember("isNative", "true")
                    .addMember("namespace", "$T.GLOBAL", ClassNames.JSINTEROP_JSPACKAGE)
                    .addMember("name", "$S", "Array")
                    .build())
            .addMethod(MethodSpec.methodBuilder("push")
                    .addModifiers(Modifier.PUBLIC, Modifier.NATIVE)
                    .addParameter(variableName, "item")
                    .build())
            .build();
}
 
Example 12
Project: jso-builder   File: JSOBuilderProcessor.java   Source Code and License 6 votes vote down vote up
private TypeSpec createGlobalInterface() {
    return TypeSpec.classBuilder("Global")
            .addModifiers(Modifier.STATIC, Modifier.FINAL)
            .addAnnotation(AnnotationSpec.builder(ClassNames.JSINTEROP_JSTYPE)
                    .addMember("isNative", "true")
                    .addMember("namespace", "$T.GLOBAL", ClassNames.JSINTEROP_JSPACKAGE)
                    .build())
            .addFields(Stream.of(Object.class,
                    Boolean.TYPE, Byte.TYPE, Character.TYPE, Double.TYPE,
                    Float.TYPE, Integer.TYPE, Long.TYPE, Short.TYPE)
                    .map(type -> FieldSpec.builder(type, "UNDEFINED_" + type.getSimpleName().toUpperCase())
                            .addModifiers(Modifier.PUBLIC, Modifier.STATIC)
                            .addAnnotation(AnnotationSpec.builder(ClassNames.JSINTEROP_JSPROPERTY)
                                    .addMember("namespace", "$T.GLOBAL", ClassNames.JSINTEROP_JSPACKAGE)
                                    .addMember("name", "$S", "undefined")
                                    .build())
                            .build())
                .collect(Collectors.toList()))
            .build();
}
 
Example 13
Project: Jerkoff   File: PojoCreatorImpl.java   Source Code and License 6 votes vote down vote up
/**
 * genera il metodo di test per method di clazz
 * 
 * @param count
 * @param method
 * @param clazz
 * @param infoFromMongoDb
 * @param methodOutput
 * @return
 */
private MethodSpec getMethodSpec(int count, Method method, Class<?> clazz, Document methodInputs,
		Document methodOutput) {
	String result = getAssignmentOfMethodResult(method);
	String expected = getExpectedResultAsBooleanAssert(method, methodOutput);
	MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(method.getName() + count + TEST);
	/*
	 * for non spring test
	 */
	String invokerName = getInvokerName(method, clazz, methodInputs, methodBuilder);
	String params = getParams(method, methodBuilder, methodInputs);
	AnnotationSpec.Builder annSpecBuilder = AnnotationSpec.builder(Test.class);
	addExpectedExceptionIfAny(methodInputs, annSpecBuilder);
	AnnotationSpec annTestSpec = annSpecBuilder.build();
	methodBuilder.addAnnotation(annTestSpec)
			.addStatement(result + invokerName + ".$N(" + params + ")", method.getName())
			.addModifiers(Modifier.PUBLIC);
	methodBuilder.addStatement("$L.assertTrue(" + expected + ")", Assert.class.getName());
	methodBuilder.addJavadoc("\n");
	return methodBuilder.build();
}
 
Example 14
Project: Jerkoff   File: PojoCreatorImpl.java   Source Code and License 6 votes vote down vote up
/**
 * genera classe di test per clazz
 * 
 * @param clazz
 * @param prop
 * @param mongo
 * @return
 */
@Override
public TypeSpec getTypeSpec(Class<?> clazz) {
	Builder classTestBuilder = TypeSpec.classBuilder(clazz.getSimpleName() + TEST);
	ClassName superClass = ClassName.get(
			PropertiesUtils.getRequiredProperty(prop, PropertiesUtils.TEST_BASE_PACKAGE),
			PropertiesUtils.getRequiredProperty(prop, PropertiesUtils.TEST_BASE_CLASS));
	classTestBuilder.superclass(superClass);
	classTestBuilder.addJavadoc("@author \n");
	classTestBuilder.addModifiers(Modifier.PUBLIC);
	AnnotationSpec.Builder annSpecBuilder = AnnotationSpec.builder(Generated.class);
	annSpecBuilder.addMember("value", "\"it.fratta.jerkoff.Generator\"");
	annSpecBuilder.addMember("date", "\"" + Calendar.getInstance().getTime().toString() + "\"");
	AnnotationSpec annGenSpec = annSpecBuilder.build();
	classTestBuilder.addAnnotation(annGenSpec);
	/*
	 * for spring test
	 */
	// FieldSpec.Builder spec = FieldSpec.builder(clazz,
	// getNewInstanceOfNoParameters(clazz), Modifier.PRIVATE);
	// spec.addAnnotation(Autowired.class);
	// classTestBuilder.addField(spec.build());
	addClassMethodsToBuilder(classTestBuilder, clazz);
	return classTestBuilder.build();
}
 
Example 15
Project: java-code-templates   File: TemplateSubstitutionVisitor.java   Source Code and License 6 votes vote down vote up
@Override
public DeferredTypeSpecBuilder visitTypeAsClass(final TypeElement element, final DeferredTypeSpecBuilder outerBuilder) {

	final Collection<AnnotationSpec> descriptorAnnotations = descriptorInventory.typeAnnotations(element);
	final TypeSubstitution substitution = applyDeclaredTypeSubstitution(element);
	final DeferredTypeSpecBuilder innerBuilder = DeferredTypeSpecBuilder.create(classBuilder(substitution.raw())
			.addTypeVariables(substitution.typeParameters())
			.addModifiers(modifiers(element))
			.addAnnotations(mergeAnnotations(copyableAnnotations(element), descriptorAnnotations))
			.superclass(applyTypeSubstitution(element.getSuperclass())))
			;

	element.getInterfaces().forEach(iface -> innerBuilder.wrapped().addSuperinterface(applyTypeSubstitution(iface)));
	element.getEnclosedElements().forEach(child -> visit(child, innerBuilder));

	// If this is a nested type, we now roll up the new type into the parent.
	return (outerBuilder != null)
			? outerBuilder.addDeferred(innerBuilder)
					: innerBuilder;
}
 
Example 16
Project: java-code-templates   File: TemplateSubstitutionVisitor.java   Source Code and License 6 votes vote down vote up
@Override
public DeferredTypeSpecBuilder visitTypeAsInterface(final TypeElement element, final DeferredTypeSpecBuilder outerBuilder) {

	final Collection<AnnotationSpec> descriptorAnnotations = descriptorInventory.typeAnnotations(element);
	final TypeSubstitution substitution = applyDeclaredTypeSubstitution(element);
	final DeferredTypeSpecBuilder innerBuilder = DeferredTypeSpecBuilder.create(interfaceBuilder(substitution.raw())
			.addTypeVariables(substitution.typeParameters())
			.addModifiers(modifiers(element))
			.addAnnotations(mergeAnnotations(copyableAnnotations(element), descriptorAnnotations)));

	element.getInterfaces().forEach(iface -> innerBuilder.wrapped().addSuperinterface(applyTypeSubstitution(iface)));
	element.getEnclosedElements().forEach(child -> visit(child, innerBuilder));

	// If this is a nested type, we now roll up the new type into the parent.
	return (outerBuilder != null)
			? outerBuilder.addDeferred(innerBuilder)
					: innerBuilder;
}
 
Example 17
Project: java-code-templates   File: TemplateSubstitutionVisitor.java   Source Code and License 6 votes vote down vote up
@Override
public DeferredTypeSpecBuilder visitTypeAsAnnotationType(final TypeElement element, final DeferredTypeSpecBuilder outerBuilder) {

	// Annotation is the implicit parent interface here, but annotations
	// can't have explicit super interfaces.

	final Collection<AnnotationSpec> descriptorAnnotations = descriptorInventory.typeAnnotations(element);
	final TypeSubstitution substitution = applyDeclaredTypeSubstitution(element);
	final DeferredTypeSpecBuilder innerBuilder = DeferredTypeSpecBuilder.create(annotationBuilder(substitution.raw())
			.addModifiers(modifiers(element))
			.addAnnotations(mergeAnnotations(copyableAnnotations(element), descriptorAnnotations)));

	element.getEnclosedElements().forEach(child -> visit(child, innerBuilder));

	// If this is a nested type, we now roll up the new type into the parent.
	return (outerBuilder != null)
			? outerBuilder.addDeferred(innerBuilder)
					: innerBuilder;
}
 
Example 18
Project: java-code-templates   File: TemplateSubstitutionVisitor.java   Source Code and License 6 votes vote down vote up
@Override
public DeferredTypeSpecBuilder visitTypeAsEnum(final TypeElement element, final DeferredTypeSpecBuilder outerBuilder) {

	// An Enum must exclude the following implicitly-defined characteristics:
	//  - a 'final' modifier, which causes compiler errors when explicit.
	//  - valueOf() and values() methods.

	final Collection<AnnotationSpec> descriptorAnnotations = descriptorInventory.typeAnnotations(element);
	final TypeSubstitution substitution = applyDeclaredTypeSubstitution(element);
	final DeferredTypeSpecBuilder innerBuilder = DeferredTypeSpecBuilder.create(enumBuilder(substitution.raw())
			.addModifiers(modifiers(element))
			.addAnnotations(mergeAnnotations(copyableAnnotations(element), descriptorAnnotations)));

	element.getInterfaces().forEach(iface -> innerBuilder.wrapped().addSuperinterface(applyTypeSubstitution(iface)));

	// Only traverse enclosed elements that are not implicit enum methods
	element.getEnclosedElements().stream()
		.filter(child -> !isImplicitEnumMethod(child))
		.forEach(child -> visit(child, innerBuilder));

	// If this is a nested type, we now roll up the new type into the parent.
	return (outerBuilder != null)
			? outerBuilder.addDeferred(innerBuilder)
					: innerBuilder;
}
 
Example 19
Project: vue-gwt   File: ComponentInjectedDependenciesBuilder.java   Source Code and License 6 votes vote down vote up
/**
 * Add an injected variable to our component
 * @param element The {@link VariableElement} that was injected
 * @param fieldName The name of the field
 */
private void addInjectedVariable(VariableElement element, String fieldName)
{
    TypeName typeName = resolveVariableTypeName(element, messager);

    // Create field
    FieldSpec.Builder fieldBuilder = FieldSpec.builder(typeName, fieldName, Modifier.PUBLIC);

    // Copy field annotations
    element
        .getAnnotationMirrors()
        .stream()
        .map(AnnotationSpec::get)
        .forEach(fieldBuilder::addAnnotation);

    // If the variable element is a method parameter, it might not have the Inject annotation
    if (!hasInjectAnnotation(element))
        fieldBuilder.addAnnotation(Inject.class);

    // And add field
    componentInjectedDependenciesBuilder.addField(fieldBuilder.build());
}
 
Example 20
Project: StaticGson   File: Annotations.java   Source Code and License 6 votes vote down vote up
public static AnnotationSpec suppressWarnings(String... warnings) {
    AnnotationSpec.Builder builder = AnnotationSpec.builder(SuppressWarnings.class);
    CodeBlock.Builder names = CodeBlock.builder();
    boolean first = true;
    for (String warning : warnings) {
        if (first) {
            names.add("$S", warning);
            first = false;
        } else {
            names.add(", $S", warning);
        }
    }
    if (warnings.length == 1) {
        builder.addMember("value", names.build());
    } else {
        builder.addMember("value", "{$L}", names.build());
    }
    return builder.build();
}
 
Example 21
Project: graylog-plugin-pipeline-processor   File: CodeGenerator.java   Source Code and License 6 votes vote down vote up
@Override
public void enterRule(Rule rule) {
    // generates a new ephemeral unique class name for each generated rule. Only valid for the runtime of the jvm
    classFile = TypeSpec.classBuilder("rule$" + rule.id())
            .addSuperinterface(GeneratedRule.class)
            .addModifiers(Modifier.FINAL, Modifier.PUBLIC)
            .addAnnotation(AnnotationSpec.builder(SuppressWarnings.class)
                    .addMember("value", "$S", "unchecked")
                    .build()
            )
            .addMethod(MethodSpec.methodBuilder("name")
                    .returns(String.class)
                    .addAnnotation(Override.class)
                    .addModifiers(Modifier.PUBLIC)
                    .addStatement("return $S", rule.name())
                    .build()
            );
    constructorBuilder = MethodSpec.constructorBuilder()
            .addModifiers(Modifier.PUBLIC)
            .addParameter(FunctionRegistry.class, "functionRegistry");
    lateConstructorBlock = CodeBlock.builder();
    hoistedConstantExpressions = CodeBlock.builder();
}
 
Example 22
Project: AndroidSupportAnnotationsHaiku   File: RequiresPermission.java   Source Code and License 6 votes vote down vote up
public AnnotationSpec build() {
  AnnotationSpec.Builder builder = SPEC.toBuilder();

  if (value != null) {
    builder.addMember("value", valueFormat, value);
  }

  if (allOf != null && allOf.size() > 0) {
    builder.addMember("allOf", allOfFormat, allOf.toArray());
  }

  if (anyOf != null && anyOf.size() > 0) {
    builder.addMember("anyOf", anyOfFormat, anyOf.toArray());
  }

  if (conditional != null) {
    builder.addMember("conditional", conditionalFormat, conditional);
  }

  return builder.build();
}
 
Example 23
Project: AndroidSupportAnnotationsHaiku   File: Size.java   Source Code and License 6 votes vote down vote up
public AnnotationSpec build() {
  AnnotationSpec.Builder builder = SPEC.toBuilder();

  if (value != null) {
    builder.addMember("value", valueFormat, value);
  }

  if (min != null) {
    builder.addMember("min", minFormat, min);
  }

  if (max != null) {
    builder.addMember("max", maxFormat, max);
  }

  if (multiple != null) {
    builder.addMember("multiple", multipleFormat, multiple);
  }

  return builder.build();
}
 
Example 24
Project: AndroidSupportAnnotationsHaiku   File: FloatRange.java   Source Code and License 6 votes vote down vote up
public AnnotationSpec build() {
  AnnotationSpec.Builder builder = SPEC.toBuilder();

  if (from != null) {
    builder.addMember("from", fromFormat, this.from);
  }

  if (to != null) {
    builder.addMember("to", toFormat, this.to);
  }

  if (fromInclusive != null) {
    builder.addMember("fromInclusive", fromInclusiveFormat, this.fromInclusive);
  }

  if (toInclusive != null) {
    builder.addMember("toInclusive", toInclusiveFormat, this.toInclusive);
  }

  return builder.build();
}
 
Example 25
Project: Mockery   File: BrewJavaFile.java   Source Code and License 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 26
Project: Mockery   File: BrewJavaFile.java   Source Code and License 6 votes vote down vote up
private MethodSpec methodAllParamLegals(ClassName className,
    Method method, int orderTest) {
  String methodName = String
      .format("When_Call_%s_Then_Get_Response", method.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, null, builder);
  response(className, method, false, builder);

  return builder.build();
}
 
Example 27
Project: pojo-updater-compiler   File: ManagerGenerator.java   Source Code and License 6 votes vote down vote up
private MethodSpec generateGetUpdaterMethod(FieldSpec mapField) {
    TypeVariableName typeVariableName = TypeVariableName.get("T");
    ParameterizedTypeName returnType = ParameterizedTypeName.get(ClassName.get(Updater.class), typeVariableName);
    ParameterSpec parameterSpec = ParameterSpec.builder(
            ParameterizedTypeName.get(ClassName.get(Class.class), typeVariableName),
            "tClass"
    ).build();

    final String returnVariableName = "updater";
    return MethodSpec.methodBuilder("getUpdater")
            .addAnnotation(AnnotationSpec.builder(SuppressWarnings.class)
                    .addMember("value", "$S", "unchecked")
                    .build())
            .addModifiers(Modifier.PUBLIC)
            .addTypeVariable(typeVariableName)
            .addParameter(parameterSpec)
            .returns(returnType)
            .addStatement("$T $N = ($T)$N.get($N)", returnType, returnVariableName, returnType, mapField, parameterSpec)
            .beginControlFlow("if ($N == null)", returnVariableName)
            .addStatement("throw new $T(\"Updater for $N not found\")", RuntimeException.class, parameterSpec)
            .endControlFlow()
            .addStatement("return updater")
            .build();
}
 
Example 28
Project: thrifty   File: ThriftyCodeGenerator.java   Source Code and License 6 votes vote down vote up
private AnnotationSpec suppressWarnings(Collection<String> warnings) {
    AnnotationSpec.Builder anno = AnnotationSpec.builder(SuppressWarnings.class);

    if (warnings.isEmpty()) {
        throw new IllegalArgumentException("No warnings present - compiler error?");
    }

    if (warnings.size() == 1) {
        anno.addMember("value", "$S", Iterables.get(warnings, 0));
    } else {
        StringBuilder sb = new StringBuilder("{");
        for (String warning : warnings) {
            sb.append("\"");
            sb.append(warning);
            sb.append("\", ");
        }
        sb.setLength(sb.length() - 2);
        sb.append("}");

        anno.addMember("value", "$L", sb.toString());
    }

    return anno.build();
}
 
Example 29
Project: thrifty   File: ThriftyCodeGenerator.java   Source Code and License 6 votes vote down vote up
private static AnnotationSpec fieldAnnotation(Field field) {
    AnnotationSpec.Builder ann = AnnotationSpec.builder(ThriftField.class)
            .addMember("fieldId", "$L", field.id());

    if (field.required()) {
        ann.addMember("isRequired", "$L", field.required());
    }

    if (field.optional()) {
        ann.addMember("isOptional", "$L", field.optional());
    }

    String typedef = field.typedefName();
    if (!Strings.isNullOrEmpty(typedef)) {
        ann = ann.addMember("typedefName", "$S", typedef);
    }

    return ann.build();
}
 
Example 30
Project: annotated-mvp   File: TriggerType.java   Source Code and License 6 votes vote down vote up
@Override
protected TypeSpec.Builder build()
{
    String params = "{";
    ClassName[] vars = new ClassName[viewElements.size()];
    int i = 0;
    for (Iterator<Element> it = viewElements.iterator(); it.hasNext(); i++)
    {
        Element element = it.next();
        params += "$T.class";
        vars[i] = ClassName.bestGuess(element.asType().toString());
        if (i < viewElements.size() - 1)
        {
            params += ", ";
        }
    }
    params += "}";
    AnnotationSpec.Builder annotationBuilder = AnnotationSpec.builder(Generate.class);
    annotationBuilder.addMember("views", params, (Object[]) vars);
    annotationBuilder.addMember("application", "$T.class", applicationClassName);
    return TypeSpec.classBuilder("Trigger")
            .addModifiers(Modifier.ABSTRACT)
            .addAnnotation(annotationBuilder.build());
}
 
Example 31
Project: tiger   File: NewInjectorGenerator.java   Source Code and License 6 votes vote down vote up
/**
 * Returns {@link #getSourceCodeName}(qualifier) + "__" + {@link #getSourceCodeName} (type), or
 * {@link #getSourceCodeName}(type) if no qualifier.
 */
private String getSourceCodeName(NewBindingKey key) {
  // System.out.println("getMethodName for key: " + key);
  StringBuilder builder = new StringBuilder();
  AnnotationSpec qualifier = key.getQualifier();
  if (qualifier != null) {
    ClassName qualifierType = (ClassName) qualifier.type;
    builder.append(Utils.getSourceCodeName(qualifierType));
    /**
     * TODO(freeman): handle all illegal chars.
     */
    if (Utils.getCanonicalName(qualifierType).equals(Named.class.getCanonicalName())) {
      builder.append("_").append(qualifier.members.get("value").toString().replace("\"", "_")
          .replace("[", "_").replace("]", "_"));
    }
    builder.append("__");
  }
  builder.append(Utils.getSourceCodeName(key.getTypeName()));
  return builder.toString();
}
 
Example 32
Project: JaxRs2Retrofit   File: RetrofitGenerator.java   Source Code and License 6 votes vote down vote up
private AnnotationSpec createContentTypeAnnotation(
		EvaluatingVisitor evaluatingVisitor,
		JavaAnnotation consumesAnnotation) {

	AnnotationValue annotationValue = consumesAnnotation.getProperty("value");
	String stringAnnotationValue = annotationValue.getParameterValue().toString();

	String value = null;
	if (stringAnnotationValue.startsWith(MediaType.class.getSimpleName() + ".")) {
		String[] token = stringAnnotationValue.split("\\.");
		try {
			value = (String) MediaType.class.getDeclaredField(token[1]).get(null);
		} catch (Exception e) {
			e.printStackTrace(System.err);
		}
	} else {
		value = consumesAnnotation.getProperty("value").accept(evaluatingVisitor).toString();
	}

	return AnnotationSpec.builder(Headers.class)
			.addMember("value", "\"Content-type: " + value + "\"")
			.build();
}
 
Example 33
Project: OnActivityResult   File: ActivityResultClass.java   Source Code and License 6 votes vote down vote up
JavaFile brewJava() {
    final TypeSpec.Builder result = TypeSpec.classBuilder(generatedClassName).addModifiers(PUBLIC);
    result.addTypeVariable(TypeVariableName.get(TYPE_VARIABLE_NAME, targetTypeName));

    final TypeVariableName typeVariableName = TypeVariableName.get(TYPE_VARIABLE_NAME);

    if (superActivityResultClass != null) {
        result.superclass(ParameterizedTypeName.get(ClassName.bestGuess(superActivityResultClass), typeVariableName));
    } else {
        result.addSuperinterface(ParameterizedTypeName.get(ACTIVITY_ON_RESULT, typeVariableName));
    }

    result.addMethod(this.createOnResultMethod());

    if (shouldAddGeneratedAnnotation) {
        result.addAnnotation(AnnotationSpec.builder(Generated.class).addMember("value", "$S", OnActivityResultProcessor.class.getCanonicalName()).build());
    }

    return JavaFile.builder(generatedClassName.packageName(), result.build()).skipJavaLangImports(true).addFileComment("Generated code from OnActivityResult. Do not modify!").build();
}
 
Example 34
Project: Akatsuki   File: BuilderIntegrationTestBase.java   Source Code and License 6 votes vote down vote up
protected TestSource createTestSource(AnnotationSpec spec, String packageName,
		Class<?> parentClass, TestField... fields) {
	final HashSet<TestField> set = Sets.newHashSet(fields);
	if (set.size() != fields.length)
		throw new IllegalArgumentException("Duplicate fields are not allowed");

	// mockito explodes if the classes are not public...
	// we use abstract just in case of our superclass is abstract too


	final TestSource source = new TestSource(packageName, generateClassName(), Modifier.PUBLIC,
			Modifier.ABSTRACT).appendFields(set.stream().map(f -> {
		if (!(f instanceof ArgTestField)) {
			f.fieldSpecBuilder().addAnnotation(Arg.class);
		}
		return f.createFieldSpec();
	}).collect(Collectors.toList()));

	if (spec != null)
		source.appendTransformation((b, s) -> b.addAnnotation(spec));
	if (parentClass != null)
		source.appendTransformation((builder, s) -> builder.superclass(parentClass));

	return source;
}
 
Example 35
Project: Knight   File: BaseClassBuilder.java   Source Code and License 6 votes vote down vote up
/**
 * Returns list of all annotations given <code>element</code> has.
 *
 * @param element Element.
 */
public List<AnnotationSpec> getQualifiers(Element element) {
    List<AnnotationSpec> list = new ArrayList<>();
    for (AnnotationMirror a : element.getAnnotationMirrors()) {
        if (a.getAnnotationType().asElement().getAnnotation(Qualifier.class) == null) {
            continue; // ignore non-Qualifier annotations
        }

        ClassName annotationClassName = (ClassName) ClassName.get(a.getAnnotationType());
        AnnotationSpec.Builder annotation = AnnotationSpec.builder(annotationClassName);
        for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : a.getElementValues().entrySet()) {
            String format = (entry.getValue().getValue() instanceof String) ? "$S" : "$L";
            annotation.addMember(entry.getKey().getSimpleName().toString(), format, entry.getValue().getValue());
        }
        list.add(annotation.build());
    }
    return list;
}
 
Example 36
Project: exovert   File: AccessorGenerator.java   Source Code and License 6 votes vote down vote up
private static ParameterSpec getSpec(ColumnMetadata column, boolean addAnnotation) {
    String name = column.getName();
    String paramName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, name);
    ParameterSpec.Builder param;

    if (Udt.instance.isUdt(column.getType())) {
        throw new IllegalArgumentException("We don't currently support UDT primary keys in the query string, field: "
                + column.getName());
    } else {
        param = ParameterSpec.builder(EntityGeneratorHelper.getRawType(column.getType()), paramName);
    }

    if(addAnnotation) {
        param.addAnnotation(AnnotationSpec.builder(Param.class).addMember("value", "$S", name).build());
    }

    return param.addModifiers(Modifier.FINAL).build();
}
 
Example 37
Project: Kinject   File: CodeGen.java   Source Code and License 6 votes vote down vote up
private static void writeClassFile(String packageName, TypeSpec classSpec, Filer filer) throws ProcessorException {
	try {
		AnnotationSpec generatedAnnotation = AnnotationSpec.builder(Generated.class)
			.addMember("value", "$S", CODE_GEN)
			.build();
		classSpec = classSpec.toBuilder()
			.addAnnotation(generatedAnnotation)
			.build();
		JavaFile javaFile = JavaFile.builder(packageName, classSpec)
			.skipJavaLangImports(true)
			.build();
		javaFile.writeTo(filer);
	} catch (IOException e) {
		throw new ProcessorException("Cannot generate code file %s.%s.", packageName, classSpec.name);
	}
}
 
Example 38
Project: anno4j   File: PropertySchemaAnnotationSupport.java   Source Code and License 6 votes vote down vote up
/**
 * Constructs a container annotation of the given type and content.
 * @param containerType The type of the container annotation.
 * @param content The annotations to be contained.
 * @return Returns the container annotation specification.
 */
private static AnnotationSpec buildContainer(Class<?> containerType, Collection<AnnotationSpec> content) {
    // Build content of container annotation as string:
    CodeBlock.Builder inner = CodeBlock.builder().add("{");

    Iterator<AnnotationSpec> contentIterator = content.iterator();
    while (contentIterator.hasNext()) {
        inner.add("$L", contentIterator.next());

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

    return AnnotationSpec.builder(containerType)
                        .addMember("value", inner.build())
                        .build();
}
 
Example 39
Project: poetry   File: PoetryTest.java   Source Code and License 6 votes vote down vote up
@Test
public void createSimpleAnnotationWithTypeSpec() {
  AnnotationSpec spec = Poetry.annotation(AnnotationC.class, "test");
  TypeSpec taco = TypeSpec.classBuilder("Taco")
      .addAnnotation(spec)
      .build();

  assertEquals(toString(taco), ""
      + "package com.squareup.tacos;\n"
      + "\n"
      + "import " + getClass().getCanonicalName() + ";\n"
      + "\n"
      + "@" + getClass().getSimpleName() + ".AnnotationC(\"test\")\n"
      + "class Taco {\n"
      + "}\n");
}
 
Example 40
Project: Android-Orma   File: Annotations.java   Source Code and License 6 votes vote down vote up
public static AnnotationSpec suppressWarnings(String... warnings) {
    AnnotationSpec.Builder builder = AnnotationSpec.builder(SuppressWarnings.class);
    CodeBlock.Builder names = CodeBlock.builder();
    boolean first = true;
    for (String warning : warnings) {
        if (first) {
            names.add("$S", warning);
            first = false;
        } else {
            names.add(", $S", warning);
        }
    }
    if (warnings.length == 1) {
        builder.addMember("value", names.build());
    } else {
        builder.addMember("value", "{$L}", names.build());
    }
    return builder.build();
}
 
Example 41
Project: jackdaw   File: JRepeatableCodeGenerator.java   Source Code and License 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 42
Project: Knight   File: BaseModuleBuilder.java   Source Code and License 6 votes vote down vote up
/**
 * Prepares {@link MethodSpec.Builder} for <code>provides</code> method.
 *
 * @param e              Method or Constructor element that will be called in <code>provides</code> method.
 * @param methodNamePart Name of the <code>provides</code> method that will be formatted.
 * @param scoped         <code>true</code> if <code>provides</code> method will be scoped.
 */
protected MethodSpec.Builder prepareProvidesMethodBuilder(ExecutableElement e, String methodNamePart, boolean scoped) {
    String methodName = createProvideMethodName(methodNamePart);

    MethodSpec.Builder method = MethodSpec.methodBuilder(methodName)
            .addAnnotation(Provides.class)
            .addModifiers(Modifier.PUBLIC);

    if (scoped) {
        method.addAnnotation(mScope);
    }
    // add also Qualifier annotations
    for (AnnotationSpec a : getQualifiers(e)) {
        method.addAnnotation(a);
    }
    return method;
}
 
Example 43
Project: bsoneer   File: BsoneeCodecProviderGenerator.java   Source Code and License 6 votes vote down vote up
public JavaFile getJavaFile() {
	ClassName bsoneerCodecProviderClassName = ClassName.get(basePackage, "BsoneeCodecProvider");

	TypeSpec.Builder codecProviderBuilder = TypeSpec.classBuilder(bsoneerCodecProviderClassName.simpleName())
	        .addJavadoc(ProcessorJavadocs.GENERATED_BY_BSONEER)
	        .addSuperinterface(CodeUtil.bsonCodecProviderTypeName())
	        .addModifiers(PUBLIC).addAnnotation(AnnotationSpec.builder(Generated.class)
	        		.addMember("value", "$S", BsonProcessor.class.getCanonicalName())
	        		.build());;

	addBaseConstructor(codecProviderBuilder);
	addGetCodecMethod(codecProviderBuilder);

	return JavaFile.builder(bsoneerCodecProviderClassName.packageName(), codecProviderBuilder.build())
			.addFileComment(ProcessorJavadocs.GENERATED_BY_BSONEER)
			.indent("\t")
			.build();
}
 
Example 44
Project: Knight   File: BaseComponentBuilder.java   Source Code and License 6 votes vote down vote up
@Override
public void end() throws ProcessorError {
    super.end();

    // set to Scope Scope
    getBuilder().addAnnotation(mScope);

    // add Component Annotation
    StringBuilder modulesFormat = new StringBuilder();
    modulesFormat.append("{").append("\n");
    for (int i = 0; i < mModules.size(); i++) {
        modulesFormat.append("$T.class,").append("\n");
    }
    modulesFormat.append("}");

    getBuilder().addAnnotation(
            AnnotationSpec.builder(getComponentAnnotation())
                    .addMember("modules", modulesFormat.toString(), mModules.toArray())
                    .build()
    );
}
 
Example 45
Project: GitHub   File: RequestManagerGenerator.java   Source Code and License 5 votes vote down vote up
@Nullable
TypeSpec generate(
    String generatedCodePackageName, @Nullable TypeSpec requestOptions, TypeSpec requestBuilder,
    Set<String> glideExtensions) {
  generatedRequestBuilderClassName = ClassName.get(generatedCodePackageName, requestBuilder.name);
  return TypeSpec.classBuilder(GENERATED_REQUEST_MANAGER_SIMPLE_NAME)
       .superclass(requestManagerClassName)
       .addJavadoc("Includes all additions from methods in {@link $T}s\n"
               + "annotated with {@link $T}\n"
               + "\n"
               + "<p>Generated code, do not modify\n",
           GlideExtension.class, GlideType.class)
      .addAnnotation(
          AnnotationSpec.builder(SuppressWarnings.class)
              .addMember("value", "$S", "deprecation")
              .build())
       .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
       .addMethod(generateAsMethod(generatedCodePackageName, requestBuilder))
       .addMethod(generateCallSuperConstructor())
       .addMethods(generateAdditionalRequestManagerMethods(glideExtensions))
       .addMethods(generateRequestManagerMethodOverrides())
       .addMethods(
           FluentIterable.from(
               Collections.singletonList(
                   generateOverrideSetRequestOptions(generatedCodePackageName, requestOptions)))
               .filter(Predicates.<MethodSpec>notNull()))
       .build();
}
 
Example 46
Project: GitHub   File: ActivityDecorator.java   Source Code and License 5 votes vote down vote up
@Override
protected void implementInitializer(MethodSpec.Builder method) {
    int resId = delegateClassGenerator.getResourceID();
    if (resId != -1) {
        //Avoid lint error
        method.addAnnotation(
                AnnotationSpec.builder(SuppressWarnings.class)
                        .addMember("value", "\"ResourceType\"")
                        .build());
        method.addStatement("view.setContentView(" + resId + ")");
    }    }
 
Example 47
Project: GitHub   File: ProcessorUtil.java   Source Code and License 5 votes vote down vote up
private static List<AnnotationSpec> getAnnotations(VariableElement element) {
  List<AnnotationSpec> result = new ArrayList<>();
  for (AnnotationMirror mirror : element.getAnnotationMirrors()) {
    result.add(AnnotationSpec.get(mirror));
  }
  return result;
}
 
Example 48
Project: GitHub   File: RequestManagerGenerator.java   Source Code and License 5 votes vote down vote up
@Nullable
TypeSpec generate(
    String generatedCodePackageName, @Nullable TypeSpec requestOptions, TypeSpec requestBuilder,
    Set<String> glideExtensions) {
  generatedRequestBuilderClassName = ClassName.get(generatedCodePackageName, requestBuilder.name);
  return TypeSpec.classBuilder(GENERATED_REQUEST_MANAGER_SIMPLE_NAME)
       .superclass(requestManagerClassName)
       .addJavadoc("Includes all additions from methods in {@link $T}s\n"
               + "annotated with {@link $T}\n"
               + "\n"
               + "<p>Generated code, do not modify\n",
           GlideExtension.class, GlideType.class)
      .addAnnotation(
          AnnotationSpec.builder(SuppressWarnings.class)
              .addMember("value", "$S", "deprecation")
              .build())
       .addModifiers(Modifier.PUBLIC)
       .addMethod(generateAsMethod(generatedCodePackageName, requestBuilder))
       .addMethod(generateCallSuperConstructor())
       .addMethods(generateExtensionRequestManagerMethods(glideExtensions))
       .addMethods(generateRequestManagerRequestManagerMethodOverrides(generatedCodePackageName))
       .addMethods(generateRequestManagerRequestBuilderMethodOverrides())
       .addMethods(
           FluentIterable.from(
               Collections.singletonList(
                   generateOverrideSetRequestOptions(generatedCodePackageName, requestOptions)))
               .filter(Predicates.<MethodSpec>notNull()))
       .build();
}
 
Example 49
Project: GitHub   File: RequestOptionsGenerator.java   Source Code and License 5 votes vote down vote up
private MethodSpec generateRequestOptionOverride(ExecutableElement methodToOverride) {
  MethodSpec.Builder result = ProcessorUtil.overriding(methodToOverride)
      .returns(glideOptionsName)
      .addModifiers(Modifier.FINAL)
      .addCode(CodeBlock.builder()
          .add("return ($T) super.$N(", glideOptionsName, methodToOverride.getSimpleName())
          .add(FluentIterable.from(methodToOverride.getParameters())
              .transform(new Function<VariableElement, String>() {
                @Override
                public String apply(VariableElement input) {
                  return input.getSimpleName().toString();
                }
              })
              .join(Joiner.on(", ")))
          .add(");\n")
          .build());

  if (methodToOverride.getSimpleName().toString().equals("transforms")) {
    result
        .addAnnotation(SafeVarargs.class)
        .addAnnotation(
            AnnotationSpec.builder(SuppressWarnings.class)
                .addMember("value", "$S", "varargs")
                .build());
  }

  for (AnnotationMirror mirror : methodToOverride.getAnnotationMirrors()) {
    result.addAnnotation(AnnotationSpec.get(mirror));
  }

  return result.build();
}
 
Example 50
Project: GitHub   File: RequestBuilderGenerator.java   Source Code and License 5 votes vote down vote up
/**
 * Overrides the protected downloadOnly method in {@code com.bumptech.glide.RequestBuilder} to
 * return our generated subclass instead.
 */
private MethodSpec generateDownloadOnlyRequestMethod() {
  ParameterizedTypeName generatedRequestBuilderOfFile
      = ParameterizedTypeName.get(generatedRequestBuilderClassName, ClassName.get(File.class));
  return MethodSpec.methodBuilder("getDownloadOnlyRequest")
      .addAnnotation(Override.class)
      .addAnnotation(AnnotationSpec.builder(CHECK_RESULT_CLASS_NAME).build())
      .returns(generatedRequestBuilderOfFile)
      .addModifiers(Modifier.PROTECTED)
      .addStatement("return new $T<>($T.class, $N).apply($N)",
          generatedRequestBuilderClassName, File.class, "this",
          "DOWNLOAD_ONLY_OPTIONS")
      .build();
}
 
Example 51
Project: autoproxy   File: CommonClassGenerator.java   Source Code and License 5 votes vote down vote up
/** Mimic annotations of the method, but exclude @Yield annotation during processing. */
public static void mimicMethodAnnotations(@NonNull final MethodSpec.Builder builder,
                                          @NonNull final Symbol.MethodSymbol ms) throws Exception {
    if (ms.hasAnnotations()) {
        for (final Attribute.Compound am : ms.getAnnotationMirrors()) {
            if (extractClass(am) == AutoProxy.Yield.class) continue;
            if (extractClass(am) == AutoProxy.AfterCall.class) continue;

            final AnnotationSpec.Builder builderAnnotation = mimicAnnotation(am);
            if (null != builderAnnotation) {
                builder.addAnnotation(builderAnnotation.build());
            }
        }
    }
}
 
Example 52
Project: autoproxy   File: CommonClassGenerator.java   Source Code and License 5 votes vote down vote up
/** Compose method parameters that mimic original code. */
@NonNull
public static StringBuilder mimicParameters(@NonNull final MethodSpec.Builder builder,
                                            @NonNull final Symbol.MethodSymbol ms) throws Exception {
    String delimiter = "";
    final StringBuilder arguments = new StringBuilder();

    final com.sun.tools.javac.util.List<Symbol.VarSymbol> parameters = ms.getParameters();

    for (int i = 0, len = parameters.size(); i < len; i++) {
        final Symbol.VarSymbol param = parameters.get(i);

        // mimic parameter of the method: name, type, modifiers
        final TypeName paramType = TypeName.get(param.asType());
        final String parameterName = param.name.toString();
        final ParameterSpec.Builder parameter = ParameterSpec.builder(paramType, parameterName, Modifier.FINAL);

        if (param.hasAnnotations()) {
            // DONE: copy annotations of parameter
            for (final Attribute.Compound am : param.getAnnotationMirrors()) {
                final AnnotationSpec.Builder builderAnnotation = mimicAnnotation(am);

                if (null != builderAnnotation) {
                    parameter.addAnnotation(builderAnnotation.build());
                }
            }
        }

        // support VarArgs if needed
        builder.varargs(ms.isVarArgs() && i == len - 1);
        builder.addParameter(parameter.build());

        // compose parameters list for forwarding
        arguments.append(delimiter).append(parameterName);
        delimiter = ", ";
    }

    return arguments;
}
 
Example 53
Project: autoproxy   File: CommonClassGenerator.java   Source Code and License 5 votes vote down vote up
/** Compose annotation spec from mirror the original code. */
@Nullable
public static AnnotationSpec.Builder mimicAnnotation(@NonNull final Attribute.Compound am) throws Exception {
    final Class<?> clazz;

    try {
        clazz = extractClass(am);
        return AnnotationSpec.builder(clazz);
    } catch (Throwable ignored) {
        // Not all annotations can be extracted, annotations marked as @Retention(SOURCE)
        // cannot be extracted by our code
    }

    return null;
}
 
Example 54
Project: drift   File: JavadocProcessor.java   Source Code and License 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 55
Project: react4j   File: ProcessorUtil.java   Source Code and License 5 votes vote down vote up
static void copyDocumentedAnnotations( @Nonnull final AnnotatedConstruct element,
                                       @Nonnull final MethodSpec.Builder builder )
{
  for ( final AnnotationMirror annotation : element.getAnnotationMirrors() )
  {
    final DeclaredType annotationType = annotation.getAnnotationType();
    if ( !annotationType.toString().startsWith( "react4j.annotations." ) &&
         null != annotationType.asElement().getAnnotation( Documented.class ) )
    {
      builder.addAnnotation( AnnotationSpec.get( annotation ) );
    }
  }
}
 
Example 56
Project: react4j   File: ProcessorUtil.java   Source Code and License 5 votes vote down vote up
static void copyDocumentedAnnotations( @Nonnull final AnnotatedConstruct element,
                                       @Nonnull final ParameterSpec.Builder builder )
{
  for ( final AnnotationMirror annotation : element.getAnnotationMirrors() )
  {
    if ( null != annotation.getAnnotationType().asElement().getAnnotation( Documented.class ) )
    {
      builder.addAnnotation( AnnotationSpec.get( annotation ) );
    }
  }
}
 
Example 57
Project: react4j   File: Generator.java   Source Code and License 5 votes vote down vote up
@Nonnull
private static MethodSpec.Builder buildEventHandlerActionMethod( @Nonnull final EventHandlerDescriptor eventHandler )
{
  final MethodSpec.Builder method =
    MethodSpec.methodBuilder( eventHandler.getMethod().getSimpleName().toString() ).
      returns( TypeName.get( eventHandler.getMethodType().getReturnType() ) );
  ProcessorUtil.copyTypeParameters( eventHandler.getMethodType(), method );
  ProcessorUtil.copyAccessModifiers( eventHandler.getMethod(), method );
  ProcessorUtil.copyDocumentedAnnotations( eventHandler.getMethod(), method );

  final AnnotationSpec.Builder annotation =
    AnnotationSpec.builder( ACTION_CLASSNAME ).
      addMember( "reportParameters", "false" );
  method.addAnnotation( annotation.build() );

  final int paramCount = eventHandler.getMethod().getParameters().size();
  for ( int i = 0; i < paramCount; i++ )
  {
    final TypeMirror paramType = eventHandler.getMethodType().getParameterTypes().get( i );
    final ParameterSpec.Builder parameter =
      ParameterSpec.builder( TypeName.get( paramType ), "arg" + i, Modifier.FINAL );
    ProcessorUtil.copyDocumentedAnnotations( eventHandler.getMethod().getParameters().get( i ), parameter );
    method.addParameter( parameter.build() );
  }
  final String params =
    0 == paramCount ?
    "" :
    IntStream.range( 0, paramCount ).mapToObj( i -> "arg" + i ).collect( Collectors.joining( "," ) );

  final boolean isVoid = eventHandler.getMethodType().getReturnType().getKind() == TypeKind.VOID;

  method.addStatement( ( isVoid ? "" : "return " ) + "super.$N(" + params + ")",
                       eventHandler.getMethod().getSimpleName() );
  return method;
}
 
Example 58
Project: GreenDao-Migrator   File: BaseUtil.java   Source Code and License 5 votes vote down vote up
public static AnnotationSpec getGenerationDetails(Class className) {
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.ENGLISH);
    return AnnotationSpec.builder(Generated.class)
            .addMember("value", "$S", className.getCanonicalName())
            .addMember("date", "$S", dateFormat.format(new Date()))
            .addMember("comments", "$S", "Auto Generated by GreenDAO Migrator. DO NOT EDIT.")
            .build();
}
 
Example 59
Project: json2java4idea   File: MoshiClassBuilder.java   Source Code and License 5 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(Json.class)
                        .addMember("name", "$S", name)
                        .build())
                .build();
    }).collect(Collectors.toList());
}
 
Example 60
Project: json2java4idea   File: SuppressWarningsAnnotationPolicyTest.java   Source Code and License 5 votes vote down vote up
@Test
public void applyShouldAddGeneratedAnnotation() throws Exception {
    // setup
    final TypeSpec.Builder builder = TypeSpec.classBuilder("Test");

    // exercise
    underTest.apply(builder);

    // verify
    assertThat(builder.build())
            .hasName("Test")
            .hasAnnotation(AnnotationSpec.builder(SuppressWarnings.class)
                    .addMember("value", "$S", "all")
                    .build());
}