use of com.squareup.javapoet.ParameterizedTypeName in project requery by requery.
the class EntityMetaGenerator method generateAttribute.
private FieldSpec generateAttribute(AttributeDescriptor attribute, AttributeDescriptor parent, TypeName targetName, String fieldName, TypeMirror mirror, boolean expression) {
TypeMirror typeMirror = mirror;
TypeName typeName;
if (attribute.isIterable()) {
typeMirror = tryFirstTypeArgument(typeMirror);
typeName = parameterizedCollectionName(attribute.typeMirror());
} else if (attribute.isOptional()) {
typeMirror = tryFirstTypeArgument(typeMirror);
typeName = TypeName.get(typeMirror);
} else {
typeName = nameResolver.generatedTypeNameOf(typeMirror).orElse(null);
}
if (typeName == null) {
typeName = boxedTypeName(typeMirror);
}
ParameterizedTypeName type;
ClassName attributeType = null;
boolean useKotlinDelegate = false;
if (expression) {
type = parameterizedTypeName(QueryExpression.class, typeName);
} else {
// if it's an association don't make it available as a query attribute
boolean isQueryable = attribute.cardinality() == null || attribute.isForeignKey();
Class<?> attributeClass = isQueryable ? QueryAttribute.class : Attribute.class;
attributeType = ClassName.get(attributeClass);
if (isQueryable) {
TypeElement delegateType = elements.getTypeElement(KOTLIN_ATTRIBUTE_DELEGATE);
if (delegateType != null) {
attributeType = ClassName.get(delegateType);
useKotlinDelegate = true;
}
}
type = ParameterizedTypeName.get(attributeType, targetName, typeName);
}
CodeBlock.Builder builder = CodeBlock.builder();
String attributeName = attribute.name();
if (parent != null && parent.isEmbedded()) {
attributeName = embeddedAttributeName(parent, attribute);
}
if (attribute.isIterable()) {
typeMirror = tryFirstTypeArgument(typeMirror);
TypeName name = nameResolver.tryGeneratedTypeName(typeMirror);
TypeElement collection = (TypeElement) types.asElement(attribute.typeMirror());
ParameterizedTypeName builderName = parameterizedTypeName(attribute.builderClass(), targetName, typeName, name);
builder.add("\nnew $T($S, $T.class, $T.class)\n", builderName, attributeName, ClassName.get(collection), name);
} else if (attribute.isMap() && attribute.cardinality() != null) {
List<TypeMirror> parameters = Mirrors.listGenericTypeArguments(typeMirror);
// key type
TypeName keyName = TypeName.get(parameters.get(0));
// value type
typeMirror = parameters.get(1);
TypeName valueName = nameResolver.tryGeneratedTypeName(typeMirror);
TypeElement valueElement = (TypeElement) types.asElement(attribute.typeMirror());
ParameterizedTypeName builderName = parameterizedTypeName(attribute.builderClass(), targetName, typeName, keyName, valueName);
builder.add("\nnew $T($S, $T.class, $T.class, $T.class)\n", builderName, attributeName, ClassName.get(valueElement), keyName, valueName);
} else {
ParameterizedTypeName builderName = parameterizedTypeName(attribute.builderClass(), targetName, typeName);
TypeName classType = typeName;
if (typeMirror.getKind().isPrimitive()) {
// if primitive just use the primitive class not the boxed version
classType = TypeName.get(typeMirror);
}
String statement;
if (Mirrors.listGenericTypeArguments(typeMirror).size() > 0) {
// use the erased type and cast to class
classType = TypeName.get(types.erasure(typeMirror));
statement = "\nnew $T($S, (Class)$T.class)\n";
} else {
statement = "\nnew $T($S, $T.class)\n";
}
builder.add(statement, builderName, attributeName, classType);
}
if (!expression) {
generateProperties(attribute, parent, typeMirror, targetName, typeName, builder);
}
// attribute builder properties
if (attribute.isKey()) {
builder.add(".setKey(true)\n");
}
builder.add(".setGenerated($L)\n", attribute.isGenerated());
builder.add(".setLazy($L)\n", attribute.isLazy());
builder.add(".setNullable($L)\n", attribute.isNullable());
builder.add(".setUnique($L)\n", attribute.isUnique());
if (!Names.isEmpty(attribute.defaultValue())) {
builder.add(".setDefaultValue($S)\n", attribute.defaultValue());
}
if (!Names.isEmpty(attribute.collate())) {
builder.add(".setCollate($S)\n", attribute.collate());
}
if (attribute.columnLength() != null) {
builder.add(".setLength($L)\n", attribute.columnLength());
}
if (!Names.isEmpty(attribute.definition())) {
builder.add(".setDefinition($S)\n", attribute.definition());
}
if (attribute.isVersion()) {
builder.add(".setVersion($L)\n", attribute.isVersion());
}
if (attribute.converterName() != null) {
builder.add(".setConverter(new $L())\n", attribute.converterName());
}
if (attribute.isForeignKey()) {
builder.add(".setForeignKey($L)\n", attribute.isForeignKey());
Optional<EntityDescriptor> referencedType = graph.referencingEntity(attribute);
referencedType.ifPresent(referenced -> {
builder.add(".setReferencedClass($T.class)\n", referenced.isImmutable() ? TypeName.get(referenced.element().asType()) : nameResolver.typeNameOf(referenced));
graph.referencingAttribute(attribute, referenced).ifPresent(referencedAttribute -> {
String name = upperCaseUnderscoreRemovePrefixes(referencedAttribute.fieldName());
TypeSpec provider = CodeGeneration.createAnonymousSupplier(ClassName.get(Attribute.class), CodeBlock.builder().addStatement("return $T.$L", nameResolver.typeNameOf(referenced), name).build());
builder.add(".setReferencedAttribute($L)\n", provider);
});
});
}
if (attribute.isIndexed()) {
builder.add(".setIndexed($L)\n", attribute.isIndexed());
if (!attribute.indexNames().isEmpty()) {
StringJoiner joiner = new StringJoiner(",");
attribute.indexNames().forEach(name -> joiner.add("$S"));
builder.add(".setIndexNames(" + joiner + ")\n", attribute.indexNames().toArray());
}
}
if (attribute.deleteAction() != null) {
builder.add(".setDeleteAction($T.$L)\n", ClassName.get(ReferentialAction.class), attribute.deleteAction());
}
if (attribute.updateAction() != null) {
builder.add(".setUpdateAction($T.$L)\n", ClassName.get(ReferentialAction.class), attribute.updateAction());
}
if (!attribute.cascadeActions().isEmpty()) {
StringJoiner joiner = new StringJoiner(",");
attribute.cascadeActions().forEach(action -> joiner.add("$T.$L"));
int index = 0;
ClassName cascadeClass = ClassName.get(CascadeAction.class);
Object[] args = new Object[attribute.cascadeActions().size() * 2];
for (CascadeAction action : attribute.cascadeActions()) {
args[index++] = cascadeClass;
args[index++] = action;
}
builder.add(".setCascadeAction(" + joiner + ")\n", args);
}
if (attribute.cardinality() != null) {
if (!expression) {
builder.add(".setCardinality($T.$L)\n", ClassName.get(Cardinality.class), attribute.cardinality());
}
graph.referencingEntity(attribute).ifPresent(referenced -> {
Set<AttributeDescriptor> mappings = graph.mappedAttributes(entity, attribute, referenced);
if (attribute.cardinality() == Cardinality.MANY_TO_MANY) {
generateJunctionType(attribute, referenced, mappings).ifPresent(name -> builder.add(".setReferencedClass($T.class)\n", name));
}
if (mappings.size() == 1) {
AttributeDescriptor mapped = mappings.iterator().next();
String staticMemberName = upperCaseUnderscoreRemovePrefixes(mapped.fieldName());
TypeSpec provider = CodeGeneration.createAnonymousSupplier(ClassName.get(Attribute.class), CodeBlock.builder().addStatement("return $T.$L", nameResolver.typeNameOf(referenced), staticMemberName).build());
builder.add(".setMappedAttribute($L)\n", provider);
}
if (attribute.orderBy() != null) {
referenced.attributes().values().stream().filter(entry -> entry.name().equals(attribute.orderBy())).findFirst().ifPresent(orderBy -> {
String staticMemberName = upperCaseUnderscoreRemovePrefixes(orderBy.fieldName());
TypeSpec provider = CodeGeneration.createAnonymousSupplier(ClassName.get(Attribute.class), CodeBlock.builder().addStatement("return $T.$L", nameResolver.typeNameOf(referenced), staticMemberName).build());
builder.add(".setOrderByAttribute($L)\n", provider);
builder.add(".setOrderByDirection($T.$L)\n", ClassName.get(Order.class), attribute.orderByDirection());
});
}
});
}
builder.add(".build()");
FieldSpec.Builder field = FieldSpec.builder(type, fieldName, Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL);
if (useKotlinDelegate) {
return field.initializer("new $T($L)", attributeType, builder.build()).build();
} else {
return field.initializer("$L", builder.build()).build();
}
}
use of com.squareup.javapoet.ParameterizedTypeName in project requery by requery.
the class EntityMetaGenerator method generateProperties.
private void generateProperties(AttributeDescriptor attribute, AttributeDescriptor parent, TypeMirror typeMirror, TypeName targetName, TypeName attributeName, CodeBlock.Builder block) {
String prefix = "";
if (parent != null) {
prefix = parent.getterName() + "().";
}
// boxed get/set using Objects
Class propertyClass = propertyClassFor(typeMirror);
ParameterizedTypeName propertyType = propertyName(propertyClass, targetName, attributeName);
TypeSpec.Builder builder = TypeSpec.anonymousClassBuilder("").addSuperinterface(propertyType);
boolean isNullable = typeMirror.getKind().isPrimitive() && attribute.isNullable();
boolean useGetter = entity.isUnimplementable() || entity.isImmutable();
boolean useSetter = entity.isUnimplementable();
String getName = prefix + (useGetter ? attribute.getterName() : attribute.fieldName());
String setName = prefix + (useSetter ? attribute.setterName() : attribute.fieldName());
new GeneratedProperty(getName, setName, targetName, attributeName).setNullable(isNullable).setReadOnly(entity.isImmutable()).setUseMethod(useGetter).build(builder);
// additional primitive get/set if the type is primitive
if (propertyClass != Property.class) {
TypeName primitiveType = TypeName.get(attribute.typeMirror());
String name = Names.upperCaseFirst(attribute.typeMirror().toString());
new GeneratedProperty(getName, setName, targetName, primitiveType).setMethodSuffix(name).setReadOnly(entity.isImmutable()).setUseMethod(useGetter).build(builder);
}
block.add(".setProperty($L)\n", builder.build());
block.add(".setPropertyName($S)\n", attribute.element().getSimpleName());
// property state get/set
if (!entity.isStateless()) {
ClassName stateClass = ClassName.get(PropertyState.class);
TypeSpec.Builder stateType = TypeSpec.anonymousClassBuilder("").addSuperinterface(parameterizedTypeName(Property.class, targetName, stateClass));
String fieldName = prefix + propertyStateFieldName(attribute);
new GeneratedProperty(fieldName, targetName, stateClass).build(stateType);
block.add(".setPropertyState($L)\n", stateType.build());
}
if (!entity.isImmutable()) {
return;
}
// if immutable add setter for the builder
String propertyName = attribute.fieldName();
TypeName builderName = typeName;
useSetter = false;
String parameterSuffix = null;
Optional<TypeMirror> builderType = entity.builderType();
if (builderType.isPresent()) {
parameterSuffix = ".builder";
if (parent != null) {
parameterSuffix = "." + parent.fieldName() + "Builder";
}
propertyName = attribute.setterName();
useSetter = true;
TypeElement element = elements.getTypeElement(builderType.get().toString());
if (element != null) {
for (ExecutableElement method : ElementFilter.methodsIn(element.getEnclosedElements())) {
List<? extends VariableElement> parameters = method.getParameters();
String name = Names.removeMethodPrefixes(method.getSimpleName());
// (some builders have with<Property> setters so strip that
if ((Names.matchesSetter("with", name)) || name.equalsIgnoreCase(attribute.fieldName()) && parameters.size() == 1) {
propertyName = method.getSimpleName().toString();
break;
} else if (Names.matchesSetter("set", name) || name.equalsIgnoreCase(attribute.fieldName()) && parameters.size() == 1) {
propertyName = method.getSimpleName().toString();
break;
}
}
} else {
// prefixed, prefix boolean types with is
if (ImmutableAnnotationKind.IMMUTABLE.isPresent(entity.element())) {
propertyName = attribute.fieldName();
String getterName = attribute.getterName().replaceFirst("get", "");
if (attribute.typeMirror().getKind() == TypeKind.BOOLEAN) {
propertyName = "is" + Names.upperCaseFirst(propertyName);
} else if (Names.isAllUpper(getterName)) {
propertyName = Names.lowerCaseFirst(getterName);
}
}
}
}
propertyType = propertyName(propertyClass, builderName, attributeName);
TypeSpec.Builder builderProperty = TypeSpec.anonymousClassBuilder("").addSuperinterface(propertyType);
new GeneratedProperty(propertyName, builderName, attributeName).setWriteOnly(true).setUseMethod(useSetter).setAccessSuffix(parameterSuffix).build(builderProperty);
if (propertyClass != Property.class) {
TypeName primitiveType = TypeName.get(attribute.typeMirror());
String name = Names.upperCaseFirst(attribute.typeMirror().toString());
new GeneratedProperty(propertyName, builderName, primitiveType).setMethodSuffix(name).setAccessSuffix(parameterSuffix).setUseMethod(useSetter).setWriteOnly(true).build(builderProperty);
}
block.add(".setBuilderProperty($L)\n", builderProperty.build());
}
use of com.squareup.javapoet.ParameterizedTypeName in project ARouter by alibaba.
the class InterceptorProcessor method parseInterceptors.
/**
* Parse tollgate.
*
* @param elements elements of tollgate.
*/
private void parseInterceptors(Set<? extends Element> elements) throws IOException {
if (CollectionUtils.isNotEmpty(elements)) {
logger.info(">>> Found interceptors, size is " + elements.size() + " <<<");
// Verify and cache, sort incidentally.
for (Element element : elements) {
if (verify(element)) {
// Check the interceptor meta
logger.info("A interceptor verify over, its " + element.asType());
Interceptor interceptor = element.getAnnotation(Interceptor.class);
Element lastInterceptor = interceptors.get(interceptor.priority());
if (null != lastInterceptor) {
// Added, throw exceptions
throw new IllegalArgumentException(String.format(Locale.getDefault(), "More than one interceptors use same priority [%d], They are [%s] and [%s].", interceptor.priority(), lastInterceptor.getSimpleName(), element.getSimpleName()));
}
interceptors.put(interceptor.priority(), element);
} else {
logger.error("A interceptor verify failed, its " + element.asType());
}
}
// Interface of ARouter.
TypeElement type_ITollgate = elementUtil.getTypeElement(IINTERCEPTOR);
TypeElement type_ITollgateGroup = elementUtil.getTypeElement(IINTERCEPTOR_GROUP);
/**
* Build input type, format as :
*
* ```Map<Integer, Class<? extends ITollgate>>```
*/
ParameterizedTypeName inputMapTypeOfTollgate = ParameterizedTypeName.get(ClassName.get(Map.class), ClassName.get(Integer.class), ParameterizedTypeName.get(ClassName.get(Class.class), WildcardTypeName.subtypeOf(ClassName.get(type_ITollgate))));
// Build input param name.
ParameterSpec tollgateParamSpec = ParameterSpec.builder(inputMapTypeOfTollgate, "interceptors").build();
// Build method : 'loadInto'
MethodSpec.Builder loadIntoMethodOfTollgateBuilder = MethodSpec.methodBuilder(METHOD_LOAD_INTO).addAnnotation(Override.class).addModifiers(PUBLIC).addParameter(tollgateParamSpec);
// Generate
if (null != interceptors && interceptors.size() > 0) {
// Build method body
for (Map.Entry<Integer, Element> entry : interceptors.entrySet()) {
loadIntoMethodOfTollgateBuilder.addStatement("interceptors.put(" + entry.getKey() + ", $T.class)", ClassName.get((TypeElement) entry.getValue()));
}
}
// Write to disk(Write file even interceptors is empty.)
JavaFile.builder(PACKAGE_OF_GENERATE_FILE, TypeSpec.classBuilder(NAME_OF_INTERCEPTOR + SEPARATOR + moduleName).addModifiers(PUBLIC).addJavadoc(WARNING_TIPS).addMethod(loadIntoMethodOfTollgateBuilder.build()).addSuperinterface(ClassName.get(type_ITollgateGroup)).build()).build().writeTo(mFiler);
logger.info(">>> Interceptor group write over. <<<");
}
}
use of com.squareup.javapoet.ParameterizedTypeName in project RxCache by VictorAlbertos.
the class BrewJavaFile method getActionProvider.
private MethodSpec getActionProvider(ClassName providersClassName, ProvidersClass.Method method) {
String methodName = method.name;
TypeName list = ClassName.get(method.enclosingTypeObservable);
TypeName enclosingTypeList = ClassName.get(method.enclosingTypeObservable.getTypeArguments().get(0));
String enclosingTypeListName = enclosingTypeList.toString();
ParameterizedTypeName action = ParameterizedTypeName.get(ClassName.get(ActionsList.class), enclosingTypeList);
ParameterizedTypeName evict = ParameterizedTypeName.get(ClassName.get(ActionsList.Evict.class), enclosingTypeList);
ParameterizedTypeName arrayList = ParameterizedTypeName.get(ClassName.get(ArrayList.class), enclosingTypeList);
ParameterizedTypeName observable = ParameterizedTypeName.get(ClassName.get(Observable.class), list);
ParameterSpec rxProvidersInstance = ParameterSpec.builder(providersClassName, "proxy").addModifiers(Modifier.FINAL).build();
MethodSpec.Builder builder = MethodSpec.methodBuilder(methodName).addModifiers(Modifier.PUBLIC, Modifier.STATIC).addParameter(rxProvidersInstance).returns(action);
if (method.hasDynamicKey) {
builder.addParameter(DynamicKey.class, "dynamicKey", Modifier.FINAL);
} else if (method.hasDynamicKeyGroup) {
builder.addParameter(DynamicKeyGroup.class, "dynamicKeyGroup", Modifier.FINAL);
}
builder.beginControlFlow("$T evict = new $T()", evict, evict).beginControlFlow("@Override public $T call($T elements)", observable, observable);
if (method.hasDynamicKey) {
setReturnEvictForEvictDynamicKey(builder, methodName);
} else if (method.hasDynamicKeyGroup) {
setReturnEvictForEvictDynamicKeyGroup(builder, methodName);
} else {
setReturnEvictForEvictProvider(builder, methodName);
}
builder.endControlFlow().endControlFlow(";");
if (method.hasDynamicKey) {
setCacheForEvictDynamicKey(builder, observable, arrayList, methodName, enclosingTypeListName);
} else if (method.hasDynamicKeyGroup) {
setCacheForEvictDynamicKeyGroup(builder, observable, arrayList, methodName, enclosingTypeListName);
} else {
setCacheForEvictProvider(builder, observable, arrayList, methodName, enclosingTypeListName);
}
builder.addStatement("return ActionsList.with(evict, oCache)");
return builder.build();
}
use of com.squareup.javapoet.ParameterizedTypeName in project butterknife by JakeWharton.
the class FieldCollectionViewBinding method render.
CodeBlock render() {
CodeBlock.Builder builder = CodeBlock.builder().add("target.$L = $T.$L(", name, UTILS, kind.factoryName);
for (int i = 0; i < ids.size(); i++) {
if (i > 0) {
builder.add(", ");
}
builder.add("\n");
boolean requiresCast = requiresCast(type);
if (!requiresCast && !required) {
builder.add("source.findViewById($L)", ids.get(i).code);
} else {
builder.add("$T.find", UTILS);
builder.add(required ? "RequiredView" : "OptionalView");
if (requiresCast) {
builder.add("AsType");
}
builder.add("(source, $L, \"field '$L'\"", ids.get(i).code, name);
if (requiresCast) {
TypeName rawType = type;
if (rawType instanceof ParameterizedTypeName) {
rawType = ((ParameterizedTypeName) rawType).rawType;
}
builder.add(", $T.class", rawType);
}
builder.add(")");
}
}
return builder.add(")").build();
}
Aggregations