use of com.squareup.javapoet.ParameterSpec in project raml-module-builder by folio-org.
the class ResourceMethodExtensionPlugin method generateOverrides.
private Builder generateOverrides(String path, String verb, Builder methodSpec) {
// clone the method without the params as we will need to update params with new / updated
// annotations and this cannot be done directly on the method as these lists are immutable
// as java poet allows building code but not editing??
MethodSpec.Builder ret = cloneMethodWithoutParams(methodSpec);
// pull out original params and their annotations from here
MethodSpec spec = methodSpec.build();
// use this list to remove and then update params whose annotations need changing since
// the param list on the method in java poet is immutable this is a workaround
List<ParameterSpec> modifiedParams = new ArrayList<>(spec.parameters);
// check if url has a param / params associated with it that needs overriding
Map<String, JsonObject> overrideEntry = overrideMap.row(path);
if (overrideEntry != null) {
// this endpoint was found in the config file and has an override associated with one of
// its parameters
List<ParameterSpec> paramSpec = spec.parameters;
int[] i = new int[] { 0 };
for (i[0] = 0; i[0] < paramSpec.size(); i[0]++) {
// clone the parameter so we can update it
ParameterSpec.Builder newParam = cloneSingleParamNoAnnotations(paramSpec.get(i[0]));
List<AnnotationSpec> originalAnnotations = getAnnotationsAsModifiableList(paramSpec.get(i[0]));
// remove the param, we need to rebuild it and then add it again
modifiedParams.remove(i[0]);
Set<Entry<String, JsonObject>> entries = overrideEntry.entrySet();
entries.forEach(entry -> {
// iterate through the params of the generated function for this url + verb and look
// for the parameter whose annotation we need to override
JsonObject job = entry.getValue();
String type = job.getString("type");
Object value = job.getValue(ANNOTATION_VALUE);
String paramName = job.getString("paramName");
if (verb.equalsIgnoreCase(job.getString("verb")) && paramName.equalsIgnoreCase(paramSpec.get(i[0]).name)) {
// we need the original annotations so that we can add the ones that were not updated
for (int j = 0; j < originalAnnotations.size(); j++) {
if (originalAnnotations.get(j).type.toString() != null && Enum2Annotation.getAnnotation(type).endsWith(originalAnnotations.get(j).type.toString())) {
originalAnnotations.remove(j);
break;
}
}
try {
AnnotationSpec aSpec = buildAnnotation(Class.forName(Enum2Annotation.getAnnotation(type)), value, type);
originalAnnotations.add(aSpec);
} catch (ClassNotFoundException e) {
log.log(Level.SEVERE, e.getMessage(), e);
}
}
});
newParam.addAnnotations(originalAnnotations);
modifiedParams.add(i[0], newParam.build());
}
}
ret.addParameters(modifiedParams);
return ret;
}
use of com.squareup.javapoet.ParameterSpec in project kripton by xcesco.
the class SelectPaginatedResultHelper method buildSpecializedPagedResultClass.
/**
* Build paginated result class handler.
*
* @param classBuilder
* the class builder
* @param method
* the method
* @return name of generated class
*/
public static String buildSpecializedPagedResultClass(TypeSpec.Builder classBuilder, SQLiteModelMethod method) {
// TypeName entityTypeName =
// TypeUtility.typeName(method.getParent().getEntityClassName());
TypeName entityTypeName = TypeUtility.typeName(method.getEntity().getName());
String pagedResultName = "PaginatedResult" + (pagedResultCounter++);
TypeSpec.Builder typeBuilder = TypeSpec.classBuilder(pagedResultName).addModifiers(Modifier.PUBLIC).superclass(TypeUtility.parameterizedTypeName(TypeUtility.className(PagedResultImpl.class), entityTypeName));
// add fields and define constructor
MethodSpec.Builder setupBuilder = MethodSpec.constructorBuilder();
MethodSpec.Builder executeBuilder = MethodSpec.methodBuilder("execute").addModifiers(Modifier.PUBLIC).returns(TypeUtility.parameterizedTypeName(TypeUtility.className(List.class), entityTypeName));
executeBuilder.addComment("Executor builder - BEGIN");
// method for execution with pageRequest
// @formatter:off
ClassName dataSourceClassName = BindDataSourceBuilder.generateDataSourceName(method.getParent().getParent());
MethodSpec.Builder executeWithPageRequestBuilder = MethodSpec.methodBuilder("execute").addModifiers(Modifier.PUBLIC).addParameter(PageRequest.class, "pageRequest").returns(TypeUtility.parameterizedTypeName(TypeUtility.className(List.class), entityTypeName));
executeWithPageRequestBuilder.addComment("Executor with pageRequet - BEGIN");
executeWithPageRequestBuilder.addCode("return $T.getInstance().executeBatch(daoFactory -> daoFactory.get$L().$L" + SelectPaginatedResultHelper.WITH_PAGE_REQUEST_PREFIX + "(", dataSourceClassName, method.getParentName(), method.getName());
ClassName daoFactoryClassName = BindDaoFactoryBuilder.generateDaoFactoryClassName(method.getParent().getParent());
MethodSpec.Builder executeWithDaoFactortBuilder = MethodSpec.methodBuilder("execute").addParameter(daoFactoryClassName, "daoFactory").addModifiers(Modifier.PUBLIC).returns(TypeUtility.parameterizedTypeName(TypeUtility.className(List.class), entityTypeName));
executeWithDaoFactortBuilder.addCode("return daoFactory.get$L().$L(", method.getParentName(), method.getName());
if (!method.isPagedLiveData()) {
executeBuilder.addCode("list=$T.this.$L(", TypeUtility.typeName(method.getParent().getElement(), BindDaoBuilder.SUFFIX), method.getName());
}
// we have always a first parameter
String separator = "";
ParameterSpec parameterSpec;
for (Pair<String, TypeName> item : method.getParameters()) {
if (method.hasDynamicPageSizeConditions() && method.dynamicPageSizeName.equals(item.value0)) {
setupBuilder.addStatement("this.pageSize=$L", item.value0);
} else {
// field
typeBuilder.addField(item.value1, item.value0);
setupBuilder.addStatement("this.$L=$L", item.value0, item.value0);
}
// construtor
parameterSpec = ParameterSpec.builder(item.value1, item.value0).build();
setupBuilder.addParameter(parameterSpec);
// execute
if (method.dynamicPageSizeName != null && method.dynamicPageSizeName.equals(item.value0)) {
if (!method.isPagedLiveData()) {
executeBuilder.addCode(separator + "this.pageSize");
}
executeWithDaoFactortBuilder.addCode(separator + "this.pageSize");
executeWithPageRequestBuilder.addCode(separator + "this.pageSize");
} else {
if (!method.isPagedLiveData()) {
executeBuilder.addCode(separator + item.value0);
}
executeWithDaoFactortBuilder.addCode(separator + item.value0);
executeWithPageRequestBuilder.addCode(separator + item.value0);
}
separator = ", ";
}
if (method.isPagedLiveData()) {
// if method is not paged live data, add complete execute method
executeBuilder.addComment("paged result is used in live data, so this method must be empty");
executeBuilder.addStatement("return null");
} else {
executeBuilder.addCode(separator + "this);\n");
executeBuilder.addStatement("return list");
}
executeBuilder.addComment("Executor builder - END");
typeBuilder.addMethod(executeBuilder.build());
if (!method.hasDynamicPageSizeConditions()) {
ModelAnnotation annotation = method.getAnnotation(BindSqlSelect.class);
int pageSize = annotation.getAttributeAsInt(AnnotationAttributeType.PAGE_SIZE);
// in case pageSize is not specified (only for liveData)
if (pageSize == 0) {
pageSize = 20;
}
setupBuilder.addStatement("this.pageSize=$L", pageSize);
}
typeBuilder.addMethod(setupBuilder.build());
executeWithDaoFactortBuilder.addCode(separator + "this);\n");
executeWithPageRequestBuilder.addCode(separator + "pageRequest));\n");
executeWithPageRequestBuilder.addComment("Executor with pageRequet - END");
// add methods to type builder
typeBuilder.addMethod(executeWithDaoFactortBuilder.build());
typeBuilder.addMethod(executeWithPageRequestBuilder.build());
classBuilder.addType(typeBuilder.build());
return pagedResultName;
}
use of com.squareup.javapoet.ParameterSpec in project kripton by xcesco.
the class SqlInsertBuilder method generate.
/**
* Generate.
*
* @param classBuilder
* the class builder
* @param method
* the method
*/
public static void generate(TypeSpec.Builder classBuilder, SQLiteModelMethod method) {
InsertType insertResultType = detectInsertType(method);
// if true, field must be associate to ben attributes
TypeName returnType = method.getReturnClass();
AssertKripton.failWithInvalidMethodSignException(insertResultType == null, method);
// generate method code
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(method.getName()).addAnnotation(Override.class).addModifiers(Modifier.PUBLIC);
ParameterSpec parameterSpec;
for (Pair<String, TypeName> item : method.getParameters()) {
parameterSpec = ParameterSpec.builder(item.value1, item.value0).build();
methodBuilder.addParameter(parameterSpec);
}
methodBuilder.returns(returnType);
// fail if we use jql to INSERT_BEAN with operation of INSERT-FOR-SELECT
// AssertKripton.failWithInvalidMethodSignException(insertResultType ==
// InsertType.INSERT_BEAN && method.jql.containsSelectOperation, method,
// "INSERT-FROM-SELECT SQL can not be used with method sign");
// generate inner code
methodBuilder.addComment("Specialized Insert - $L - BEGIN", insertResultType.getClass().getSimpleName());
insertResultType.generate(classBuilder, methodBuilder, method, returnType);
methodBuilder.addComment("Specialized Insert - $L - END", insertResultType.getClass().getSimpleName());
MethodSpec methodSpec = methodBuilder.build();
classBuilder.addMethod(methodSpec);
if (method.contentProviderEntryPathEnabled) {
// we need to generate insert for content provider to
generateInsertForContentProvider(classBuilder, method, insertResultType);
}
}
use of com.squareup.javapoet.ParameterSpec in project kripton by xcesco.
the class SqlInsertBuilder method generateInsertForContentProvider.
/**
* <p>
* Generate insert used in content provider class.
* </p>
*
* @param classBuilder
* the class builder
* @param method
* the method
* @param insertResultType
* the insert result type
*/
private static void generateInsertForContentProvider(TypeSpec.Builder classBuilder, final SQLiteModelMethod method, InsertType insertResultType) {
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);
}
ParameterSpec parameterSpec;
parameterSpec = ParameterSpec.builder(Uri.class, "uri").build();
methodBuilder.addParameter(parameterSpec);
parameterSpec = ParameterSpec.builder(ContentValues.class, "contentValues").build();
methodBuilder.addParameter(parameterSpec);
methodBuilder.returns(Long.TYPE);
SqlBuilderHelper.generateLogForContentProviderBeginning(method, methodBuilder);
// just detect which columns are admitted
JQLChecker.getInstance().replace(method, method.jql, new JQLReplacerListenerImpl(method) {
@Override
public String onColumnName(String columnName) {
SQLProperty tempProperty = entity.get(columnName);
AssertKripton.assertTrueOrUnknownPropertyInJQLException(tempProperty != null, method, columnName);
columns.add(tempProperty.columnName);
return tempProperty.columnName;
}
@Override
public String onColumnFullyQualifiedName(String tableName, String columnName) {
AssertKripton.fail("Inconsistent state");
return null;
}
});
// generate columnCheckSet
SqlBuilderHelper.generateColumnCheckSet(classBuilder, method, columns);
// retrieve content values
methodBuilder.addStatement("$T _contentValues=contentValuesForContentProvider(contentValues)", KriptonContentValues.class);
// generate column check
SqlBuilderHelper.forEachColumnInContentValue(methodBuilder, method, "_contentValues.values().keySet()", true, null);
methodBuilder.addCode("\n");
String rxIdGetter = "result";
// every controls was done in constructor of SQLiteModelMethod
for (ContentUriPlaceHolder variable : method.contentProviderUriVariables) {
SQLProperty entityProperty = entity.get(variable.value);
if (entityProperty != null) {
methodBuilder.addCode("// Add parameter $L at path segment $L\n", variable.value, variable.pathSegmentIndex);
TypeName entityPropertyType = entityProperty.getPropertyType().getTypeName();
if (TypeUtility.isString(entityPropertyType)) {
methodBuilder.addStatement("contentValues.put($S, uri.getPathSegments().get($L))", entityProperty.columnName, variable.pathSegmentIndex);
} else {
methodBuilder.addStatement("contentValues.put($S, Long.valueOf(uri.getPathSegments().get($L)))", entityProperty.columnName, variable.pathSegmentIndex);
}
}
if (entityProperty.isPrimaryKey()) {
rxIdGetter = PropertyUtility.getter(entityProperty);
}
}
// generate log for inser operation
SqlBuilderHelper.generateLogForContentValuesContentProvider(method, methodBuilder);
ConflictAlgorithmType conflictAlgorithmType = InsertBeanHelper.getConflictAlgorithmType(method);
String conflictString2 = "";
// we need to use everytime after support
// if (conflictAlgorithmType != ConflictAlgorithmType.NONE) {
conflictString2 = ", " + conflictAlgorithmType.getConflictAlgorithm();
methodBuilder.addCode("// conflict algorithm $L\n", method.jql.conflictAlgorithmType);
// }
methodBuilder.addComment("insert operation");
methodBuilder.addStatement("long result = getDatabase().insert($S$L, _contentValues.values())", entity.getTableName(), conflictString2);
if (method.getParent().getParent().generateRx) {
SQLProperty primaryKey = entity.getPrimaryKey();
if (primaryKey.columnType == ColumnType.PRIMARY_KEY) {
// long autogenerated
rxIdGetter = "result";
} else {
if (primaryKey.isType(String.class)) {
rxIdGetter = String.format("contentValues.getAsString(\"%s\")", primaryKey.columnName);
} else {
rxIdGetter = String.format("contentValues.getAsLong(\"%s\")", primaryKey.columnName);
}
}
GenericSQLHelper.generateSubjectNext(entity, methodBuilder, SubjectType.INSERT, rxIdGetter);
}
// support for livedata
if (daoDefinition.hasLiveData()) {
methodBuilder.addComment("support for livedata");
methodBuilder.addStatement(BindDaoBuilder.METHOD_NAME_REGISTRY_EVENT + "(result>0?1:0)");
}
methodBuilder.addStatement("return result");
// javadoc
// 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 contentValues content values\n");
methodBuilder.addJavadoc("@return new row's id\n");
classBuilder.addMethod(methodBuilder.build());
}
use of com.squareup.javapoet.ParameterSpec in project so by onap.
the class FluentGenerator method run.
public void run() throws IOException {
List<JavaFile> files = new ArrayList<>();
for (Entry<String, ObjectType> entry : doc.entrySet()) {
// String key = "routing-instance";
// ObjectType oType = test;
String key = entry.getKey();
ObjectType oType = entry.getValue();
MethodSpec.Builder constructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PROTECTED);
List<ParameterSpec> constructorParams = new ArrayList<>();
List<FieldSpec> classFields = new ArrayList<>();
if (!oType.getType().equals("top level")) {
Pair<String, String> path = splitClasspath(this.baseBuilderClass);
ClassName parameterizedTypeName = ClassName.get(path.getLeft(), path.getRight());
constructorParams.add(ParameterSpec.builder(parameterizedTypeName, "parentObj").build());
classFields.add(FieldSpec.builder(parameterizedTypeName, "parentObj").addModifiers(Modifier.PRIVATE, Modifier.FINAL).build());
}
List<ParameterSpec> typeParams = new ArrayList<>();
for (ObjectField oF : oType.getFields()) {
if (oF.getType().equals("string")) {
typeParams.add(ParameterSpec.builder(String.class, lowerCamel(makeValidJavaVariable(oF.getName()))).build());
classFields.add(FieldSpec.builder(String.class, lowerCamel(makeValidJavaVariable(oF.getName()))).addModifiers(Modifier.PRIVATE, Modifier.FINAL).build());
} else if (oF.getType().equals("integer")) {
typeParams.add(ParameterSpec.builder(int.class, lowerCamel(makeValidJavaVariable(oF.getName()))).build());
classFields.add(FieldSpec.builder(int.class, lowerCamel(makeValidJavaVariable(oF.getName()))).addModifiers(Modifier.PRIVATE, Modifier.FINAL).build());
}
}
constructorParams.addAll(typeParams);
constructor.addParameters(constructorParams);
for (ParameterSpec p : constructorParams) {
constructor.addStatement("this.$L = $L", p.name, p.name);
}
List<MethodSpec> methods = new ArrayList<>();
methods.add(constructor.build());
methods.addAll(createChildMethods(oType));
methods.addAll(createInterfaceMethods(oType, typeParams));
ClassName superType = null;
if (oType.getType().equals("top level")) {
Pair<String, String> path = splitClasspath(this.topLevelBuilderClass);
superType = ClassName.get(path.getLeft(), path.getRight());
} else {
if (oType.getType().equals("singular")) {
Pair<String, String> path = splitClasspath(this.singularBuilderClass);
superType = ClassName.get(path.getLeft(), path.getRight());
} else if (oType.getType().equals("plural")) {
Pair<String, String> path = splitClasspath(this.pluralBuilderClass);
superType = ClassName.get(path.getLeft(), path.getRight());
}
}
TypeSpec type = TypeSpec.classBuilder(upperCamel(key)).addModifiers(Modifier.PUBLIC, Modifier.FINAL).addType(createInnerInfoClass(oType)).addSuperinterface(superType).addFields(classFields).addMethods(methods).build();
files.add(JavaFile.builder(CLASSPATH, type).build());
}
files.add(createBuilderClass());
files.stream().forEach(javaFile -> {
try {
javaFile.writeTo(Paths.get(location, "fluent"));
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
Aggregations