private static List<MethodSpec> createIntentBuildMethods( AutoBundleBindingClass target, String fieldName) { List<MethodSpec> methodSpecs = new ArrayList<>(2); ClassName contextClass = ClassName.get("android.content", "Context"); ClassName intentClass = ClassName.get("android.content", "Intent"); MethodSpec buildWithContext = MethodSpec.methodBuilder("build") .addModifiers(Modifier.PUBLIC) .addParameter(contextClass, "context") .returns(intentClass) .addStatement( "$T intent = new $T(context, $T.class)", intentClass, intentClass, target.getTargetType()) .addStatement("intent.putExtras($N)", fieldName) .addStatement("return intent") .build(); MethodSpec buildWithIntent = MethodSpec.methodBuilder("build") .addModifiers(Modifier.PUBLIC) .addParameter(intentClass, "intent") .returns(intentClass) .addStatement("intent.putExtras($N)", fieldName) .addStatement("return intent") .build(); methodSpecs.add(buildWithContext); methodSpecs.add(buildWithIntent); return methodSpecs; }
protected TypeName getImplementationType() { if (this.implementationType == null) { Class<?> impl = getDefaultImplementation(); if (impl != null) { return ClassName.get(impl); } return ClassName.get((TypeElement) Util.typeUtils.asElement(this.getType())); } return ClassName.get((TypeElement) Util.typeUtils.asElement(this.implementationType)); }
TypeName cataMapperTypeName(DataConstructor dc) { TypeName[] argsTypeNames = concat( dc.arguments().stream().map(DataArgument::type), dc.typeRestrictions() .stream() .map(TypeRestriction::idFunction) .map(DataArgument::type)) .map(t -> Utils.asBoxedType.visit(t, utils.types())) .map(this::substituteTypeWithRecursionVar) .map(TypeName::get) .toArray(TypeName[]::new); return adt.dataConstruction().isVisitorDispatch() ? argsTypeNames.length == 0 ? ParameterizedTypeName.get( ClassName.get(FlavourImpl.findF0(context.flavour(), utils.elements())), TypeName.get(adt.matchMethod().returnTypeVariable())) : argsTypeNames.length == 1 ? ParameterizedTypeName.get( ClassName.get(FlavourImpl.findF(context.flavour(), utils.elements())), argsTypeNames[0], TypeName.get(adt.matchMethod().returnTypeVariable())) : ParameterizedTypeName.get( Utils.getClassName(context, MapperDerivator.mapperInterfaceName(dc)), concat( concat( dc.typeVariables().stream().map(TypeVariableName::get), fold( MapperDerivator.findInductiveArgument(utils, adt, dc), Stream.<TypeName>of(), tm -> Stream.of( ParameterizedTypeName.get( ClassName.get( FlavourImpl.findF0( context.flavour(), utils.elements())), TypeName.get( adt.matchMethod().returnTypeVariable()))))), Stream.of(TypeVariableName.get(adt.matchMethod().returnTypeVariable()))) .toArray(TypeName[]::new)) : TypeName.get( utils .types() .getDeclaredType( Utils.asTypeElement.visit(dc.deconstructor().visitorType().asElement()).get(), dc.deconstructor() .visitorType() .getTypeArguments() .stream() .map(this::substituteTypeWithRecursionVar) .toArray(TypeMirror[]::new))); }
private boolean hasParcelableConstructor(TypeElement typeElement) { for (Element e : typeElement.getEnclosedElements()) { if (e.getKind() == ElementKind.CONSTRUCTOR && hasSomeModifier(e, Modifier.PUBLIC)) { ExecutableElement c = (ExecutableElement) e; List<? extends VariableElement> params = c.getParameters(); if (params.size() == 1 && ClassName.get(params.get(0).asType()).equals(ClassName.get(Parcel.class))) { return true; } } } return false; }
public static MethodSpec.Builder createParseFieldsFunction( String paramPackageName, String paramClassName) { ClassName clazzReturn = ClassName.get("java.lang", "String"); ClassName stringBuilder = ClassName.get("java.lang", "StringBuilder"); ClassName parameter = ClassName.get(paramPackageName, paramClassName); MethodSpec.Builder mapFieldsBuilder = MethodSpec.methodBuilder(parseFieldsFunction) .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addException(fieldDecoratorEx) .addParameter(parameter, instanceName) .returns(clazzReturn) .addStatement("$T " + stringBuilderName + " = new $T()", stringBuilder, stringBuilder); return mapFieldsBuilder; }
public static void addGetterSetterCallBean( TypeWrapper type, MethodSpec.Builder mapFieldsBuilder, String getterName) { ClassName nestedParser = ClassName.get(packageName, type.getName() + classNameSufix); mapFieldsBuilder .beginControlFlow( "if (" + instanceName + " != null && " + instanceName + "." + getterName + "() != null)") .addStatement( stringBuilderName + ".append($T." + parseFieldsFunction + "(" + instanceName + "." + getterName + "()))", nestedParser) .endControlFlow() .beginControlFlow("else") .addStatement( stringBuilderName + ".append($T." + parseFieldsFunction + "(null))", nestedParser) .endControlFlow(); }
private static List<MethodSpec> createBuilderMethods( AutoBundleBindingClass target, String fieldName) { List<MethodSpec> methodSpecs = new ArrayList<>(); for (AutoBundleBindingField arg : target.getNotRequiredArgs()) { String argKey = arg.getArgKey(); TypeName argType = arg.getArgType(); String operationName = arg.getOperationName("put"); MethodSpec.Builder builder = MethodSpec.methodBuilder(argKey) .addModifiers(Modifier.PUBLIC) .addParameter(argType, argKey) .returns(ClassName.get(target.getPackageName(), target.getBuilderClassName())); if (arg.hasCustomConverter()) { TypeName converter = arg.getConverter(); builder .addStatement("$T $NConverter = new $T()", converter, argKey, converter) .addStatement( "$N.$N($S, $NConverter.convert($N))", fieldName, operationName, argKey, argKey, argKey); } else { builder.addStatement("$N.$N($S, $N)", fieldName, operationName, argKey, argKey); } builder.addStatement("return this"); methodSpecs.add(builder.build()); } return methodSpecs; }
static { javaToSqlite.put(TypeName.INT, "INTEGER"); javaToSqlite.put(TypeName.INT.box(), "INTEGER"); javaToSqlite.put(TypeName.LONG, "INTEGER"); javaToSqlite.put(TypeName.LONG.box(), "INTEGER"); javaToSqlite.put(TypeName.SHORT, "INTEGER"); javaToSqlite.put(TypeName.SHORT.box(), "INTEGER"); javaToSqlite.put(TypeName.BYTE, "INTEGER"); javaToSqlite.put(TypeName.BYTE.box(), "INTEGER"); javaToSqlite.put(TypeName.FLOAT, "REAL"); javaToSqlite.put(TypeName.FLOAT.box(), "REAL"); javaToSqlite.put(TypeName.DOUBLE, "REAL"); javaToSqlite.put(TypeName.DOUBLE.box(), "REAL"); javaToSqlite.put(ClassName.get(String.class), "TEXT"); javaToSqlite.put(TypeName.CHAR, "TEXT"); javaToSqlite.put(TypeName.CHAR.box(), "TEXT"); javaToSqlite.put(ArrayTypeName.of(TypeName.BYTE), "BLOB"); javaToSqlite.put(TypeName.BOOLEAN, "BOOLEAN"); javaToSqlite.put(TypeName.BOOLEAN.box(), "BOOLEAN"); javaToSqlite.put(Types.SingleRelation, "INTEGER"); // foreign key // TODO: date and time types? }
/** @author [email protected] (Marcio Endo) */ class AttributeAnnotationFake { public static final AttributeAnnotation ALT = AttributeAnnotation.builder() .name("alt") .identifier("alt") .typeName(ClassName.get(String.class)) .build(); public static final AttributeAnnotation CLASS = AttributeAnnotation.builder() .name("class") .identifier("styleClass") .typeName(ClassName.get(String.class)) .build(); public static final AttributeAnnotation HIDDEN = AttributeAnnotation.builder() .name("hidden") .identifier("hidden") .typeName(TypeName.BOOLEAN) .build(); public static final AttributeAnnotation ID = AttributeAnnotation.builder() .name("id") .identifier("id") .typeName(ClassName.get(String.class)) .build(); public static final AttributeAnnotation SRC = AttributeAnnotation.builder() .name("src") .identifier("src") .typeName(ClassName.get(String.class)) .build(); public static final AttributeAnnotation TABINDEX = AttributeAnnotation.builder() .name("tabindex") .identifier("tabindex") .typeName(TypeName.INT) .build(); private AttributeAnnotationFake() {} }
static { JAVA_TO_SQLITE_TYPE = new HashMap<>(); JAVA_TO_SQLITE_TYPE.put(TypeName.INT.toString(), INTEGER); JAVA_TO_SQLITE_TYPE.put(TypeName.LONG.toString(), INTEGER); JAVA_TO_SQLITE_TYPE.put(TypeName.FLOAT.toString(), REAL); JAVA_TO_SQLITE_TYPE.put(TypeName.DOUBLE.toString(), REAL); JAVA_TO_SQLITE_TYPE.put(TypeName.BOOLEAN.toString(), INTEGER); JAVA_TO_SQLITE_TYPE.put(ClassName.get(String.class).toString(), TEXT); JAVA_TO_SQLITE_TYPE.put(BYTE_ARRAY, BLOB); }
static { CURSOR_TO_JAVA_TYPE = new HashMap<>(); CURSOR_TO_JAVA_TYPE.put(TypeName.INT.toString(), "$T.getInt(cursor, $S)"); CURSOR_TO_JAVA_TYPE.put(TypeName.LONG.toString(), "$T.getLong(cursor, $S)"); CURSOR_TO_JAVA_TYPE.put(TypeName.FLOAT.toString(), "$T.getFloat(cursor, $S)"); CURSOR_TO_JAVA_TYPE.put(TypeName.DOUBLE.toString(), "$T.getDouble(cursor, $S)"); CURSOR_TO_JAVA_TYPE.put(TypeName.BOOLEAN.toString(), "$T.getBoolean(cursor, $S)"); CURSOR_TO_JAVA_TYPE.put(ClassName.get(String.class).toString(), "$T.getString(cursor, $S)"); CURSOR_TO_JAVA_TYPE.put(BYTE_ARRAY, "$T.getBlob(cursor, $S)"); }
public TypeSpec createTerminalType() { final TypeName terminal = ParameterizedTypeName.get( ClassName.get(Terminal.class), ClassName.get(packageName, terminalName)); return TypeSpec.classBuilder(terminalName) .addJavadoc("The <$L> element.\n", tag) .addAnnotation(AnnotationSpec.builder(Root.class).build()) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addSuperinterface(terminal) .addField(createFieldMissing()) .addField(createFieldValue()) .addMethod(createPublicConstructor()) .addMethod(createPrivateConstructor()) .addMethod(createValueGetter()) .addMethod(createCompareTo()) .addMethod(createHashCode()) .addMethod(createEquals()) .addMethod(createShow()) .build(); }
public TerminalWriter(final JavaFileInfo javaFileInfo) { Preconditions.checkNotNull(javaFileInfo, "Missing 'javaFileInfo'."); this.javaFileInfo = javaFileInfo; packageName = javaFileInfo.packageName(); terminalName = javaFileInfo.entityName(); prime = javaFileInfo.prime(); tag = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, terminalName); simpleName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, terminalName).replace('_', ' '); terminalTypeName = ClassName.get(packageName, terminalName); }
{ put(ArrayTypeName.of(TypeName.BYTE), "getBlb"); put(ArrayTypeName.of(TypeName.BYTE.box()), "getBlob"); put(TypeName.BYTE, "getByt"); put(TypeName.BYTE.box(), "getByte"); put(TypeName.DOUBLE, "getDble"); put(TypeName.DOUBLE.box(), "getDouble"); put(TypeName.FLOAT, "getFlt"); put(TypeName.FLOAT.box(), "getFloat"); put(TypeName.INT, "getInt"); put(TypeName.INT.box(), "getInteger"); put(TypeName.LONG, "getLng"); put(TypeName.LONG.box(), "getLong"); put(TypeName.SHORT, "getShrt"); put(TypeName.SHORT.box(), "getShort"); put(TypeName.BOOLEAN.box(), "getBoolean"); put(TypeName.BOOLEAN, "getBool"); put(ClassName.get(String.class), "getString"); put(ClassName.get(Blob.class), "getBlb"); }
{ put(ArrayTypeName.of(TypeName.BYTE), "getBlob"); put(ArrayTypeName.of(TypeName.BYTE.box()), "getBlob"); put(TypeName.BOOLEAN, "getInt"); put(TypeName.BYTE, "getInt"); put(TypeName.BYTE.box(), "getInt"); put(TypeName.CHAR, "getString"); put(TypeName.CHAR.box(), "getString"); put(TypeName.DOUBLE, "getDouble"); put(TypeName.DOUBLE.box(), "getDouble"); put(TypeName.FLOAT, "getFloat"); put(TypeName.FLOAT.box(), "getFloat"); put(TypeName.INT, "getInt"); put(TypeName.INT.box(), "getInt"); put(TypeName.LONG, "getLong"); put(TypeName.LONG.box(), "getLong"); put(TypeName.SHORT, "getShort"); put(TypeName.SHORT.box(), "getShort"); put(ClassName.get(String.class), "getString"); put(ClassName.get(Blob.class), "getBlob"); }
public static void addGetterSetterCallPrimitive( MethodSpec.Builder mapFieldsBuilder, String getterName, int length, String decoratorClassName, char paddingCharacter, PaddingAlign paddingAlign) { ClassName padding = ClassName.get(PaddingAlign.class); mapFieldsBuilder .beginControlFlow( "if (" + instanceName + " != null && " + instanceName + "." + getterName + "() != null)") .addStatement( stringBuilderName + ".append($T.getInstance().parseToText(" + instanceName + "." + getterName + "()," + length + ", " + decoratorClassName + ".class, '" + paddingCharacter + "', $T." + paddingAlign.toString() + "))", extractor, padding) .endControlFlow() .beginControlFlow("else") .addStatement( stringBuilderName + ".append($T.getInstance().parseToText(null," + length + ", " + decoratorClassName + ".class, '" + paddingCharacter + "', $T." + paddingAlign.toString() + "))", extractor, padding) .endControlFlow(); }
{ put(TypeName.BYTE, SQLiteHelper.INTEGER); put(TypeName.SHORT, SQLiteHelper.INTEGER); put(TypeName.INT, SQLiteHelper.INTEGER); put(TypeName.LONG, SQLiteHelper.INTEGER); put(TypeName.FLOAT, SQLiteHelper.REAL); put(TypeName.DOUBLE, SQLiteHelper.REAL); put(TypeName.BOOLEAN, SQLiteHelper.INTEGER); put(TypeName.CHAR, SQLiteHelper.TEXT); put(ArrayTypeName.of(TypeName.BYTE), SQLiteHelper.BLOB); put(TypeName.BYTE.box(), SQLiteHelper.INTEGER); put(TypeName.SHORT.box(), SQLiteHelper.INTEGER); put(TypeName.INT.box(), SQLiteHelper.INTEGER); put(TypeName.LONG.box(), SQLiteHelper.INTEGER); put(TypeName.FLOAT.box(), SQLiteHelper.REAL); put(TypeName.DOUBLE.box(), SQLiteHelper.REAL); put(TypeName.BOOLEAN.box(), SQLiteHelper.INTEGER); put(TypeName.CHAR.box(), SQLiteHelper.TEXT); put(ClassName.get(String.class), SQLiteHelper.TEXT); put(ArrayTypeName.of(TypeName.BYTE.box()), SQLiteHelper.BLOB); put(ArrayTypeName.of(TypeName.BYTE), SQLiteHelper.BLOB); put(ClassName.get(Blob.class), SQLiteHelper.BLOB); }
private void generate(RestActionClass actionClass) { TypeSpec.Builder classBuilder = TypeSpec.classBuilder(actionClass.getHelperName()) .addModifiers(Modifier.PUBLIC) .addJavadoc("SantaRest compile time, autogenerated class, which fills actions") .addSuperinterface( ParameterizedTypeName.get( ClassName.get(SantaRest.ActionHelper.class), actionClass.getTypeName())); classBuilder.addMethod(createRequestMethod(actionClass)); classBuilder.addMethod(createFillResponseMethod(actionClass)); classBuilder.addMethod(createFillErrorMethod(actionClass)); saveClass(actionClass.getPackageName(), classBuilder.build()); }
private static MethodSpec createCallBuilderMethod(AutoBundleBindingClass target) { ClassName builderClass = ClassName.get(target.getPackageName(), target.getBuilderClassName()); MethodSpec.Builder builder = MethodSpec.methodBuilder("create" + target.getBuilderType().name() + "Builder") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(builderClass) .addCode("return new $T(", builderClass); for (int i = 0, count = target.getRequiredArgs().size(); i < count; i++) { if (i > 0) { builder.addCode(","); } AutoBundleBindingField arg = target.getRequiredArgs().get(i); builder.addParameter(arg.getArgType(), arg.getArgKey()).addCode("$N", arg.getArgKey()); } return builder.addCode(");\n").build(); }
private MethodSpec createFillResponseMethod(RestActionClass actionClass) { MethodSpec.Builder builder = MethodSpec.methodBuilder("fillResponse") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .returns(ClassName.get(actionClass.getTypeElement().asType())) .addParameter(actionClass.getTypeName(), "action") .addParameter(Response.class, "response") .addParameter(Converter.class, "converter"); addStatusField(actionClass, builder); addResponses(actionClass, builder); addBasicHeadersMap(actionClass, builder); addResponseHeaders(actionClass, builder); builder.addStatement("return action"); return builder.build(); }
public static TypeName getTypeName(final Element element, final boolean wrap) { final TypeMirror typeMirror = getTypeMirror(element); final TypeKind kind = typeMirror.getKind(); if (kind == TypeKind.ERROR) { final ProcessorContext context = ProcessorContextHolder.getContext(); final Collection<ProcessorSourceContext> sourceContexts = context.getSourceContexts(); final String typeName = String.valueOf(typeMirror); final TypeElement originElement = ProcessorSourceContext.guessOriginElement(sourceContexts, typeName); if (originElement != null) { final String packageName = ProcessorUtils.packageName(originElement); return ClassName.get(packageName, typeName); } return ClassName.bestGuess(typeName); } return TypeName.get(wrap ? ProcessorUtils.getWrappedType(typeMirror).asType() : typeMirror); }
private static MethodSpec createBindMethod(AutoBundleBindingClass target) { MethodSpec.Builder builder = MethodSpec.methodBuilder("bind") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(void.class) .addParameter(target.getTargetType(), "target"); switch (target.getBuilderType()) { case Fragment: builder.addStatement("bind(target, target.getArguments())"); break; case Intent: builder.addParameter(ClassName.get("android.content", "Intent"), "intent"); builder .beginControlFlow("if (intent.getExtras() != null)") .addStatement("bind(target, intent.getExtras())") .endControlFlow(); break; } return builder.build(); }
private void addCreatorField(HelperClassBuilder builder) { FieldSpec.Builder field = FieldSpec.builder( ParameterizedTypeName.get( ClassName.get(Parcelable.Creator.class), builder.getArgClassName()), FIELD_NAME_CREATOR, Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL); field.addAnnotation( WeaveBuilder.weave() .field() .withStatement("%s.%s", fullName(builder.getClassName()), FIELD_NAME_CREATOR) .build()); field.initializer( "new $T<$T>() {\n" + "\t@$T\n" + "\tpublic $T createFromParcel($T in) {\n" + "\t\treturn new $T(in);\n" + "\t}\n" + "\t@$T\n" + "\tpublic $T[] newArray(int size) {\n" + "\t\treturn new $T[size];\n" + "\t}\n" + "}", Parcelable.Creator.class, builder.getArgClassName(), Override.class, builder.getArgClassName(), Parcel.class, builder.getArgClassName(), Override.class, builder.getArgClassName(), builder.getArgClassName()); builder.getBuilder().addField(field.build()); }
public static MethodSpec.Builder createParseFieldsToListFunction( TypeWrapper type, MethodSpec.Builder mapFieldsBuilder, String getterName, int length) { ClassName nestedParser = ClassName.get(packageName, type.getName() + classNameSufix); mapFieldsBuilder .beginControlFlow("for (int i = 0; i < " + String.valueOf(length) + "; i++)") .beginControlFlow( "if (" + instanceName + " != null && " + instanceName + "." + getterName + "() != null && " + instanceName + "." + getterName + "().size() > i)") .addStatement( stringBuilderName + ".append($T." + parseFieldsFunction + "(" + instanceName + "." + getterName + "().get(i)))", nestedParser) .endControlFlow() .beginControlFlow("else") .addStatement( stringBuilderName + ".append($T." + parseFieldsFunction + "(null))", nestedParser) .endControlFlow() .endControlFlow(); return mapFieldsBuilder; }
/** * Description: The static FQCN string file to assist in providing class names for imports and more * in the Compiler */ public class ClassNames { public static final String BASE_PACKAGE = "com.raizlabs.android.dbflow"; public static final String FLOW_MANAGER_PACKAGE = BASE_PACKAGE + ".config"; public static final String DATABASE_HOLDER_STATIC_CLASS_NAME = "GeneratedDatabaseHolder"; public static final String CONVERTER = BASE_PACKAGE + ".converter"; public static final String STRUCTURE = BASE_PACKAGE + ".structure"; public static final String CONTAINER = STRUCTURE + ".container"; public static final String SQL = BASE_PACKAGE + ".sql"; public static final String LANGUAGE = SQL + ".language"; public static final String PROPERTY_PACKAGE = LANGUAGE + ".property"; public static final String CONFIG = BASE_PACKAGE + ".config"; public static final String BUILDER = SQL + ".builder"; public static final String MIGRATION_PACKAGE = SQL + ".migration"; public static final String LISTENER = STRUCTURE + ".listener"; public static final String RUNTIME = BASE_PACKAGE + ".runtime"; public static final String TRANSACTION = RUNTIME + ".transaction"; public static final String PROCESS = TRANSACTION + ".process"; public static final ClassName DATABASE_HOLDER = ClassName.get(CONFIG, "DatabaseHolder"); public static final ClassName FLOW_SQLITE_OPEN_HELPER = ClassName.get(CONFIG, "FlowSQLiteOpenHelper"); public static final ClassName FLOW_MANAGER = ClassName.get(CONFIG, "FlowManager"); public static final ClassName BASE_DATABASE_DEFINITION_CLASSNAME = ClassName.get(CONFIG, "BaseDatabaseDefinition"); public static final ClassName SQLITE_STATEMENT = ClassName.get("android.database.sqlite", "SQLiteStatement"); public static final ClassName URI = ClassName.get("android.net", "Uri"); public static final ClassName URI_MATCHER = ClassName.get("android.content", "UriMatcher"); public static final ClassName CURSOR = ClassName.get("android.database", "Cursor"); public static final ClassName CONTENT_VALUES = ClassName.get("android.content", "ContentValues"); public static final ClassName CONTENT_URIS = ClassName.get("android.content", "ContentUris"); public static final ClassName MODEL_ADAPTER = ClassName.get(STRUCTURE, "ModelAdapter"); public static final ClassName QUERY_MODEL_ADAPTER = ClassName.get(STRUCTURE, "QueryModelAdapter"); public static final ClassName MODEL = ClassName.get(STRUCTURE, "Model"); public static final ClassName MODEL_VIEW_ADAPTER = ClassName.get(STRUCTURE, "ModelViewAdapter"); public static final ClassName MODEL_VIEW = ClassName.get(STRUCTURE, "BaseModelView"); public static final ClassName CONDITION_QUERY_BUILDER = ClassName.get(BUILDER, "ConditionQueryBuilder"); public static final ClassName CONDITION = ClassName.get(BUILDER, "Condition"); public static final ClassName SQL_UTILS = ClassName.get(SQL, "SqlUtils"); public static final ClassName QUERY = ClassName.get(SQL, "Query"); public static final ClassName TYPE_CONVERTER = ClassName.get(CONVERTER, "TypeConverter"); public static final ClassName PROCESS_MODEL_INFO = ClassName.get(PROCESS, "ProcessModelInfo"); public static final ClassName FLOW_MANAGER_STATIC_INTERFACE = ClassName.get(FLOW_MANAGER_PACKAGE, "DatabaseHolder"); public static final ClassName MIGRATION = ClassName.get(MIGRATION_PACKAGE, "Migration"); public static final ClassName CONFLICT_ACTION = ClassName.get(ConflictAction.class); public static final ClassName CONTENT_VALUES_LISTENER = ClassName.get(LISTENER, "ContentValuesListener"); public static final ClassName LOAD_FROM_CURSOR_LISTENER = ClassName.get(LISTENER, "LoadFromCursorListener"); public static final ClassName SQLITE_STATEMENT_LISTENER = ClassName.get(LISTENER, "SQLiteStatementListener"); public static final ClassName DELETE_MODEL_LIST_TRANSACTION = ClassName.get(PROCESS, "DeleteModelListTransaction"); public static final ClassName SAVE_MODEL_LIST_TRANSACTION = ClassName.get(PROCESS, "SaveModelTransaction"); public static final ClassName UPDATE_MODEL_LIST_TRANSACTION = ClassName.get(PROCESS, "UpdateModelListTransaction"); public static final ClassName INSERT_MODEL_LIST_TRANSACTION = ClassName.get(PROCESS, "InsertModelTransaction"); public static final ClassName PROPERTY = ClassName.get(PROPERTY_PACKAGE, "Property"); public static final ClassName IPROPERTY = ClassName.get(PROPERTY_PACKAGE, "IProperty"); public static final ClassName BASE_PROPERTY = ClassName.get(PROPERTY_PACKAGE, "BaseProperty"); public static final ClassName INDEX_PROPERTY = ClassName.get(PROPERTY_PACKAGE, "IndexProperty"); public static final ClassName CONDITION_GROUP = ClassName.get(LANGUAGE, "ConditionGroup"); public static final ClassName SELECT = ClassName.get(LANGUAGE, "Select"); public static final ClassName UPDATE = ClassName.get(LANGUAGE, "Update"); public static final ClassName DELETE = ClassName.get(LANGUAGE, "Delete"); public static final ClassName METHOD = ClassName.get(LANGUAGE, "Method"); public static final ClassName BASE_CONTENT_PROVIDER = ClassName.get(RUNTIME, "BaseContentProvider"); public static final ClassName PROPERTY_CONVERTER = ClassName.get(RUNTIME + ".BaseContentProvider", "PropertyConverter"); public static final ClassName MODEL_CONTAINER_UTILS = ClassName.get(CONTAINER, "ModelContainerUtils"); public static final ClassName MODEL_CONTAINER = ClassName.get(CONTAINER, "ModelContainer"); public static final ClassName MODEL_CONTAINER_ADAPTER = ClassName.get(CONTAINER, "ModelContainerAdapter"); public static final ClassName FOREIGN_KEY_CONTAINER = ClassName.get(CONTAINER, "ForeignKeyContainer"); public static final ClassName BASE_MODEL = ClassName.get(STRUCTURE, "BaseModel"); public static final ClassName MODEL_CACHE = ClassName.get(STRUCTURE + ".cache", "ModelCache"); public static final ClassName MULTI_KEY_CACHE_CONVERTER = ClassName.get(STRUCTURE + ".cache", "IMultiKeyCacheConverter"); }
private DeriveResult<DerivedCodeSpec> visitorDispatchImpl( VariableElement visitorParam, DeclaredType visitorType, List<DataConstructor> constructors) { NameAllocator nameAllocator = nameAllocator(constructors); TypeSpec wrapper = TypeSpec.anonymousClassBuilder("") .addField( FieldSpec.builder(TypeName.get(visitorType), nameAllocator.get("cata")) .initializer( CodeBlock.builder() .addStatement( "$T.$L($L)", ClassName.get(context.targetPackage(), context.targetClassName()), MapperDerivator.visitorLambdaFactoryName(adt), Utils.joinStringsAsArguments( constructors .stream() .map( constructor -> constructor .arguments() .stream() .map(DataArguments::getType) .noneMatch( tm -> utils .types() .isSameType( tm, adt.typeConstructor() .declaredType())) ? constructor.name() : CodeBlock.builder() .add( "($L) -> $L.$L($L)", Utils.asLambdaParametersString( constructor.arguments(), constructor.typeRestrictions()), constructor.name(), MapperDerivator.mapperApplyMethod( utils, context, constructor), Utils.joinStringsAsArguments( Stream.concat( constructor .arguments() .stream() .map( argument -> utils .types() .isSameType( argument .type(), adt.typeConstructor() .declaredType()) ? "() -> " + argument .fieldName() + "." + adt.matchMethod() .element() .getSimpleName() + "(this." + nameAllocator .get( "cata") + ")" : argument .fieldName()), constructor .typeRestrictions() .stream() .map( TypeRestriction ::idFunction) .map( DataArgument ::fieldName)))) .build() .toString()))) .build()) .build()) .build(); MethodSpec cataMethod = MethodSpec.methodBuilder("cata") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addTypeVariables( Stream.concat( adt.typeConstructor().typeVariables().stream(), Stream.of(adt.matchMethod().returnTypeVariable())) .map(TypeVariableName::get) .collect(Collectors.toList())) .returns( TypeName.get( utils .types() .getDeclaredType( FlavourImpl.findF(context.flavour(), utils.elements()), adt.typeConstructor().declaredType(), adt.matchMethod().returnTypeVariable()))) .addParameters( constructors .stream() .map( dc -> ParameterSpec.builder( cataMapperTypeName(dc), MapperDerivator.mapperFieldName(dc)) .build()) .collect(toList())) .addStatement( "$T $L = $L.$L", TypeName.get(visitorType), nameAllocator.get("cata"), wrapper, nameAllocator.get("cata")) .addStatement( "return $L -> $L.$L($L)", nameAllocator.get("adt var"), nameAllocator.get("adt var"), adt.matchMethod().element().getSimpleName(), nameAllocator.get("cata")) .build(); return result(methodSpec(cataMethod)); }
public class AutoBundleWriter { private final AutoBundleBindingClass bindingClass; private static final String FIELD_BUNDLE_NAME = "args"; private static final ClassName CLASS_BUNDLE = ClassName.get("android.os", "Bundle"); public AutoBundleWriter(AutoBundleBindingClass target) { this.bindingClass = target; } public void write(Filer filer) throws IOException { TypeSpec clazz = TypeSpec.classBuilder(bindingClass.getHelperClassName()) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addType(createBuilderClass(bindingClass)) .addMethod(createCallBuilderMethod(bindingClass)) .addMethod(createBindMethod(bindingClass)) .addMethod(createBindWithSourceMethod(bindingClass)) .addMethod(createPackMethod(bindingClass)) .build(); JavaFile.builder(bindingClass.getPackageName(), clazz).build().writeTo(filer); } private static MethodSpec createCallBuilderMethod(AutoBundleBindingClass target) { ClassName builderClass = ClassName.get(target.getPackageName(), target.getBuilderClassName()); MethodSpec.Builder builder = MethodSpec.methodBuilder("create" + target.getBuilderType().name() + "Builder") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(builderClass) .addCode("return new $T(", builderClass); for (int i = 0, count = target.getRequiredArgs().size(); i < count; i++) { if (i > 0) { builder.addCode(","); } AutoBundleBindingField arg = target.getRequiredArgs().get(i); builder.addParameter(arg.getArgType(), arg.getArgKey()).addCode("$N", arg.getArgKey()); } return builder.addCode(");\n").build(); } private static TypeSpec createBuilderClass(AutoBundleBindingClass target) { return TypeSpec.classBuilder(target.getBuilderClassName()) .addModifiers(Modifier.PUBLIC, Modifier.FINAL, Modifier.STATIC) .addField(createField(FIELD_BUNDLE_NAME)) .addMethod(createBuilderConstructor(target, FIELD_BUNDLE_NAME)) .addMethods(createBuilderMethods(target, FIELD_BUNDLE_NAME)) .addMethods(createBuildMethods(target, FIELD_BUNDLE_NAME)) .build(); } private static MethodSpec createBuilderConstructor( AutoBundleBindingClass target, String fieldName) { MethodSpec.Builder builder = MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC) .addStatement("this.$N = new $T()", fieldName, CLASS_BUNDLE); for (AutoBundleBindingField arg : target.getRequiredArgs()) { String key = arg.getArgKey(); TypeName type = arg.getArgType(); String operationName = arg.getOperationName("put"); builder.addParameter(type, key); if (arg.hasCustomConverter()) { TypeName converter = arg.getConverter(); builder .addStatement("$T $NConverter = new $T()", converter, key, converter) .addStatement( "this.$N.$N($S, $NConverter.convert($N))", fieldName, operationName, key, key, key); } else { builder.addStatement("this.$N.$N($S, $N)", fieldName, operationName, key, key); } } return builder.build(); } private static FieldSpec createField(String fieldName) { return FieldSpec.builder(CLASS_BUNDLE, fieldName, Modifier.FINAL).build(); } private static List<MethodSpec> createBuilderMethods( AutoBundleBindingClass target, String fieldName) { List<MethodSpec> methodSpecs = new ArrayList<>(); for (AutoBundleBindingField arg : target.getNotRequiredArgs()) { String argKey = arg.getArgKey(); TypeName argType = arg.getArgType(); String operationName = arg.getOperationName("put"); MethodSpec.Builder builder = MethodSpec.methodBuilder(argKey) .addModifiers(Modifier.PUBLIC) .addParameter(argType, argKey) .returns(ClassName.get(target.getPackageName(), target.getBuilderClassName())); if (arg.hasCustomConverter()) { TypeName converter = arg.getConverter(); builder .addStatement("$T $NConverter = new $T()", converter, argKey, converter) .addStatement( "$N.$N($S, $NConverter.convert($N))", fieldName, operationName, argKey, argKey, argKey); } else { builder.addStatement("$N.$N($S, $N)", fieldName, operationName, argKey, argKey); } builder.addStatement("return this"); methodSpecs.add(builder.build()); } return methodSpecs; } private static List<MethodSpec> createBuildMethods( AutoBundleBindingClass target, String fieldName) { if (target.getBuilderType() == AutoBundleBindingClass.BuilderType.Fragment) { return createFragmentBuildMethods(target, fieldName); } else { return createIntentBuildMethods(target, fieldName); } } private static List<MethodSpec> createFragmentBuildMethods( AutoBundleBindingClass target, String fieldName) { List<MethodSpec> methodSpecs = new ArrayList<>(2); ClassName targetClass = target.getTargetType(); MethodSpec buildWithNoParam = MethodSpec.methodBuilder("build") .addModifiers(Modifier.PUBLIC) .returns(targetClass) .addStatement("$T fragment = new $T()", targetClass, targetClass) .addStatement("fragment.setArguments($N)", fieldName) .addStatement("return fragment") .build(); MethodSpec buildWithFragment = MethodSpec.methodBuilder("build") .addModifiers(Modifier.PUBLIC) .addParameter(targetClass, "fragment") .returns(targetClass) .addStatement("fragment.setArguments($N)", fieldName) .addStatement("return fragment") .build(); methodSpecs.add(buildWithNoParam); methodSpecs.add(buildWithFragment); return methodSpecs; } private static List<MethodSpec> createIntentBuildMethods( AutoBundleBindingClass target, String fieldName) { List<MethodSpec> methodSpecs = new ArrayList<>(2); ClassName contextClass = ClassName.get("android.content", "Context"); ClassName intentClass = ClassName.get("android.content", "Intent"); MethodSpec buildWithContext = MethodSpec.methodBuilder("build") .addModifiers(Modifier.PUBLIC) .addParameter(contextClass, "context") .returns(intentClass) .addStatement( "$T intent = new $T(context, $T.class)", intentClass, intentClass, target.getTargetType()) .addStatement("intent.putExtras($N)", fieldName) .addStatement("return intent") .build(); MethodSpec buildWithIntent = MethodSpec.methodBuilder("build") .addModifiers(Modifier.PUBLIC) .addParameter(intentClass, "intent") .returns(intentClass) .addStatement("intent.putExtras($N)", fieldName) .addStatement("return intent") .build(); methodSpecs.add(buildWithContext); methodSpecs.add(buildWithIntent); return methodSpecs; } private static MethodSpec createBindWithSourceMethod(AutoBundleBindingClass target) { List<AutoBundleBindingField> args = new ArrayList<>(); args.addAll(target.getRequiredArgs()); args.addAll(target.getNotRequiredArgs()); MethodSpec.Builder builder = MethodSpec.methodBuilder("bind") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(void.class) .addParameter(target.getTargetType(), "target") .addParameter(CLASS_BUNDLE, "source"); for (AutoBundleBindingField arg : args) { String key = arg.getArgKey(); String fieldName = arg.getFieldName(); TypeName argType = arg.getArgType(); String operationName = arg.getOperationName("get"); builder.beginControlFlow("if (source.containsKey($S))", key); if (arg.hasCustomConverter()) { TypeName converter = arg.getConverter(); builder .addStatement("$T $NConverter = new $T()", converter, key, converter) .addStatement( "target.$N = ($T) $NConverter.original(source.$N($S))", fieldName, argType, key, operationName, key); } else { if (arg.noCast()) { builder.addStatement("target.$N = source.$N($S)", fieldName, operationName, key); } else { builder.addStatement( "target.$N = ($T) source.$N($S)", fieldName, argType, operationName, key); } } if (arg.isRequired()) { String exceptionMessage = String.format("%s is required, but not found in the bundle.", key); builder .nextControlFlow("else") .addStatement("throw new IllegalStateException($S)", exceptionMessage); } builder.endControlFlow(); } return builder.build(); } private static MethodSpec createBindMethod(AutoBundleBindingClass target) { MethodSpec.Builder builder = MethodSpec.methodBuilder("bind") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(void.class) .addParameter(target.getTargetType(), "target"); switch (target.getBuilderType()) { case Fragment: builder.addStatement("bind(target, target.getArguments())"); break; case Intent: builder.addParameter(ClassName.get("android.content", "Intent"), "intent"); builder .beginControlFlow("if (intent.getExtras() != null)") .addStatement("bind(target, intent.getExtras())") .endControlFlow(); break; } return builder.build(); } private static MethodSpec createPackMethod(AutoBundleBindingClass target) { List<AutoBundleBindingField> args = new ArrayList<>(); args.addAll(target.getRequiredArgs()); args.addAll(target.getNotRequiredArgs()); MethodSpec.Builder builder = MethodSpec.methodBuilder("pack") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(void.class) .addParameter(target.getTargetType(), "source") .addParameter(CLASS_BUNDLE, "args"); for (AutoBundleBindingField arg : args) { String key = arg.getArgKey(); String fieldName = arg.getFieldName(); TypeName argType = arg.getArgType(); String operationName = arg.getOperationName("put"); if (!argType.isPrimitive()) { String exceptionMessage = String.format("%s must not be null.", fieldName); builder .beginControlFlow("if (source.$N == null)", fieldName) .addStatement("throw new IllegalStateException($S)", exceptionMessage) .endControlFlow(); } if (arg.hasCustomConverter()) { TypeName converter = arg.getConverter(); builder .addStatement("$T $NConverter = new $T()", converter, key, converter) .addStatement( "args.$N($S, $NConverter.convert(source.$N))", operationName, key, key, fieldName); } else { builder.addStatement("args.$N($S, source.$N)", operationName, key, fieldName); } } return builder.build(); } }
public ClassName getClassName() { return ClassName.get(packageName, className); }
@Override public void onWriteDefinition(TypeSpec.Builder typeBuilder) { typeBuilder.addField( FieldSpec.builder( ClassName.get(String.class), AUTHORITY, Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL) .initializer("$S", authority) .build()); int code = 0; for (TableEndpointDefinition endpointDefinition : endpointDefinitions) { for (ContentUriDefinition contentUriDefinition : endpointDefinition.contentUriDefinitions) { typeBuilder.addField( FieldSpec.builder( TypeName.INT, contentUriDefinition.name, Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL) .initializer(String.valueOf(code)) .build()); code++; } } FieldSpec.Builder uriField = FieldSpec.builder( ClassNames.URI_MATCHER, URI_MATCHER, Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL); CodeBlock.Builder initializer = CodeBlock.builder() .addStatement("new $T($T.NO_MATCH)", ClassNames.URI_MATCHER, ClassNames.URI_MATCHER) .add("static {\n"); for (TableEndpointDefinition endpointDefinition : endpointDefinitions) { for (ContentUriDefinition contentUriDefinition : endpointDefinition.contentUriDefinitions) { String path; if (contentUriDefinition.path != null) { path = "\"" + contentUriDefinition.path + "\""; } else { path = CodeBlock.builder() .add( "$L.$L.getPath()", contentUriDefinition.elementClassName, contentUriDefinition.name) .build() .toString(); } initializer.addStatement( "$L.addURI($L, $L, $L)", URI_MATCHER, AUTHORITY, path, contentUriDefinition.name); } } initializer.add("}\n"); typeBuilder.addField(uriField.initializer(initializer.build()).build()); typeBuilder.addMethod( MethodSpec.methodBuilder("getDatabaseName") .addAnnotation(Override.class) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addStatement("return $S", databaseNameString) .returns(ClassName.get(String.class)) .build()); MethodSpec.Builder getTypeBuilder = MethodSpec.methodBuilder("getType") .addAnnotation(Override.class) .addParameter(ClassNames.URI, "uri") .returns(ClassName.get(String.class)) .addModifiers(Modifier.PUBLIC, Modifier.FINAL); CodeBlock.Builder getTypeCode = CodeBlock.builder() .addStatement("$T type = null", ClassName.get(String.class)) .beginControlFlow("switch($L.match(uri))", URI_MATCHER); for (TableEndpointDefinition tableEndpointDefinition : endpointDefinitions) { for (ContentUriDefinition uriDefinition : tableEndpointDefinition.contentUriDefinitions) { getTypeCode .beginControlFlow("case $L:", uriDefinition.name) .addStatement("type = $S", uriDefinition.type) .addStatement("break") .endControlFlow(); } } getTypeCode .beginControlFlow("default:") .addStatement( "throw new $T($S + $L)", ClassName.get(IllegalArgumentException.class), "Unknown URI", "uri") .endControlFlow(); getTypeCode.endControlFlow(); getTypeCode.addStatement("return type"); getTypeBuilder.addCode(getTypeCode.build()); typeBuilder.addMethod(getTypeBuilder.build()); for (MethodDefinition method : methods) { MethodSpec methodSpec = method.getMethodSpec(); if (methodSpec != null) { typeBuilder.addMethod(methodSpec); } } }
public List<MethodSpec> buildMethodSpecs() { List<MethodSpec> methodSpecs = new ArrayList<>(); List<AnnotationSpec> overrideAndNonNull = Arrays.asList(Specs.buildNonNullAnnotationSpec(), Specs.buildOverrideAnnotationSpec()); List<AnnotationSpec> overrideAndNullable = Arrays.asList(Specs.buildNullableAnnotationSpec(), Specs.buildOverrideAnnotationSpec()); methodSpecs.add( MethodSpec.methodBuilder("getModelClass") .addAnnotations(overrideAndNonNull) .addModifiers(Modifier.PUBLIC) .returns( ParameterizedTypeName.get(ClassName.get(Class.class), schema.getModelClassName())) .addStatement("return $T.class", schema.getModelClassName()) .build()); methodSpecs.add( MethodSpec.methodBuilder("getTableName") .addAnnotations(overrideAndNonNull) .addModifiers(Modifier.PUBLIC) .returns(Types.String) .addStatement("return $L", TABLE_NAME) .build()); methodSpecs.add( MethodSpec.methodBuilder("getPrimaryKey") .addAnnotations(overrideAndNonNull) .addModifiers(Modifier.PUBLIC) .returns(Types.WildcardColumnDef) .addStatement("return $N", primaryKey) .build()); methodSpecs.add( MethodSpec.methodBuilder("getColumns") .addAnnotations(overrideAndNonNull) .addModifiers(Modifier.PUBLIC) .returns(Types.ColumnList) .addStatement("return $L", COLUMNS) .build()); methodSpecs.add( MethodSpec.methodBuilder("getEscapedColumnNames") .addAnnotations(overrideAndNonNull) .addModifiers(Modifier.PUBLIC) .returns(Types.StringArray) .addStatement("return $L", ESCAPED_COLUMN_NAMES) .build()); methodSpecs.add( MethodSpec.methodBuilder("getCreateTableStatement") .addAnnotations(overrideAndNonNull) .addModifiers(Modifier.PUBLIC) .returns(Types.String) .addStatement("return $S", sql.buildCreateTableStatement(schema)) .build()); methodSpecs.add( MethodSpec.methodBuilder("getCreateIndexStatements") .addAnnotations(overrideAndNonNull) .addModifiers(Modifier.PUBLIC) .returns(Types.getList(Types.String)) .addCode(sql.buildCreateIndexStatements(schema)) .build()); methodSpecs.add( MethodSpec.methodBuilder("getDropTableStatement") .addAnnotations(overrideAndNonNull) .addModifiers(Modifier.PUBLIC) .returns(Types.String) .addStatement("return $S", sql.buildDropTableStatement(schema)) .build()); methodSpecs.add( MethodSpec.methodBuilder("getInsertStatement") .addAnnotations(overrideAndNonNull) .addModifiers(Modifier.PUBLIC) .returns(Types.String) .addStatement("return $S", sql.buildInsertStatement(schema)) .build()); methodSpecs.add( MethodSpec.methodBuilder("bindArgs") .addModifiers(Modifier.PUBLIC) .returns(TypeName.VOID) .addParameter( ParameterSpec.builder(Types.OrmaConnection, "conn") .addAnnotation(Specs.buildNonNullAnnotationSpec()) .build()) .addParameter( ParameterSpec.builder(Types.SQLiteStatement, "statement") .addAnnotation(Specs.buildNonNullAnnotationSpec()) .build()) .addParameter( ParameterSpec.builder(schema.getModelClassName(), "model") .addAnnotation(Specs.buildNonNullAnnotationSpec()) .build()) .addCode(buildBindArgs()) .build()); methodSpecs.add( MethodSpec.methodBuilder("createModelFromCursor") .addAnnotations(overrideAndNonNull) .addModifiers(Modifier.PUBLIC) .returns(schema.getModelClassName()) .addParameter( ParameterSpec.builder(Types.OrmaConnection, "conn") .addAnnotation(Specs.buildNonNullAnnotationSpec()) .build()) .addParameter( ParameterSpec.builder(Types.Cursor, "cursor") .addAnnotation(Specs.buildNonNullAnnotationSpec()) .build()) .addCode(buildCreateModelFromCursor()) .build()); return methodSpecs; }