use of com.abubusoft.kripton.processor.core.ModelAnnotation 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.core.ModelAnnotation 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.core.ModelAnnotation in project kripton by xcesco.
the class AnnotationUtility method buildAnnotationList.
public static List<ModelAnnotation> buildAnnotationList(final Element element, final AnnotationFilter filter) {
final List<ModelAnnotation> annotationList = new ArrayList<>();
forEachAnnotations(element, filter, new AnnotationFoundListener() {
@Override
public void onAcceptAnnotation(Element executableMethod, String annotationClassName, Map<String, String> attributes) {
ModelAnnotation annotation = new ModelAnnotation(annotationClassName, attributes);
annotationList.add(annotation);
}
});
return annotationList;
}
use of com.abubusoft.kripton.processor.core.ModelAnnotation in project kripton by xcesco.
the class BindSharedPreferencesBuilder method generate.
/**
* Generate shared preference manager
*
* @return typeName of generated class
*
* @throws IOException
*/
public static String generate(Elements elementUtils, Filer filer, PrefsEntity entity) throws IOException {
com.abubusoft.kripton.common.Converter<String, String> converter = CaseFormat.UPPER_CAMEL.converterTo(CaseFormat.LOWER_CAMEL);
String beanClassName = entity.getSimpleName().toString();
String suffix;
if (beanClassName.endsWith(SUFFIX_SHARED_PREFERENCE)) {
suffix = "";
} else if (beanClassName.endsWith(SUFFIX_PREFERENCE)) {
suffix = "";
} else {
suffix = SUFFIX_SHARED_PREFERENCE;
}
String className = PREFIX + beanClassName + suffix;
ModelAnnotation annotation = entity.getAnnotation(BindSharedPreferences.class);
String sharedPreferenceName = annotation.getAttribute(AnnotationAttributeType.VALUE);
PackageElement pkg = elementUtils.getPackageOf(entity.getElement());
String packageName = pkg.isUnnamed() ? "" : pkg.getQualifiedName().toString();
AnnotationProcessorUtilis.infoOnGeneratedClasses(BindSharedPreferences.class, packageName, className);
// @formatter:off
builder = TypeSpec.classBuilder(className).addModifiers(Modifier.PUBLIC).superclass(AbstractSharedPreference.class);
BindTypeContext context = new BindTypeContext(builder, TypeUtility.typeName(entity.getElement()), Modifier.PRIVATE);
// @formatter:on
builder.addJavadoc("This class is the shared preference binder defined for $T\n\n", entity.getElement());
JavadocUtility.generateJavadocGeneratedBy(builder);
builder.addJavadoc("@see $T\n", entity.getElement());
if (StringUtils.hasText(sharedPreferenceName)) {
builder.addField(FieldSpec.builder(String.class, "SHARED_PREFERENCE_NAME", Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL).initializer("$S", converter.convert(entity.getSimpleName().toString())).addJavadoc("shared preferences typeName for $T\n", entity.getElement()).build());
}
builder.addField(FieldSpec.builder(className(beanClassName), "defaultBean", Modifier.PRIVATE, Modifier.FINAL).addJavadoc("working instance of bean\n").build());
{
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("edit").addJavadoc("create an editor to modify shared preferences\n").returns(typeName("BindEditor")).addModifiers(Modifier.PUBLIC);
methodBuilder.addStatement("return new $T()", typeName("BindEditor"));
builder.addMethod(methodBuilder.build());
}
generateEditor(entity);
generateConstructor(sharedPreferenceName, beanClassName);
generateRefresh(sharedPreferenceName, className);
generateResetMethod(entity);
generateReadMethod(entity);
generateWriteMethod(entity);
generateSingleReadMethod(entity);
// generate all needed writer and reader
List<PrefsProperty> fields = entity.getCollection();
List<PrefsProperty> filteredFields = new ArrayList<>();
// we need to avoid generation of persists values
for (PrefsProperty item : fields) {
if (SetPrefsTransformation.isStringSet(item)) {
continue;
} else {
filteredFields.add(item);
}
}
// avoid to consider StringSet
ManagedPropertyPersistenceHelper.generateFieldPersistance(context, filteredFields, PersistType.STRING, false, Modifier.PROTECTED);
generateInstance(className);
TypeSpec typeSpec = builder.build();
JavaWriterHelper.writeJava2File(filer, packageName, typeSpec);
return className;
}
use of com.abubusoft.kripton.processor.core.ModelAnnotation in project kripton by xcesco.
the class BindTableGenerator method buldIndexes.
public static Pair<String, String> buldIndexes(final SQLiteEntity entity, boolean unique, int counter) {
Pair<String, String> result = new Pair<>();
result.value0 = "";
result.value1 = "";
ModelAnnotation annotationTable = entity.getAnnotation(BindTable.class);
if (annotationTable == null)
return result;
List<String> indexes = null;
String uniqueString;
if (unique) {
uniqueString = "UNIQUE ";
indexes = annotationTable.getAttributeAsArray(AnnotationAttributeType.UNIQUE_INDEXES);
} else {
uniqueString = "";
indexes = annotationTable.getAttributeAsArray(AnnotationAttributeType.INDEXES);
}
if (indexes == null || indexes.size() == 0)
return result;
// CREATE INDEX index_name ON tab_name (column1, column2)
// Matcher matcher = patternIndex.matcher(rawIndexes);
List<String> listCreateIndex = new ArrayList<>();
List<String> listDropIndex = new ArrayList<>();
for (String index : indexes) {
String createIndex = String.format(" CREATE %sINDEX idx_%s_%s on %s (%s)", uniqueString, entity.getTableName(), counter++, entity.getTableName(), index);
String dropIndex = String.format(" DROP INDEX IF EXISTS idx_%s_%s", entity.getTableName(), counter);
final One<Integer> fieldCounter = new One<Integer>(0);
createIndex = JQLChecker.getInstance().replace(new JQLContext() {
@Override
public String getContextDescription() {
return "While table definition generation for entity " + entity.getName();
}
}, createIndex, new JQLReplacerListenerImpl(null) {
@Override
public String onColumnName(String columnName) {
fieldCounter.value0++;
SQLProperty property = entity.findPropertyByName(columnName);
AssertKripton.assertTrue(property != null, "class '%s' in @%s(indexes) use unknown property '%s'", entity.getName(), BindTable.class.getSimpleName(), columnName);
return property.columnName;
}
@Override
public String onColumnFullyQualifiedName(String tableName, String columnName) {
AssertKripton.fail("Inconsistent state");
return null;
}
});
AssertKripton.assertTrue(fieldCounter.value0 > 0, "class '%s' have @%s(indexes) with no well formed indexes", entity.getName(), BindTable.class.getSimpleName());
listCreateIndex.add(createIndex);
listDropIndex.add(dropIndex);
}
result.value0 = StringUtils.join(listCreateIndex, ";");
result.value1 = StringUtils.join(listDropIndex, ";");
return result;
}
Aggregations