use of com.abubusoft.kripton.processor.sqlite.model.SQLiteModelMethod in project kripton by xcesco.
the class BindDaoBuilder method visit.
@Override
public void visit(SQLiteDaoDefinition value) throws Exception {
currentDaoDefinition = value;
// check if we need to generate or not
if (value.getElement().getAnnotation(BindDaoMany2Many.class) != null && value.getElement().getAnnotation(BindGeneratedDao.class) == null) {
return;
}
String classTableName = daoName(value);
PackageElement pkg = elementUtils.getPackageOf(value.getElement());
String packageName = pkg.isUnnamed() ? "" : pkg.getQualifiedName().toString();
AnnotationProcessorUtilis.infoOnGeneratedClasses(BindDao.class, packageName, classTableName);
builder = TypeSpec.classBuilder(classTableName).superclass(Dao.class).addSuperinterface(typeName(value.getElement())).addModifiers(Modifier.PUBLIC);
for (TypeName item : value.implementedInterface) {
builder.addSuperinterface(item);
}
BindTypeContext context = new BindTypeContext(builder, TypeUtility.typeName(packageName, classTableName), Modifier.PRIVATE);
String entityName = BindDataSourceSubProcessor.generateEntityName(value, value.getEntity());
// javadoc for class
builder.addJavadoc("<p>");
builder.addJavadoc("\nDAO implementation for entity <code>$L</code>, based on interface <code>$L</code>\n", entityName, value.getElement().getSimpleName().toString());
builder.addJavadoc("</p>\n\n");
JavadocUtility.generateJavadocGeneratedBy(builder);
builder.addJavadoc(" @see $T\n", TypeUtility.className(value.getEntityClassName()));
builder.addJavadoc(" @see $T\n", TypeUtility.className(value.getElement().getQualifiedName().toString()));
builder.addJavadoc(" @see $T\n", BindTableGenerator.tableClassName(value, value.getEntity()));
{
// constructor
MethodSpec.Builder methodBuilder = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addParameter(SQLContext.class, "context");
methodBuilder.addStatement("super(context)");
builder.addMethod(methodBuilder.build());
}
// define column typeName set
for (SQLiteModelMethod item : value.getCollection()) {
item.accept(this);
}
// generate live data support methods
if (value.hasLiveData()) {
// method sendEvent
{
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(METHOD_NAME_REGISTRY_EVENT).addModifiers(Modifier.PROTECTED).addParameter(Integer.TYPE, "affectedRows");
methodBuilder.beginControlFlow("if (affectedRows==0)");
methodBuilder.addStatement("return");
methodBuilder.endControlFlow();
methodBuilder.beginControlFlow("if (_context.isInSession())");
methodBuilder.addStatement("_context.registrySQLEvent($T.$L)", BindDataSourceBuilder.generateDataSourceName(value.getParent()), value.daoUidName);
methodBuilder.nextControlFlow("else");
methodBuilder.addStatement("invalidateLiveData()");
methodBuilder.endControlFlow();
builder.addMethod(methodBuilder.build());
}
// field liveDatas
{
FieldSpec.Builder liveDataBuilder = FieldSpec.builder(ParameterizedTypeName.get(ClassName.get(Collection.class), ParameterizedTypeName.get(ClassName.get(WeakReference.class), ParameterizedTypeName.get(ClassName.get(KriptonComputableLiveData.class), WildcardTypeName.subtypeOf(Object.class)))), "liveDatas").addModifiers(Modifier.STATIC).initializer(CodeBlock.builder().add("$T.synchronizedCollection(new $T())", Collections.class, ParameterizedTypeName.get(ClassName.get(HashSet.class), ParameterizedTypeName.get(ClassName.get(WeakReference.class), ParameterizedTypeName.get(ClassName.get(KriptonComputableLiveData.class), WildcardTypeName.subtypeOf(Object.class))))).build());
builder.addField(liveDataBuilder.build());
}
// registryLiveData
{
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(METHOD_NAME_REGISTRY_LIVE_DATA).addModifiers(Modifier.PROTECTED).addParameter(ParameterizedTypeName.get(ClassName.get(KriptonComputableLiveData.class), WildcardTypeName.subtypeOf(Object.class)), "value");
methodBuilder.addStatement("liveDatas.add(new $T(value))", ParameterizedTypeName.get(ClassName.get(WeakReference.class), ParameterizedTypeName.get(ClassName.get(KriptonComputableLiveData.class), WildcardTypeName.subtypeOf(Object.class))));
builder.addMethod(methodBuilder.build());
}
// invalidateLiveData
{
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(METHOD_NAME_INVALIDATE_LIVE_DATA).addModifiers(Modifier.PROTECTED);
methodBuilder.beginControlFlow("for ($T item: liveDatas)", ParameterizedTypeName.get(ClassName.get(WeakReference.class), ParameterizedTypeName.get(ClassName.get(KriptonComputableLiveData.class), WildcardTypeName.subtypeOf(Object.class))));
methodBuilder.beginControlFlow("if (item.get()!=null)");
methodBuilder.addStatement("item.get().invalidate()");
methodBuilder.endControlFlow();
methodBuilder.endControlFlow();
builder.addMethod(methodBuilder.build());
}
}
// generate serializer params
for (Entry<TypeName, String> item : currentDaoDefinition.managedParams.entrySet()) {
ManagedPropertyPersistenceHelper.generateParamSerializer(context, item.getValue(), item.getKey(), PersistType.BYTE);
ManagedPropertyPersistenceHelper.generateParamParser(context, item.getValue(), item.getKey(), PersistType.BYTE);
}
// generate subject
if (currentDaoDefinition.getParent().generateRx) {
ParameterizedTypeName subjectTypeName = ParameterizedTypeName.get(ClassName.get(PublishSubject.class), ClassName.get(SQLiteEvent.class));
// subject
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("subject").addModifiers(Modifier.PUBLIC);
methodBuilder.addStatement("return subject").returns(subjectTypeName);
builder.addMethod(methodBuilder.build());
// subject instance
FieldSpec.Builder fieldBuilder = FieldSpec.builder(subjectTypeName, "subject", Modifier.PRIVATE, Modifier.FINAL, Modifier.STATIC).initializer("$T.create()", ClassName.get(PublishSubject.class));
builder.addField(fieldBuilder.build());
}
// generate prepared statement cleaner
{
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("clearCompiledStatements").addModifiers(Modifier.PUBLIC, Modifier.STATIC).returns(Void.TYPE);
for (String item : value.preparedStatementNames) {
methodBuilder.beginControlFlow("if ($L!=null)", item);
methodBuilder.addStatement("$L.close()", item);
methodBuilder.addStatement("$L=null", item);
methodBuilder.endControlFlow();
}
builder.addMethod(methodBuilder.build());
}
TypeSpec typeSpec = builder.build();
JavaWriterHelper.writeJava2File(filer, packageName, typeSpec);
}
use of com.abubusoft.kripton.processor.sqlite.model.SQLiteModelMethod in project kripton by xcesco.
the class BindDataSourceSubProcessor method fillMethods.
/**
* @param currentDaoDefinition
* @param daoElement
*/
private void fillMethods(final SQLiteDaoDefinition currentDaoDefinition, Element daoElement) {
// create method for dao
SqlBuilderHelper.forEachMethods((TypeElement) daoElement, new MethodFoundListener() {
@Override
public void onMethod(ExecutableElement element) {
if (excludedMethods.contains(element.getSimpleName().toString()))
return;
final List<ModelAnnotation> annotationList = new ArrayList<>();
// optional annotations
final List<ModelAnnotation> supportAnnotationList = new ArrayList<>();
AnnotationUtility.forEachAnnotations(element, new AnnotationFoundListener() {
@Override
public void onAcceptAnnotation(Element element, String annotationClassName, Map<String, String> attributes) {
if (// @formatter:off
annotationClassName.equals(BindSqlInsert.class.getCanonicalName()) || annotationClassName.equals(BindSqlUpdate.class.getCanonicalName()) || annotationClassName.equals(BindSqlDelete.class.getCanonicalName()) || annotationClassName.equals(BindSqlSelect.class.getCanonicalName()) || annotationClassName.equals(BindContentProviderEntry.class.getCanonicalName())) // @formatter:on
{
ModelAnnotation annotation = new ModelAnnotation(annotationClassName, attributes);
annotationList.add(annotation);
}
// we don't insert annotation
}
});
// AssertKripton. assertTrue(annotationList.size()==1, "Dao
// definition '%s' has method '%s' that is not correctly
// annotated", currentDaoDefinition.getName(),
// element.getSimpleName());
annotationList.addAll(supportAnnotationList);
final SQLiteModelMethod currentMethod = new SQLiteModelMethod(currentDaoDefinition, element, annotationList);
addWithCheckMethod(currentDaoDefinition, currentMethod);
}
private void addWithCheckMethod(SQLiteDaoDefinition currentDaoDefinition, SQLiteModelMethod newMethod) {
SQLiteModelMethod oldMethod = currentDaoDefinition.findPropertyByName(newMethod.getName());
// ASSERT: same name and same number
if (oldMethod != null && oldMethod.getParameters().size() == newMethod.getParameters().size()) {
boolean sameParameters = true;
for (int i = 0; i < oldMethod.getParameters().size(); i++) {
if (!oldMethod.getParameters().get(i).value1.equals(newMethod.getParameters().get(i).value1)) {
sameParameters = false;
break;
}
}
AssertKripton.failWithInvalidMethodSignException(sameParameters, newMethod, "conflict between generated method and declared method.");
}
// add method
currentDaoDefinition.add(newMethod);
}
});
}
use of com.abubusoft.kripton.processor.sqlite.model.SQLiteModelMethod in project kripton by xcesco.
the class BindContentProviderBuilder method generateQuery.
private void generateQuery(SQLiteDatabaseSchema schema) {
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("query").addModifiers(Modifier.PUBLIC).addAnnotation(Override.class).returns(Cursor.class);
methodBuilder.addParameter(Uri.class, "uri");
methodBuilder.addParameter(ParameterSpec.builder(TypeUtility.arrayTypeName(String.class), "projection").build());
methodBuilder.addParameter(String.class, "selection");
methodBuilder.addParameter(ParameterSpec.builder(TypeUtility.arrayTypeName(String.class), "selectionArgs").build());
methodBuilder.addParameter(String.class, "sortOrder");
boolean hasOperation = hasOperationOfType(schema, methodBuilder, JQLType.SELECT);
if (!hasOperation) {
methodBuilder.addStatement("throw new $T(\"Unknown URI for $L operation: \" + uri)", IllegalArgumentException.class, JQLType.SELECT);
classBuilder.addMethod(methodBuilder.build());
return;
}
methodBuilder.addStatement("$T returnCursor=null", Cursor.class);
for (SQLiteDaoDefinition daoDefinition : schema.getCollection()) {
for (SQLiteModelMethod daoMethod : daoDefinition.getCollection()) {
if (daoMethod.jql.operationType != JQLType.SELECT)
continue;
// methodBuilder.addJavadoc("method $L.$L\n",
// daoDefinition.getName(), daoMethod.getName());
}
}
defineJavadocHeaderForContentOperation(methodBuilder, "query");
methodBuilder.beginControlFlow("switch (sURIMatcher.match(uri))");
for (Entry<String, ContentEntry> item : uriSet.entrySet()) {
if (item.getValue().select == null)
continue;
defineJavadocForContentUri(methodBuilder, item.getValue().select);
// methodBuilder.addJavadoc("uri $L\n", item.getKey());
methodBuilder.beginControlFlow("case $L:", item.getValue().pathIndex);
methodBuilder.addCode("// URI: $L\n", item.getValue().select.contentProviderUri());
methodBuilder.addStatement("returnCursor=dataSource.get$L().$L(uri, projection, selection, selectionArgs, sortOrder)", item.getValue().select.getParent().getName(), item.getValue().select.contentProviderMethodName);
methodBuilder.addStatement("break");
methodBuilder.endControlFlow();
}
methodBuilder.beginControlFlow("default:");
methodBuilder.addStatement("throw new $T(\"Unknown URI for $L operation: \" + uri)", IllegalArgumentException.class, JQLType.SELECT);
methodBuilder.endControlFlow();
methodBuilder.endControlFlow();
defineJavadocFooterForContentOperation(methodBuilder);
if (hasOperation) {
methodBuilder.addStatement("return returnCursor");
}
classBuilder.addMethod(methodBuilder.build());
}
use of com.abubusoft.kripton.processor.sqlite.model.SQLiteModelMethod in project kripton by xcesco.
the class BindContentProviderBuilder method build.
public void build(Elements elementUtils, Filer filer, SQLiteDatabaseSchema schema) throws Exception {
uriSet.clear();
String dataSourceName = schema.getName();
String dataSourceNameClazz = BindDataSourceBuilder.PREFIX + dataSourceName;
String contentProviderName = PREFIX + dataSourceName.replace(BindDataSourceBuilder.SUFFIX, "") + SUFFIX;
PackageElement pkg = elementUtils.getPackageOf(schema.getElement());
String packageName = pkg.isUnnamed() ? null : pkg.getQualifiedName().toString();
AnnotationProcessorUtilis.infoOnGeneratedClasses(BindContentProvider.class, packageName, contentProviderName);
classBuilder = TypeSpec.classBuilder(contentProviderName).addModifiers(Modifier.PUBLIC).superclass(ContentProvider.class);
classBuilder.addJavadoc("<p>This is the content provider generated for {@link $L}</p>\n\n", dataSourceName);
classBuilder.addJavadoc("<h2>Content provider authority:</h2>\n");
classBuilder.addJavadoc("<pre>$L</pre>\n\n", schema.contentProvider.authority);
generateOnCreate(dataSourceNameClazz);
generateOnShutdown(dataSourceNameClazz);
// define static fields
classBuilder.addField(FieldSpec.builder(String.class, "URI", Modifier.STATIC, Modifier.PUBLIC, Modifier.FINAL).initializer("$S", schema.contentProviderUri()).addJavadoc("<p>content provider's URI.</p>\n<pre>$L</pre>\n", schema.contentProviderUri()).build());
// instance
classBuilder.addField(FieldSpec.builder(className(dataSourceNameClazz), "dataSource", Modifier.PRIVATE, Modifier.STATIC).addJavadoc("<p>datasource singleton</p>\n").build());
classBuilder.addField(FieldSpec.builder(String.class, "AUTHORITY", Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL).addJavadoc("<p>Content provider authority</p>\n").initializer("$S", schema.contentProvider.authority).build());
classBuilder.addField(FieldSpec.builder(UriMatcher.class, "sURIMatcher", Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL).addJavadoc("<p>URI matcher</p>\n").initializer("new $T($T.NO_MATCH)", UriMatcher.class, UriMatcher.class).build());
Builder staticBuilder = CodeBlock.builder();
Converter<String, String> daoConstantConverter = CaseFormat.UPPER_CAMEL.converterTo(CaseFormat.UPPER_UNDERSCORE);
List<FieldSpec> listFieldUri = new ArrayList<>();
List<FieldSpec> listFieldString = new ArrayList<>();
List<FieldSpec> listFieldIndex = new ArrayList<>();
List<FieldSpec> listFieldAlias = new ArrayList<>();
for (SQLiteDaoDefinition daoDefinition : schema.getCollection()) {
String pathConstantName = "PATH_" + daoConstantConverter.convert(daoDefinition.getEntitySimplyClassName());
if (!daoDefinition.contentProviderEnabled)
continue;
// define content provider paths
for (SQLiteModelMethod daoMethod : daoDefinition.getCollection()) {
if (!daoMethod.contentProviderEntryPathEnabled)
continue;
ContentEntry entry = uriSet.get(daoMethod.contentProviderEntryPathTemplate);
if (entry == null) {
entry = new ContentEntry(daoMethod.contentProviderEntryPath);
uriSet.put(daoMethod.contentProviderEntryPathTemplate, entry);
entry.path = daoMethod.contentProviderEntryPath;
entry.uriTemplate = daoMethod.contentProviderEntryPathTemplate;
// we finish later
entry.pathCostant = pathConstantName;
entry.pathIndex = pathConstantName;
}
switch(daoMethod.jql.operationType) {
case INSERT:
AssertKripton.fail(entry.insert != null, String.format("In DAO %s, there are more than one %s statement associated to content provider path '%s'", daoDefinition.getName().toString(), daoMethod.jql.operationType, entry.path));
entry.insert = daoMethod;
break;
case UPDATE:
AssertKripton.fail(entry.update != null, String.format("In DAO %s, there are more than one %s statement associated to content provider path '%s'", daoDefinition.getName().toString(), daoMethod.jql.operationType, entry.path));
entry.update = daoMethod;
break;
case SELECT:
AssertKripton.fail(entry.select != null, String.format("In DAO %s, there are more than one %s statement associated to content provider path '%s'", daoDefinition.getName().toString(), daoMethod.jql.operationType, entry.path));
entry.select = daoMethod;
break;
case DELETE:
AssertKripton.fail(entry.delete != null, String.format("In DAO %s, there are more than one %s statement associated to content provider path '%s'", daoDefinition.getName().toString(), daoMethod.jql.operationType, entry.path));
entry.delete = daoMethod;
break;
}
}
}
// sort uri set by
List<Pair<String, ContentEntry>> listUriSet = new ArrayList<>();
Pair<String, ContentEntry> item;
for (Entry<String, ContentEntry> entry : uriSet.entrySet()) {
item = new Pair<String, ContentEntry>(entry.getKey(), entry.getValue());
listUriSet.add(item);
}
Comparator<Pair<String, ContentEntry>> c = new Comparator<Pair<String, ContentEntry>>() {
@Override
public int compare(Pair<String, ContentEntry> lhs, Pair<String, ContentEntry> rhs) {
return lhs.value0.compareTo(rhs.value0);
}
};
Collections.sort(listUriSet, c);
Set<String> alreadyUsedName = new HashSet<String>();
Converter<String, String> format = CaseFormat.LOWER_CAMEL.converterTo(CaseFormat.UPPER_UNDERSCORE);
int i = 1;
for (Pair<String, ContentEntry> entry : listUriSet) {
// define ordered part of attributes (after sort)
entry.value1.pathCostant += "_" + i;
entry.value1.pathIndex += "_" + i + "_INDEX";
entry.value1.pathValue = i;
// build class attributes
listFieldString.add(FieldSpec.builder(String.class, entry.value1.pathCostant, Modifier.STATIC, Modifier.FINAL).initializer(CodeBlock.of("$S", entry.value1.uriTemplate)).build());
listFieldIndex.add(FieldSpec.builder(Integer.TYPE, entry.value1.pathIndex, Modifier.STATIC, Modifier.FINAL).initializer(CodeBlock.of("$L", entry.value1.pathValue)).build());
listFieldUri.add(FieldSpec.builder(Uri.class, "URI_" + entry.value1.pathCostant, Modifier.STATIC, Modifier.FINAL, Modifier.PRIVATE).addJavadoc("<p>Uri</p>\n").addJavadoc("<pre>$L/$L</pre>\n", schema.contentProviderUri().replace("*", "[*]"), entry.value1.uriTemplate.replace("*", "[*]")).initializer(CodeBlock.of("Uri.parse(URI+\"/$L\")", entry.value1.uriTemplate)).build());
generateURIForMethod(schema, listFieldAlias, alreadyUsedName, format, entry, entry.value1.delete);
generateURIForMethod(schema, listFieldAlias, alreadyUsedName, format, entry, entry.value1.insert);
generateURIForMethod(schema, listFieldAlias, alreadyUsedName, format, entry, entry.value1.select);
generateURIForMethod(schema, listFieldAlias, alreadyUsedName, format, entry, entry.value1.update);
staticBuilder.addStatement("sURIMatcher.addURI(AUTHORITY, $L, $L)", entry.value1.pathCostant, entry.value1.pathIndex);
i++;
}
for (FieldSpec f : listFieldUri) {
classBuilder.addField(f);
}
for (FieldSpec f : listFieldString) {
classBuilder.addField(f);
}
for (FieldSpec f : listFieldIndex) {
classBuilder.addField(f);
}
for (FieldSpec f : listFieldAlias) {
classBuilder.addField(f);
}
classBuilder.addStaticBlock(staticBuilder.build());
generateQuery(schema);
generateInsert(schema);
generateUpdate(schema);
generateDelete(schema);
generateGetType(schema);
TypeSpec typeSpec = classBuilder.build();
JavaWriterHelper.writeJava2File(filer, packageName, typeSpec);
}
Aggregations