use of com.squareup.javapoet.TypeSpec.Builder in project kripton by xcesco.
the class BindSharedPreferencesBuilder method generate.
/**
* Generate shared preference manager.
*
* @param elementUtils
* the element utils
* @param filer
* the filer
* @param entity
* the entity
* @return typeName of generated class
* @throws IOException
* Signals that an I/O exception has occurred.
*/
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.getElement().getSimpleName().toString();
String className = getBuildPreferenceName(entity);
ModelAnnotation annotation = entity.getAnnotation(BindSharedPreferences.class);
String sharedPreferenceName = annotation.getAttribute(AnnotationAttributeType.VALUE);
boolean generateRx = entity.hasRxProperties();
boolean generateLiveData = entity.hasLiveDataProperties();
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, Modifier.STATIC);
// @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);
generateCreate(sharedPreferenceName, beanClassName, generateRx, generateLiveData);
generateConstructor(entity, sharedPreferenceName, beanClassName);
generateRefresh(sharedPreferenceName, className);
generateRxSupport(sharedPreferenceName, beanClassName, generateRx, entity);
generateLiveDataSupport(sharedPreferenceName, beanClassName, generateLiveData, entity);
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.squareup.javapoet.TypeSpec.Builder in project kripton by xcesco.
the class BindSharedPreferencesBuilder method generateLiveDataSupport.
private static void generateLiveDataSupport(String sharedPreferenceName, String beanClassName, boolean generateLiveData, PrefsEntity entity) {
if (!generateLiveData)
return;
// generate livedata collections
FieldSpec fs = FieldSpec.builder(ParameterizedTypeName.get(ClassName.get(List.class), ParameterizedTypeName.get(ClassName.get(Pair.class), ClassName.get(String.class), ParameterizedTypeName.get(ClassName.get(WeakReference.class), ClassName.get(LiveDataHandler.class)))), "liveDatas", Modifier.PRIVATE).initializer(CodeBlock.of("new $T<$T<String, WeakReference<$T>>>()", CopyOnWriteArrayList.class, Pair.class, LiveDataHandler.class)).addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "\"rawtypes\"").build()).build();
builder.addField(fs);
{
// registryLiveData
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("registryLiveData").addModifiers(Modifier.PROTECTED).addParameter(String.class, "key").addParameter(ClassName.get(LiveDataHandler.class), "value").addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "\"rawtypes\"").build()).addStatement("liveDatas.add(new Pair<String , WeakReference<$T>>(key, new WeakReference<$T>(value)))", LiveDataHandler.class, LiveDataHandler.class);
builder.addMethod(methodBuilder.build());
}
{
// update LiveData
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("updateLiveData").addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "\"rawtypes\"").build()).addModifiers(Modifier.PROTECTED).addParameter(String.class, "key").addParameter(Object.class, "value").beginControlFlow("for (Pair<String, WeakReference<$T>> item : liveDatas)", LiveDataHandler.class).beginControlFlow("if (item.value0.equals(key) && item.value1.get() != null)").addStatement("item.value1.get().invalidate()").endControlFlow().endControlFlow();
builder.addMethod(methodBuilder.build());
}
Converter<String, String> converter = CaseFormat.LOWER_CAMEL.converterTo(CaseFormat.UPPER_CAMEL);
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("onSharedPreferenceChanged").addAnnotation(Override.class).addModifiers(Modifier.PUBLIC).addParameter(SharedPreferences.class, "sharedPreferences", Modifier.FINAL).addParameter(String.class, "key", Modifier.FINAL);
{
// inner method run
MethodSpec.Builder runBuilder = MethodSpec.methodBuilder("run").addModifiers(Modifier.PUBLIC).addAnnotation(Override.class);
// ----
runBuilder.beginControlFlow("switch (key)");
PrefsTransform transform;
TypeName typeName;
for (PrefsProperty item : entity.getCollection()) {
if (!item.isGenerateLiveData())
continue;
if (item.hasTypeAdapter()) {
transform = PrefsTransformer.lookup(item.typeAdapter.getDataTypeTypename());
} else {
transform = PrefsTransformer.lookup(item);
}
typeName = item.getPropertyType().getTypeName();
if (TypeUtility.isTypePrimitive(typeName)) {
typeName = typeName.box();
}
generateMethodAsLiveData(converter, typeName, item);
runBuilder.addComment("$L - $L", item.getPreferenceKey(), item.getName());
runBuilder.addCode("case $S: {\n", item.getPreferenceKey());
transform.generateReadProperty(runBuilder, "sharedPreferences", typeName(item.getElement().asType()), "defaultBean", item, false, ReadType.VALUE);
runBuilder.addCode("\n");
runBuilder.addStatement("updateLiveData($S, _value)", item.getPreferenceKey());
runBuilder.addStatement("return");
runBuilder.addCode("}\n");
}
runBuilder.addStatement("default: return");
runBuilder.endControlFlow();
// ----
{
// run builder
TypeSpec innerBuilder = TypeSpec.anonymousClassBuilder("").addSuperinterface(Runnable.class).addMethod(runBuilder.build()).build();
methodBuilder.addStatement("$T.getExecutorService().execute($L)", KriptonLibrary.class, innerBuilder);
}
}
TypeSpec innerBuilder = TypeSpec.anonymousClassBuilder("").addSuperinterface(OnSharedPreferenceChangeListener.class).addMethod(methodBuilder.build()).build();
FieldSpec.Builder f = FieldSpec.builder(ClassName.get(OnSharedPreferenceChangeListener.class), "liveDataListener", Modifier.PRIVATE).addJavadoc("Listener used to propagate shared prefs changes through RX\n").initializer("$L", innerBuilder);
builder.addField(f.build());
}
use of com.squareup.javapoet.TypeSpec.Builder in project kripton by xcesco.
the class BindTypeBuilder method generate.
/**
* Generate.
*
* @param filer
* the filer
* @param item
* the item
* @return typeName of generated class
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public static String generate(Filer filer, BindEntity item) throws IOException {
Elements elementUtils = BaseProcessor.elementUtils;
String beanClassName = item.getSimpleName();
boolean needSuffix = true;
if (beanClassName.endsWith(SUFFIX)) {
needSuffix = false;
}
String className = PREFIX + beanClassName + (needSuffix ? SUFFIX : "");
PackageElement pkg = elementUtils.getPackageOf(item.getElement());
String packageName = pkg.isUnnamed() ? "" : pkg.getQualifiedName().toString();
AnnotationProcessorUtilis.infoOnGeneratedClasses(BindType.class, packageName, className);
// @formatter:off
TypeSpec.Builder builder = TypeSpec.classBuilder(className).addAnnotation(AnnotationSpec.builder(BindMap.class).addMember("value", "$T.class", typeName(item.getElement().asType())).build()).addModifiers(Modifier.PUBLIC).superclass(TypeUtility.parameterizedTypeName(className(AbstractMapper.class), typeName(item.getElement().asType())));
BindTypeContext context = new BindTypeContext(builder, TypeUtility.typeName(packageName, className), Modifier.PRIVATE);
// @formatter:on
builder.addJavadoc("This class is binder map for $T\n\n", item.getElement());
JavadocUtility.generateJavadocGeneratedBy(builder);
builder.addJavadoc("@see $T\n", item.getElement());
// order item by order, property typeName
item.getCollection().sort(Comparator.comparingInt((BindProperty lhs) -> lhs.order).thenComparing(ModelEntity::getName));
// generate serializeOnJackson
generateSerializeOnJackson(context, item);
// generate serializeOnJacksonAsString
generateSerializeOnJacksonAsString(context, item);
// order item by type (attribute, element, value), order, xmlName
item.getCollection().sort(Comparator.comparingInt((BindProperty lhs) -> lhs.xmlInfo.xmlType.ordinal()).thenComparingInt(lhs -> lhs.order).thenComparing(lhs -> lhs.label));
// generate serializeOnXml
generateSerializeOnXml(context, item);
// generate parseOnJackson
generateParseOnJackson(context, item);
// generate parseOnJacksonAsString
generateParseOnJacksonAsString(context, item);
// generate parseOnXml
generateParseOnXml(context, item);
// initializate binders and generate method
generateBinderInit(context.builder, context.initBuilder, item);
builder.addMethod(context.initBuilder.build());
TypeSpec typeSpec = builder.build();
JavaWriterHelper.writeJava2File(filer, packageName, typeSpec);
return className;
}
use of com.squareup.javapoet.TypeSpec.Builder in project kripton by xcesco.
the class SqlSelectBuilder method generateSelectForContentProvider.
/**
* <p>
* Generate select used in content provider class.
* </p>
*
* @param builder
* the builder
* @param method
* the method
* @param selectResultType
* the select result type
*/
private static void generateSelectForContentProvider(Builder builder, final SQLiteModelMethod method, SelectType selectResultType) {
final SQLiteDaoDefinition daoDefinition = method.getParent();
final SQLiteEntity entity = method.getEntity();
final Set<String> columns = new LinkedHashSet<>();
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(method.contentProviderMethodName);
if (!method.getParent().hasSamePackageOfSchema()) {
methodBuilder.addModifiers(Modifier.PUBLIC);
}
// params
methodBuilder.addParameter(ParameterSpec.builder(Uri.class, "uri").build());
methodBuilder.addParameter(ParameterSpec.builder(ArrayTypeName.of(String.class), "projection").build());
methodBuilder.addParameter(ParameterSpec.builder(String.class, "selection").build());
methodBuilder.addParameter(ParameterSpec.builder(ArrayTypeName.of(String.class), "selectionArgs").build());
methodBuilder.addParameter(ParameterSpec.builder(String.class, "sortOrder").build());
methodBuilder.returns(Cursor.class);
SqlBuilderHelper.generateLogForContentProviderBeginning(method, methodBuilder);
JQLChecker jqlChecker = JQLChecker.getInstance();
SplittedSql splittedSql = generateSQL(method, methodBuilder, true);
List<JQLPlaceHolder> placeHolders = jqlChecker.extractFromVariableStatement(method, splittedSql.sqlWhereStatement);
// remove placeholder for dynamic where, we are not interested here
placeHolders = SqlBuilderHelper.removeDynamicPlaceHolder(placeHolders);
AssertKripton.assertTrue(placeHolders.size() == method.contentProviderUriVariables.size(), "In '%s.%s' content provider URI path variables and variables in where conditions are different. If SQL uses parameters, they must be defined in URI path.", daoDefinition.getName(), method.getName());
Set<JQLProjection> projectedColumns = jqlChecker.extractProjections(method, method.jql.value, entity);
for (JQLProjection item : projectedColumns) {
if (item.type == ProjectionType.COLUMN) {
if (item.alias != null) {
columns.add(entity.get(item.alias.trim()).columnName);
} else {
columns.add(entity.get(item.column.trim()).columnName);
}
} else {
columns.add(item.expression.trim());
}
}
methodBuilder.addStatement("$T _contentValues=contentValues()", KriptonContentValues.class);
methodBuilder.addStatement("$T _sqlBuilder=sqlBuilder()", StringBuilder.class);
SqlModifyBuilder.generateInitForDynamicWhereVariables(method, methodBuilder, "selection", "selectionArgs");
methodBuilder.addStatement("$T _projectionBuffer=new $T()", StringBuilder.class, StringBuilder.class);
if (method.jql.isOrderBy()) {
methodBuilder.addStatement("String _sortOrder=sortOrder");
}
methodBuilder.addStatement("_sqlBuilder.append($S)", splittedSql.sqlBasic);
SqlBuilderHelper.generateWhereCondition(methodBuilder, method, false);
generateDynamicPartOfQuery(method, methodBuilder, splittedSql, false, "paginatedResult");
// generate and check columns
{
methodBuilder.addCode("\n// manage projected columns\n");
methodBuilder.addStatement("String _columnSeparator=\"\"");
methodBuilder.beginControlFlow("if (projection!=null && projection.length>0)");
// generate projected column check
String columnCheckSetName = SqlBuilderHelper.generateColumnCheckSet(builder, method, columns);
SqlBuilderHelper.forEachColumnInContentValue(methodBuilder, method, "projection", true, new OnColumnListener() {
@Override
public void onColumnCheck(MethodSpec.Builder methodBuilder, String projectedColumnVariable) {
methodBuilder.addStatement("_projectionBuffer.append(_columnSeparator + $L)", projectedColumnVariable);
methodBuilder.addStatement("_columnSeparator=\", \"");
}
});
methodBuilder.nextControlFlow("else");
methodBuilder.beginControlFlow("for (String column: $L)", columnCheckSetName);
methodBuilder.addStatement("_projectionBuffer.append(_columnSeparator + column)");
methodBuilder.addStatement("_columnSeparator=\", \"");
methodBuilder.endControlFlow();
methodBuilder.endControlFlow();
int i = 0;
// every controls was done in constructor of SQLiteModelMethod
for (ContentUriPlaceHolder variable : method.contentProviderUriVariables) {
AssertKripton.assertTrue(SqlBuilderHelper.validate(variable.value, placeHolders, i), "In '%s.%s' content provider URI path and where conditions must use same set of variables", daoDefinition.getName(), method.getName());
SQLProperty entityProperty = entity.get(variable.value);
TypeName methodParameterType = method.findParameterTypeByAliasOrName(variable.value);
methodBuilder.addCode("// Add parameter $L at path segment $L\n", variable.value, variable.pathSegmentIndex);
// methodBuilder.addStatement("_sqlWhereParams.add(uri.getPathSegments().get($L))",
// variable.pathSegmentIndex);
methodBuilder.addStatement("_contentValues.addWhereArgs(uri.getPathSegments().get($L))", variable.pathSegmentIndex);
if (entityProperty != null) {
AssertKripton.assertTrue(TypeUtility.isTypeIncludedIn(entityProperty.getPropertyType().getTypeName(), String.class, Long.class, Long.TYPE), "In '%s.%s' content provider URI path variables %s must be String of Long type", daoDefinition.getName(), method.getName(), entityProperty.getName());
} else if (methodParameterType != null) {
AssertKripton.assertTrue(TypeUtility.isTypeIncludedIn(methodParameterType, String.class, Long.class, Long.TYPE), "In '%s.%s' content provider URI path variables %s must be String of Long type", daoDefinition.getName(), method.getName(), method.findParameterNameByAlias(variable.value));
}
i++;
}
}
// _sql must be always defined
methodBuilder.addStatement("String _sql=String.format(_sqlBuilder.toString(), _projectionBuffer.toString())");
SqlBuilderHelper.generateLogForSQL(method, methodBuilder);
SqlBuilderHelper.generateLogForWhereParameters(method, methodBuilder);
methodBuilder.addCode("\n// execute query\n");
methodBuilder.addStatement("Cursor _result = getDatabase().query(_sql, _contentValues.whereArgsAsArray())");
methodBuilder.addStatement("return _result");
// we add at last javadoc, because need info is built at last.
SqlBuilderHelper.generateJavaDocForContentProvider(method, methodBuilder);
methodBuilder.addJavadoc("@param uri $S\n", method.contentProviderUriTemplate.replace("*", "[*]"));
methodBuilder.addJavadoc("@param selection dynamic part of <code>where</code> statement $L\n", method.hasDynamicWhereConditions() ? "" : "<b>NOT USED</b>");
methodBuilder.addJavadoc("@param selectionArgs arguments of dynamic part of <code>where</code> statement $L\n", method.hasDynamicWhereConditions() ? "" : "<b>NOT USED</b>");
methodBuilder.addJavadoc("@return number of effected rows\n");
builder.addMethod(methodBuilder.build());
}
use of com.squareup.javapoet.TypeSpec.Builder in project aws-sdk-java-v2 by aws.
the class AsyncClientClass method poetSpec.
@Override
public TypeSpec poetSpec() {
ClassName interfaceClass = poetExtensions.getClientClass(model.getMetadata().getAsyncInterface());
Builder classBuilder = PoetUtils.createClassBuilder(className);
classBuilder.addAnnotation(SdkInternalApi.class).addModifiers(Modifier.FINAL).addField(FieldSpec.builder(ClassName.get(Logger.class), "log").addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL).initializer("$T.getLogger($T.class)", LoggerFactory.class, className).build()).addField(AsyncClientHandler.class, "clientHandler", Modifier.PRIVATE, Modifier.FINAL).addField(protocolSpec.protocolFactory(model)).addField(SdkClientConfiguration.class, "clientConfiguration", Modifier.PRIVATE, Modifier.FINAL).addSuperinterface(interfaceClass).addJavadoc("Internal implementation of {@link $1T}.\n\n@see $1T#builder()", interfaceClass).addMethod(constructor(classBuilder)).addMethod(nameMethod()).addMethods(operations()).addMethod(closeMethod()).addMethods(protocolSpec.additionalMethods()).addMethod(protocolSpec.initProtocolFactory(model)).addMethod(resolveMetricPublishersMethod());
// Kinesis doesn't support CBOR for STS yet so need another protocol factory for JSON
if (model.getMetadata().isCborProtocol()) {
classBuilder.addField(AwsJsonProtocolFactory.class, "jsonProtocolFactory", Modifier.PRIVATE, Modifier.FINAL);
}
if (model.hasPaginators()) {
classBuilder.addMethod(applyPaginatorUserAgentMethod(poetExtensions, model));
}
if (model.containsRequestSigners() || model.containsRequestEventStreams() || hasStreamingV4AuthOperations()) {
classBuilder.addMethod(applySignerOverrideMethod(poetExtensions, model));
classBuilder.addMethod(isSignerOverriddenOnClientMethod());
}
if (model.getCustomizationConfig().getUtilitiesMethod() != null) {
classBuilder.addMethod(utilitiesMethod());
}
model.getEndpointOperation().ifPresent(o -> classBuilder.addField(EndpointDiscoveryRefreshCache.class, "endpointDiscoveryCache", PRIVATE));
protocolSpec.createErrorResponseHandler().ifPresent(classBuilder::addMethod);
if (model.hasWaiters()) {
classBuilder.addField(FieldSpec.builder(ClassName.get(ScheduledExecutorService.class), "executorService").addModifiers(PRIVATE, FINAL).build());
classBuilder.addMethod(waiterImplMethod());
}
return classBuilder.build();
}
Aggregations