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(); }
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(); }
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(); }
/** * 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(); }
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(); }
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); } }; }
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(); } }
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(); }
/** * 创建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; }
@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()); }
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(); }
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(); }
/** * 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(); }
/** * 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(); }
@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; }
@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; }
@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; }
@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; }
/** * 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()); }
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(); }
@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(); }
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(); }
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(); }
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(); }
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(); }
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(); }
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(); }
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(); }
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(); }
@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()); }
/** * 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(); }
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(); }
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(); }
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; }
/** * 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; }
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(); }
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); } }
/** * 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(); }
@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"); }