use of com.squareup.javapoet.ParameterizedTypeName in project tiger by google.
the class Utils method getDependencyInfoByGeneric.
/**
* Return {@link NewDependencyInfo} for the generalized {@link NewBindingKey} for
* the give key. Null if not applicable or not exist.
*/
public static NewDependencyInfo getDependencyInfoByGeneric(SetMultimap<NewBindingKey, NewDependencyInfo> dependencies, NewBindingKey key) {
TypeName typeName = key.getTypeName();
Preconditions.checkArgument(key.getQualifier() == null, String.format("Binding to %s is supposed to be resolved through generic type of %s" + "but has non-null qualifier.", key, typeName));
if (typeName instanceof ParameterizedTypeName) {
ParameterizedTypeName parameterizedTypeName = (ParameterizedTypeName) typeName;
ClassName rawTypeName = parameterizedTypeName.rawType;
NewBindingKey rawKey = NewBindingKey.get(rawTypeName);
if (dependencies.containsKey(rawKey)) {
NewDependencyInfo dependencyInfo = Iterables.getOnlyElement(dependencies.get(rawKey));
TypeName formalTypeName = dependencyInfo.getDependant().getTypeName();
Preconditions.checkState(formalTypeName instanceof ParameterizedTypeName, String.format("Formal type %s is not of type ParameterizedTypeName. Related actual type is %s", formalTypeName, parameterizedTypeName));
Map<TypeVariableName, TypeName> mapTypeVariableToSpecialized = getMapFromTypeVariableToSpecialized(parameterizedTypeName, (ParameterizedTypeName) formalTypeName);
Set<NewBindingKey> specializedDependencies = specializeIfNeeded(dependencyInfo.getDependencies(), mapTypeVariableToSpecialized);
return new NewDependencyInfo(key, specializedDependencies, dependencyInfo.getSourceClassElement(), dependencyInfo.getProvisionMethodElement(), dependencyInfo.getType());
}
}
return null;
}
use of com.squareup.javapoet.ParameterizedTypeName in project tiger by google.
the class Utils method isMap.
/**
* Returns if key is a map with type variables.
*/
public static boolean isMap(NewBindingKey key) {
TypeName typeName = key.getTypeName();
if (!(typeName instanceof ParameterizedTypeName)) {
return false;
}
ParameterizedTypeName parameterizedTypeName = (ParameterizedTypeName) typeName;
return parameterizedTypeName.rawType.equals(ClassName.get(Map.class));
}
use of com.squareup.javapoet.ParameterizedTypeName in project requery by requery.
the class EntityGenerator method generateListeners.
private void generateListeners(MethodSpec.Builder constructor) {
for (Map.Entry<Element, ? extends ListenerDescriptor> entry : entity.listeners().entrySet()) {
for (Annotation annotation : entry.getValue().listenerAnnotations()) {
String annotationName = annotation.annotationType().getSimpleName().replace("Persist", "Insert").replace("Remove", "Delete");
String methodName = Names.lowerCaseFirst(annotationName);
// avoid hardcoding the package name here
Element listener = elements.getTypeElement(PreInsertListener.class.getCanonicalName());
PackageElement packageElement = elements.getPackageOf(listener);
// generate the listener name
String packageName = packageElement.getQualifiedName().toString();
ClassName listenerName = ClassName.get(packageName, annotationName + "Listener");
ParameterizedTypeName getterType = ParameterizedTypeName.get(listenerName, typeName);
TypeSpec.Builder listenerBuilder = TypeSpec.anonymousClassBuilder("").addSuperinterface(getterType).addMethod(CodeGeneration.overridePublicMethod(methodName).addParameter(typeName, "entity").addStatement("$L()", entry.getKey().getSimpleName()).build());
constructor.addStatement("$L.modifyListeners().add$L($L)", PROXY_NAME, annotationName + "Listener", listenerBuilder.build());
}
}
}
use of com.squareup.javapoet.ParameterizedTypeName in project requery by requery.
the class EntityGenerator method generateProxyMethods.
private void generateProxyMethods(TypeSpec.Builder builder) {
// add proxy field
TypeName entityType = entity.isEmbedded() ? nameResolver.typeNameOf(parent) : typeName;
TypeName proxyName = parameterizedTypeName(EntityProxy.class, entityType);
FieldSpec.Builder proxyField = FieldSpec.builder(proxyName, PROXY_NAME, Modifier.PRIVATE, Modifier.FINAL, Modifier.TRANSIENT);
if (!entity.isEmbedded()) {
proxyField.initializer("new $T(this, $L)", proxyName, TYPE_NAME);
}
builder.addField(proxyField.build());
for (AttributeDescriptor attribute : entity.attributes().values()) {
boolean useField = attribute.isTransient() || attribute.isEmbedded();
TypeMirror typeMirror = attribute.typeMirror();
TypeName unboxedTypeName;
if (attribute.isIterable()) {
unboxedTypeName = parameterizedCollectionName(typeMirror);
} else if (attribute.isOptional()) {
unboxedTypeName = TypeName.get(tryFirstTypeArgument(attribute.typeMirror()));
} else if (attribute.isEmbedded()) {
EntityDescriptor embedded = graph.embeddedDescriptorOf(attribute).orElseThrow(IllegalStateException::new);
unboxedTypeName = nameResolver.embeddedTypeNameOf(embedded, entity);
} else {
unboxedTypeName = nameResolver.tryGeneratedTypeName(typeMirror);
}
String attributeName = attribute.fieldName();
String getterName = attribute.getterName();
String fieldName = Names.upperCaseUnderscore(Names.removeMemberPrefixes(attributeName));
if (entity.isEmbedded()) {
fieldName = attributeFieldName(attribute);
}
// getter
MethodSpec.Builder getter = MethodSpec.methodBuilder(getterName).addModifiers(Modifier.PUBLIC).returns(attribute.isOptional() ? TypeName.get(typeMirror) : unboxedTypeName);
if (Mirrors.overridesMethod(types, typeElement, getterName)) {
getter.addAnnotation(Override.class);
}
memberExtensions.forEach(extension -> extension.addToGetter(attribute, getter));
if (useField) {
if (attribute.isEmbedded()) {
// have to cast to embedded type
getter.addStatement("return ($T)this.$L", unboxedTypeName, attributeName);
} else {
getter.addStatement("return this.$L", attributeName);
}
} else if (attribute.isOptional()) {
getter.addStatement("return $T.ofNullable($L.get($L))", Optional.class, PROXY_NAME, fieldName);
} else {
getter.addStatement("return $L.get($L)", PROXY_NAME, fieldName);
}
builder.addMethod(getter.build());
// setter
String setterName = attribute.setterName();
// if read only don't generate a public setter
boolean readOnly = entity.isReadOnly() || attribute.isReadOnly();
// edge case check if it's interface and we need to implement the setter
if (entity.element().getKind().isInterface() && ElementFilter.methodsIn(entity.element().getEnclosedElements()).stream().anyMatch(element -> element.getSimpleName().toString().equals(setterName))) {
readOnly = false;
}
if (!readOnly) {
TypeName setTypeName = unboxedTypeName;
boolean castType = false;
// use wildcard generic collection type if necessary
if (setTypeName instanceof ParameterizedTypeName) {
ParameterizedTypeName parameterizedName = (ParameterizedTypeName) setTypeName;
List<TypeName> arguments = parameterizedName.typeArguments;
List<TypeName> wildcards = new ArrayList<>();
for (TypeName argument : arguments) {
if (!(argument instanceof WildcardTypeName)) {
Elements elements = processingEnv.getElementUtils();
TypeElement element = elements.getTypeElement(argument.toString());
if (element != null && element.getKind() == ElementKind.INTERFACE) {
wildcards.add(WildcardTypeName.subtypeOf(argument));
} else {
wildcards.add(argument);
}
} else {
wildcards.add(argument);
}
}
TypeName[] array = new TypeName[wildcards.size()];
setTypeName = ParameterizedTypeName.get(parameterizedName.rawType, wildcards.toArray(array));
castType = true;
}
String paramName = Names.lowerCaseFirst(Names.removeMemberPrefixes(attributeName));
MethodSpec.Builder setter = MethodSpec.methodBuilder(setterName).addModifiers(Modifier.PUBLIC).addParameter(setTypeName, paramName);
if (useField) {
setter.addStatement("this.$L = $L", attributeName, paramName);
} else {
if (castType) {
setter.addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "$S", "unchecked").build());
setter.addStatement("$L.set($L, ($T)$L)", PROXY_NAME, fieldName, unboxedTypeName, paramName);
} else {
setter.addStatement("$L.set($L, $L)", PROXY_NAME, fieldName, paramName);
}
}
memberExtensions.forEach(extension -> extension.addToSetter(attribute, setter));
PropertyNameStyle style = entity.propertyNameStyle();
if (style == PropertyNameStyle.FLUENT || style == PropertyNameStyle.FLUENT_BEAN) {
setter.addStatement("return this");
setter.returns(typeName);
}
builder.addMethod(setter.build());
}
}
MethodSpec.Builder constructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC);
if (entity.isEmbedded()) {
constructor.addParameter(ParameterSpec.builder(proxyName, "proxy").build());
constructor.addStatement("this.$L = proxy", PROXY_NAME);
entity.attributes().values().stream().filter(attribute -> !attribute.isTransient()).forEach(attribute -> {
ParameterizedTypeName attributeType = ParameterizedTypeName.get(ClassName.get(Attribute.class), nameResolver.typeNameOf(parent), resolveAttributeType(attribute));
constructor.addParameter(ParameterSpec.builder(attributeType, attribute.name()).build());
constructor.addStatement("this.$L = $L", attributeFieldName(attribute), attribute.name());
});
}
generateListeners(constructor);
// initialize the generated embedded entities
entity.attributes().values().stream().filter(AttributeDescriptor::isEmbedded).forEach(attribute -> graph.embeddedDescriptorOf(attribute).ifPresent(embedded -> {
ClassName embeddedName = nameResolver.embeddedTypeNameOf(embedded, entity);
String format = embedded.attributes().values().stream().map(attr -> Names.upperCaseUnderscore(embeddedAttributeName(attribute, attr))).collect(Collectors.joining(", ", "$L = new $T($L, ", ")"));
constructor.addStatement(format, attribute.fieldName(), embeddedName, PROXY_NAME);
}));
builder.addMethod(constructor.build());
}
use of com.squareup.javapoet.ParameterizedTypeName in project requery by requery.
the class EntityGenerator method generateMembers.
private void generateMembers(TypeSpec.Builder builder) {
Modifier visibility = entity.isEmbedded() ? Modifier.PROTECTED : Modifier.PRIVATE;
// generate property states
if (!entity.isStateless()) {
entity.attributes().values().stream().filter(attribute -> !attribute.isTransient()).forEach(attribute -> {
TypeName stateType = ClassName.get(PropertyState.class);
builder.addField(FieldSpec.builder(stateType, propertyStateFieldName(attribute), visibility).build());
});
}
if (entity.isEmbedded() && !(entity.isImmutable() || entity.isUnimplementable())) {
entity.attributes().values().stream().filter(attribute -> !attribute.isTransient()).forEach(attribute -> {
ParameterizedTypeName attributeType = ParameterizedTypeName.get(ClassName.get(Attribute.class), nameResolver.typeNameOf(parent), resolveAttributeType(attribute));
builder.addField(FieldSpec.builder(attributeType, attributeFieldName(attribute), Modifier.PRIVATE, Modifier.FINAL).build());
});
}
// only generate for interfaces or if the entity is immutable but has no builder
boolean generateMembers = typeElement.getKind().isInterface() || !entity.builderType().isPresent();
Set<String> existingFieldNames = entity.attributes().keySet().stream().filter(it -> it.getKind() == ElementKind.FIELD).map(it -> it.getSimpleName().toString()).collect(Collectors.toSet());
if (generateMembers) {
for (Map.Entry<Element, ? extends AttributeDescriptor> entry : entity.attributes().entrySet()) {
Element element = entry.getKey();
AttributeDescriptor attribute = entry.getValue();
if (element.getKind() == ElementKind.METHOD) {
ExecutableElement methodElement = (ExecutableElement) element;
TypeMirror typeMirror = methodElement.getReturnType();
TypeName fieldName;
if (attribute.isIterable()) {
fieldName = parameterizedCollectionName(typeMirror);
} else if (attribute.isOptional()) {
typeMirror = tryFirstTypeArgument(attribute.typeMirror());
fieldName = TypeName.get(typeMirror);
} else {
fieldName = nameResolver.tryGeneratedTypeName(typeMirror);
}
if (entity.isImmutable() || !existingFieldNames.contains(attribute.fieldName())) {
builder.addField(FieldSpec.builder(fieldName, attribute.fieldName(), visibility).build());
}
}
}
}
if (entity.isImmutable()) {
generateBuilder(builder, entity, "builder");
entity.attributes().values().stream().filter(AttributeDescriptor::isEmbedded).forEach(attribute -> graph.embeddedDescriptorOf(attribute).ifPresent(embedded -> embedded.builderType().ifPresent(type -> {
String fieldName = attribute.fieldName() + "Builder";
generateBuilder(builder, embedded, fieldName);
})));
}
}
Aggregations