use of com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition 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.SQLiteDaoDefinition in project kripton by xcesco.
the class AbstractSelectCodeGenerator method generateLiveData.
/**
* generate live data method
* @param classBuilder
* @param mapFields
* @param method
* @param returnType
*/
@Override
public void generateLiveData(TypeSpec.Builder classBuilder, SQLiteModelMethod method) {
SQLiteDaoDefinition daoDefinition = method.getParent();
Set<JQLProjection> fieldList = JQLChecker.getInstance().extractProjections(method, method.jql.value, daoDefinition.getEntity());
// generate method code
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(method.getName().replaceAll(LIVE_DATA_PREFIX, "")).addAnnotation(Override.class).addModifiers(Modifier.PUBLIC);
methodBuilder.addJavadoc("<h2>Live data</h2>\n");
methodBuilder.addJavadoc("<p>This method open a connection internally.</p>\n\n");
generateCommonPart(method, classBuilder, methodBuilder, fieldList, selectType.isMapFields(), GenerationType.NO_CONTENT, method.liveDataReturnClass);
ClassName dataSourceClazz = BindDataSourceBuilder.generateDataSourceName(daoDefinition.getParent());
ClassName daoFactoryClazz = TypeUtility.className(BindDaoFactoryBuilder.generateDaoFactoryName(daoDefinition.getParent()));
ClassName batchClazz = TypeUtility.mergeTypeNameWithSuffix(dataSourceClazz, ".Batch");
List<Pair<String, TypeName>> methodParameters = method.getParameters();
StringBuilder buffer = new StringBuilder();
String separator = "";
for (Pair<String, TypeName> item : methodParameters) {
buffer.append(separator + item.value0);
separator = ", ";
}
TypeSpec batchBuilder = TypeSpec.anonymousClassBuilder("").addSuperinterface(ParameterizedTypeName.get(batchClazz, method.getReturnClass())).addMethod(MethodSpec.methodBuilder("onExecute").addAnnotation(Override.class).addModifiers(Modifier.PUBLIC).addParameter(ParameterSpec.builder(daoFactoryClazz, "daoFactory").build()).returns(method.getReturnClass()).addStatement("return daoFactory.get$L().$L($L)", daoDefinition.getName(), method.getName() + LIVE_DATA_PREFIX, buffer.toString()).build()).build();
TypeSpec liveDataBuilder = TypeSpec.anonymousClassBuilder("").addSuperinterface(ParameterizedTypeName.get(ClassName.get(KriptonComputableLiveData.class), method.getReturnClass())).addMethod(MethodSpec.methodBuilder("compute").addAnnotation(Override.class).addModifiers(Modifier.PROTECTED).returns(method.getReturnClass()).addStatement("return $T.instance().executeBatch($L)", dataSourceClazz, batchBuilder).build()).build();
methodBuilder.addStatement("final $T builder=$L", ParameterizedTypeName.get(ClassName.get(KriptonComputableLiveData.class), method.getReturnClass()), liveDataBuilder);
methodBuilder.addStatement("registryLiveData(builder)");
methodBuilder.addStatement("return builder.getLiveData()");
classBuilder.addMethod(methodBuilder.build());
}
use of com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition in project kripton by xcesco.
the class AbstractSelectCodeGenerator method generateCommonPart.
public void generateCommonPart(SQLiteModelMethod method, TypeSpec.Builder classBuilder, MethodSpec.Builder methodBuilder, Set<JQLProjection> fieldList, boolean mapFields, GenerationType generationType, TypeName forcedReturnType, JavadocPart... javadocParts) {
SQLiteDaoDefinition daoDefinition = method.getParent();
SQLiteEntity entity = daoDefinition.getEntity();
// if true, field must be associate to ben attributes
// TypeName returnType = method.getReturnClass();
TypeName returnTypeName = forcedReturnType;
if (returnTypeName == null) {
returnTypeName = method.getReturnClass();
}
ModelAnnotation annotation = method.getAnnotation(BindSqlSelect.class);
// parameters
List<String> paramNames = new ArrayList<String>();
List<String> paramGetters = new ArrayList<String>();
List<TypeName> paramTypeNames = new ArrayList<TypeName>();
List<String> usedBeanPropertyNames = new ArrayList<>();
// used method parameters
Set<String> usedMethodParameters = new HashSet<String>();
final One<String> whereJQL = new One<>("");
final One<String> havingJQL = new One<>("");
final One<String> groupJQL = new One<>("");
final One<String> orderJQL = new One<>("");
// extract parts of jql statement
JQLChecker.getInstance().replaceVariableStatements(method, method.jql.value, new JQLReplaceVariableStatementListenerImpl() {
@Override
public String onWhere(String statement) {
whereJQL.value0 = statement;
return null;
}
@Override
public String onOrderBy(String statement) {
orderJQL.value0 = statement;
return null;
}
@Override
public String onHaving(String statement) {
havingJQL.value0 = statement;
return null;
}
@Override
public String onGroup(String statement) {
groupJQL.value0 = statement;
return null;
}
});
SqlAnalyzer analyzer = new SqlAnalyzer();
// String whereSQL =
// annotation.getAttribute(AnnotationAttributeType.WHERE);
analyzer.execute(BaseProcessor.elementUtils, method, whereJQL.value0);
paramGetters.addAll(analyzer.getParamGetters());
paramNames.addAll(analyzer.getParamNames());
paramTypeNames.addAll(analyzer.getParamTypeNames());
usedBeanPropertyNames.addAll(analyzer.getUsedBeanPropertyNames());
usedMethodParameters.addAll(analyzer.getUsedMethodParameters());
// String havingSQL =
// annotation.getAttribute(AnnotationAttributeType.HAVING);
analyzer.execute(BaseProcessor.elementUtils, method, havingJQL.value0);
paramGetters.addAll(analyzer.getParamGetters());
paramNames.addAll(analyzer.getParamNames());
paramTypeNames.addAll(analyzer.getParamTypeNames());
usedBeanPropertyNames.addAll(analyzer.getUsedBeanPropertyNames());
usedMethodParameters.addAll(analyzer.getUsedMethodParameters());
// String groupBySQL =
// annotation.getAttribute(AnnotationAttributeType.GROUP_BY);
analyzer.execute(BaseProcessor.elementUtils, method, groupJQL.value0);
paramGetters.addAll(analyzer.getParamGetters());
paramNames.addAll(analyzer.getParamNames());
paramTypeNames.addAll(analyzer.getParamTypeNames());
usedBeanPropertyNames.addAll(analyzer.getUsedBeanPropertyNames());
usedMethodParameters.addAll(analyzer.getUsedMethodParameters());
// String orderBySQL =
// annotation.getAttribute(AnnotationAttributeType.ORDER_BY);
analyzer.execute(BaseProcessor.elementUtils, method, orderJQL.value0);
paramGetters.addAll(analyzer.getParamGetters());
paramNames.addAll(analyzer.getParamNames());
paramTypeNames.addAll(analyzer.getParamTypeNames());
usedBeanPropertyNames.addAll(analyzer.getUsedBeanPropertyNames());
usedMethodParameters.addAll(analyzer.getUsedMethodParameters());
// add as used parameter dynamic components too
if (method.hasDynamicWhereConditions()) {
AssertKripton.assertTrueOrInvalidMethodSignException(!usedMethodParameters.contains(method.dynamicWhereParameterName), method, " parameter %s is used like SQL parameter and dynamic WHERE condition.", method.dynamicOrderByParameterName);
usedMethodParameters.add(method.dynamicWhereParameterName);
if (method.hasDynamicWhereArgs()) {
AssertKripton.assertTrueOrInvalidMethodSignException(!usedMethodParameters.contains(method.dynamicWhereArgsParameterName), method, " parameter %s is used like SQL parameter and dynamic WHERE ARGS condition.", method.dynamicWhereArgsParameterName);
usedMethodParameters.add(method.dynamicWhereArgsParameterName);
}
}
if (method.hasDynamicOrderByConditions()) {
AssertKripton.assertTrueOrInvalidMethodSignException(!usedMethodParameters.contains(method.dynamicOrderByParameterName), method, " parameter %s is used like SQL parameter and dynamic ORDER BY condition.", method.dynamicOrderByParameterName);
usedMethodParameters.add(method.dynamicOrderByParameterName);
}
if (method.hasDynamicPageSizeConditions()) {
AssertKripton.assertTrueOrInvalidMethodSignException(!usedMethodParameters.contains(method.dynamicPageSizeName), method, " parameter %s is used like SQL parameter and dynamic page size of LIMIT condition.", method.dynamicPageSizeName);
usedMethodParameters.add(method.dynamicPageSizeName);
}
// generate method signature
if (generationType.generateMethodSign) {
generateMethodSignature(method, methodBuilder, returnTypeName);
}
// generate javadoc
JavadocUtility.generateJavaDocForSelect(methodBuilder, paramNames, method, annotation, fieldList, selectType, javadocParts);
if (generationType.generateMethodContent) {
SplittedSql splittedSql = SqlSelectBuilder.generateSQL(method, methodBuilder, false);
// retrieve content values
methodBuilder.addStatement("$T _contentValues=contentValues()", KriptonContentValues.class);
if (method.hasDynamicParts()) {
generateSQLBuild(method, methodBuilder, splittedSql);
methodBuilder.addStatement("String _sql=_sqlBuilder.toString()");
} else {
String sqlName = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, method.buildSQLName());
String sql = SqlSelectBuilder.convertJQL2SQL(method, true);
classBuilder.addField(FieldSpec.builder(String.class, sqlName, Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL).initializer("$S", sql).build());
methodBuilder.addComment("query SQL is statically defined");
methodBuilder.addStatement("String _sql=$L", sqlName);
}
// build where condition (common for every type of select)
StringBuilder logArgsBuffer = new StringBuilder();
methodBuilder.addComment("add where arguments");
{
String separator = "";
TypeName paramTypeName;
// String paramName;
boolean nullable;
int i = 0;
boolean rawParameters;
String beanName = null;
beanName = method.findEntityProperty();
for (String item : paramGetters) {
rawParameters = paramNames.get(i).indexOf(".") == -1;
methodBuilder.addCode("_contentValues.addWhereArgs(");
logArgsBuffer.append(separator + "%s");
paramTypeName = paramTypeNames.get(i);
// code for query arguments
nullable = TypeUtility.isNullable(paramTypeName);
if (rawParameters) {
if (nullable && !method.hasAdapterForParam(item)) {
methodBuilder.addCode("($L==null?\"\":", item);
}
// check for string conversion
TypeUtility.beginStringConversion(methodBuilder, paramTypeName);
SQLTransformer.javaMethodParam2WhereConditions(methodBuilder, method, item, paramTypeName);
// check for string conversion
TypeUtility.endStringConversion(methodBuilder, paramTypeName);
if (nullable && !method.hasAdapterForParam(item)) {
methodBuilder.addCode(")");
}
} else {
// eventually we take associated property
SQLProperty property = usedBeanPropertyNames.get(i) == null ? null : entity.get(usedBeanPropertyNames.get(i));
if (nullable && !(property != null) && !method.hasAdapterForParam(item)) {
methodBuilder.addCode("($L==null?\"\":", item);
}
// check for string conversion
TypeUtility.beginStringConversion(methodBuilder, paramTypeName);
// if (property != null) {
// SQLTransformer.javaProperty2WhereCondition(methodBuilder,
// method, item, paramTypeName, property);
// } else {
SQLTransformer.javaProperty2WhereCondition(methodBuilder, method, beanName, paramTypeName, property);
// }
// check for string conversion
TypeUtility.endStringConversion(methodBuilder, paramTypeName);
if (nullable && !(property != null) && !method.hasAdapterForParam(item)) {
methodBuilder.addCode(")");
}
}
separator = ", ";
i++;
methodBuilder.addCode(");\n");
}
}
methodBuilder.addStatement("String[] _sqlArgs=_contentValues.whereArgsAsArray()");
if (daoDefinition.isLogEnabled()) {
// generate log section - BEGIN
methodBuilder.addComment("log section BEGIN");
methodBuilder.beginControlFlow("if (_context.isLogEnabled())");
// manage log
methodBuilder.addComment("manage log");
methodBuilder.addStatement("$T.info(_sql)", Logger.class);
// log for where parames
SqlBuilderHelper.generateLogForWhereParameters(method, methodBuilder);
// generate log section - END
methodBuilder.endControlFlow();
methodBuilder.addComment("log section END");
}
if (generationType.generateCloseableCursor) {
methodBuilder.beginControlFlow("try ($T _cursor = database().rawQuery(_sql, _sqlArgs))", Cursor.class);
} else {
methodBuilder.addStatement("$T _cursor = database().rawQuery(_sql, _sqlArgs)", Cursor.class);
}
if (daoDefinition.isLogEnabled()) {
// generate log section - BEGIN
methodBuilder.addComment("log section BEGIN");
methodBuilder.beginControlFlow("if (_context.isLogEnabled())");
methodBuilder.addCode("$T.info(\"Rows found: %s\",_cursor.getCount());\n", Logger.class);
// generate log section - END
methodBuilder.endControlFlow();
methodBuilder.addComment("log section END");
}
switch(selectType) {
case LISTENER_CURSOR:
{
ClassName readCursorListenerToExclude = ClassName.get(OnReadCursorListener.class);
checkUnusedParameters(method, usedMethodParameters, readCursorListenerToExclude);
}
break;
case LISTENER_BEAN:
{
ParameterizedTypeName readBeanListenerToExclude = ParameterizedTypeName.get(ClassName.get(OnReadBeanListener.class), TypeName.get(entity.getElement().asType()));
checkUnusedParameters(method, usedMethodParameters, readBeanListenerToExclude);
}
break;
default:
checkUnusedParameters(method, usedMethodParameters, null);
break;
}
}
}
use of com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition in project kripton by xcesco.
the class AbstractSelectCodeGenerator method generate.
@Override
public void generate(TypeSpec.Builder classBuilder, boolean mapFields, SQLiteModelMethod method) {
SQLiteDaoDefinition daoDefinition = method.getParent();
Set<JQLProjection> fieldList = JQLChecker.getInstance().extractProjections(method, method.jql.value, daoDefinition.getEntity());
// generate method code
MethodSpec.Builder methodBuilder = generateMethodBuilder(method);
generateCommonPart(method, classBuilder, methodBuilder, fieldList, selectType.isMapFields());
generateSpecializedPart(method, classBuilder, methodBuilder, fieldList, selectType.isMapFields());
classBuilder.addMethod(methodBuilder.build());
}
use of com.abubusoft.kripton.processor.sqlite.model.SQLiteDaoDefinition 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());
}
Aggregations