Build paginated result class handler.

@param classBuilder
the class builder
@param method
the method
@return name of generated class
198405
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");

		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");
			} else {
				if (!method.isPagedLiveData()) {
					executeBuilder.addCode(separator + item.value0);
				}
				executeWithDaoFactortBuilder.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");

		typeBuilder.addMethod(executeWithDaoFactortBuilder.build());

		classBuilder.addType(typeBuilder.build());

		return pagedResultName;
	}
510160
@Override
	public void generateLiveData(TypeSpec.Builder classBuilder, SQLiteModelMethod method) {
		SQLiteDaoDefinition daoDefinition = method.getParent();
		Set<JQLProjection> fieldList = JQLChecker.getInstance().extractProjections(method, method.jql.value, method.getEntity());

		// generate method code
		MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(method.getName().replaceAll(LIVE_DATA_PREFIX, "")).addAnnotation(Override.class).addModifiers(Modifier.PUBLIC);

		methodBuilder.addJavadoc("<h2>Live data</h2>\n");
		methodBuilder.addJavadoc("<p>This method open a connection internally.</p>\n\n");

		generateCommonPart(method, classBuilder, methodBuilder, fieldList, GenerationType.NO_CONTENT, method.liveDataReturnClass, true, false);

		boolean pagedLiveData = method.isPagedLiveData();

		if (pagedLiveData) {
			SelectType.PAGED_RESULT.generate(classBuilder, method);

			String pageResultName = SelectPaginatedResultHelper.getCurrentPagedResultClass();
			SelectPaginatedResultHelper.createPagedResult(method, pageResultName, methodBuilder);
		}

		ClassName dataSourceClazz = BindDataSourceBuilder.generateDataSourceName(daoDefinition.getParent());
		ClassName daoFactoryClazz = TypeUtility.className(BindDaoFactoryBuilder.generateDaoFactoryName(daoDefinition.getParent()));
		ClassName batchClazz = TypeUtility.mergeTypeNameWithSuffix(dataSourceClazz, ".Batch");

		List<Pair<String, TypeName>> methodParameters = method.getParameters();
		StringBuilder buffer = new StringBuilder();
		String separator = "";

		for (Pair<String, TypeName> item : methodParameters) {
			buffer.append(separator + item.value0);
			separator = ", ";
		}

		ClassName handlerClass = KriptonLiveDataManager.getInstance().getLiveDataHandlerClazz();
		if (pagedLiveData) {
			handlerClass = KriptonLiveDataManager.getInstance().getPagedLiveDataHandlerClazz();

			TypeSpec batchBuilder = TypeSpec.anonymousClassBuilder("").addSuperinterface(ParameterizedTypeName.get(batchClazz, method.getReturnClass()))
					.addMethod(
							MethodSpec.methodBuilder("onExecute").addAnnotation(Override.class).addModifiers(Modifier.PUBLIC).addParameter(ParameterSpec.builder(daoFactoryClazz, "daoFactory").build())
									.returns(method.getReturnClass()).addStatement("return paginatedResult.execute(daoFactory)").build())
					.build();

			// return
			TypeSpec.Builder liveDataBuilderBuilder = TypeSpec.anonymousClassBuilder("paginatedResult")
					.addSuperinterface(ParameterizedTypeName.get(handlerClass, method.getReturnClass())).addMethod(MethodSpec.methodBuilder("compute").addAnnotation(Override.class)
							.addModifiers(Modifier.PROTECTED).returns(method.getReturnClass()).addStatement("return $T.getInstance().executeBatch($L)", dataSourceClazz, batchBuilder).build());
			TypeSpec liveDataBuilder = liveDataBuilderBuilder.build();

			methodBuilder.addStatement("final $T builder=$L", ParameterizedTypeName.get(handlerClass, method.getReturnClass()), liveDataBuilder);
		} else {
			TypeSpec batchBuilder = TypeSpec.anonymousClassBuilder("").addSuperinterface(ParameterizedTypeName.get(batchClazz, method.getReturnClass()))
					.addMethod(MethodSpec.methodBuilder("onExecute").addAnnotation(Override.class).addModifiers(Modifier.PUBLIC)
							.addParameter(ParameterSpec.builder(daoFactoryClazz, "daoFactory").build()).returns(method.getReturnClass())
							.addStatement("return daoFactory.get$L().$L($L)", daoDefinition.getName(), method.getName() + LIVE_DATA_PREFIX, buffer.toString()).build())
					.build();

			TypeSpec.Builder liveDataBuilderBuilder = TypeSpec.anonymousClassBuilder("").addSuperinterface(ParameterizedTypeName.get(handlerClass, method.getReturnClass()))
					.addMethod(MethodSpec.methodBuilder("compute").addAnnotation(Override.class).addModifiers(Modifier.PROTECTED).returns(method.getReturnClass())
							.addStatement("return $T.getInstance().executeBatch($L)", dataSourceClazz, batchBuilder).build());
			TypeSpec liveDataBuilder = liveDataBuilderBuilder.build();

			methodBuilder.addStatement("final $T builder=$L", ParameterizedTypeName.get(handlerClass, method.getReturnClass()), liveDataBuilder);
		}

		methodBuilder.addStatement("registryLiveData(builder)");
		methodBuilder.addStatement("return builder.getLiveData()");

		classBuilder.addMethod(methodBuilder.build());
	}
384077
private void classifyMethod(ExecutableElement method) {
    switch (method.getParameters().size()) {
      case 0:
        classifyMethodNoArgs(method);
        break;
      case 1:
        classifyMethodOneArg(method);
        break;
      default:
        errorReporter.reportError("Builder methods must have 0 or 1 parameters", method);
    }
  }
1166886
protected function createQueuedHandlerCallable($className, $method)
    {
        return function () use ($className, $method)
        {
            // Clone the given arguments for queueing.
            $arguments = array_map(function ($a)
            {
                return is_object($a) ? clone $a : $a;

            }, func_get_args());

            if (method_exists($className, 'queue')) {
                $this->callQueueMethodOnHandler($className, $method, $arguments);
            } else {
                $this->resolveQueue()->push('Nova\Events\CallQueuedHandler@call', array(
                    'class'  => $className,
                    'method' => $method,
                    'data'   => serialize($arguments),
                ));
            }
        };
    }
17225
public static void generateSQLForInsertDynamic(final SQLiteModelMethod method, MethodSpec.Builder methodBuilder) {
		methodBuilder.addComment("generate SQL for insert");
		JQLChecker checker = JQLChecker.getInstance();

		// replace the table name, other pieces will be removed
		String sql = checker.replace(method, method.jql, new JQLReplacerListenerImpl(method) {

			@Override
			public String onBindParameter(String bindParameterName, boolean inStatement) {
				return "?";
			}
		});

		final One<Integer> counter = new One<Integer>(0);
		sql = checker.replaceVariableStatements(method, sql, new JQLReplaceVariableStatementListenerImpl() {

			@Override
			public String onColumnNameSet(String statement) {
				counter.value0++;
				return "%s";
			}

			@Override
			public String onColumnValueSet(String statement) {
				counter.value0++;
				return "%s";
			}

		});

		if (counter.value0 == 2) {
			methodBuilder.addStatement("String _sql=String.format($S, _contentValues.keyList(), _contentValues.keyValueList())", sql);
		} else {
			methodBuilder.addStatement("String _sql=String.format($S, _contentValues.keyList())", sql);
		}
	}
661647
public static function getMethodSlot(ClassMethod $method)
    {
        $className = $method->getClassDefinition()->getCompleteName();
        $methodName = $method->getName();

        if (isset(self::$cacheMethodSlots[$className][$methodName])) {
            return self::$cacheMethodSlots[$className][$methodName];
        }

        $slot = self::$slot++;
        if ($slot >= self::MAX_SLOTS_NUMBER) {
            return 0;
        }

        self::$cacheMethodSlots[$className][$methodName] = $slot;

        return $slot;
    }
561072
public static void validateMethodOrThrow(Method method) {
    Class<?> returnType = method.getReturnType();
    if (returnType.equals(Void.TYPE)) {
      return;
    } else if (!Publisher.class.isAssignableFrom(returnType)) {
      throw new UnsupportedOperationException("Service method return type can be Publisher only");
    }
    if (method.getParameterCount() > 1) {
      throw new UnsupportedOperationException("Service method can accept 0 or 1 parameters only");
    }
  }
415769
private void createAmpResultMethod(JavaClass jClass,
                                     Method method,
                                     int resultOffset)
  {
    String methodName = method.getName();
    Class<?> []parameterTypes = method.getParameterTypes();
    
    if (parameterTypes.length != 1) {
      throw new IllegalStateException();
    }

    addMethod(method);
    
    CodeWriterAttribute code = createMethodHeader(jClass, method);
    
    code.setMaxLocals(1 + 2 * parameterTypes.length);
    code.setMaxStack(10 + 2 * parameterTypes.length);

    code.pushObjectVar(getLength(parameterTypes, resultOffset) + 1);
    
    code.pushObjectVar(0);
    code.getField(jClass.getThisClass(),
                  getMethodFieldName(methodName),
                  ShimConverter.class);
     
    code.pushObjectVar(0);
    
    code.invoke(ShimConverter.class,
                "toTransfer",
                Object.class,
                Object.class);
    
    code.invokeInterface(Result.class,
                         "ok",
                         void.class,
                         Object.class);

    code.addReturn();

    code.close();
  }
1302730
public static void generateGenericExecSQL(MethodSpec.Builder methodBuilder, final SQLiteModelMethod method) {

		boolean nullable;
		final List<String> paramsList = new ArrayList<String>();
		final List<String> contentValueList = new ArrayList<String>();
		final One<Boolean> columnsToUpdate = new One<Boolean>(true);

		String sql = JQLChecker.getInstance().replace(method, method.jql, new JQLReplacerListenerImpl(method) {

			@Override
			public void onWhereStatementBegin(Where_stmtContext ctx) {
				super.onWhereStatementBegin(ctx);

				columnsToUpdate.value0 = false;
			}

			@Override
			public void onWhereStatementEnd(Where_stmtContext ctx) {
				super.onWhereStatementEnd(ctx);

				columnsToUpdate.value0 = true;
			}

			@Override
			public String onColumnName(String columnName) {
				String resolvedName = currentSchema.findColumnNameByPropertyName(method, columnName);
				AssertKripton.assertTrueOrUnknownPropertyInJQLException(resolvedName != null, method, columnName);

				return resolvedName;

			}

			@Override
			public String onBindParameter(String bindParameterName, boolean inStatement) {
				String propertyName = method.findParameterAliasByName(bindParameterName);

				if (columnsToUpdate.value0) {
					contentValueList.add(propertyName);
				} else {
					paramsList.add(propertyName);
				}
				return "?";
			}
		});

		// update/insert columns
		final SQLiteEntity entity = method.getEntity();
		for (String item : contentValueList) {
			// ASSERT: property is always in entity
			String propertyName = method.findParameterNameByAlias(item);
			TypeName paramType = method.findParameterTypeByAliasOrName(item);

			SQLProperty property = entity.get(item);

			if (propertyName == null)
				throw (new PropertyNotFoundException(method, propertyName, paramType));

			Pair<String, TypeName> methodParam = new Pair<String, TypeName>(propertyName, paramType);

			// check same type
			TypeUtility.checkTypeCompatibility(method, methodParam, property);
			// check nullabliity
			// nullable = TypeUtility.isNullable(method, methodParam, property);
			//
			// if (nullable) {
			// // it use raw method param's typeName
			// methodBuilder.beginControlFlow("if ($L!=null)", methodParam.value0);
			// }

			if (method.isLogEnabled()) {
				methodBuilder.addCode("_contentValues.put($S, ", property.columnName);
			} else {
				methodBuilder.addCode("_contentValues.put(");
			}

			// it does not need to be converted in string
			SQLTransformer.javaMethodParam2ContentValues(methodBuilder, method, methodParam.value0, methodParam.value1,
					property);
			methodBuilder.addCode(");\n");
			// if (nullable) {
			// methodBuilder.nextControlFlow("else");
			//
			// if (method.isLogEnabled()) {
			// methodBuilder.addStatement("_contentValues.putNull($S)", property.columnName);
			// } else {
			// methodBuilder.addStatement("_contentValues.putNull()");
			// }
			//
			// methodBuilder.endControlFlow();
			// }

		}

		// where condition
		methodBuilder.addComment("build where condition");
		{
			// String separator = "";
			TypeName paramType;
			String realName;

			for (String item : paramsList) {
				methodBuilder.addCode("_contentValues.addWhereArgs(");

				paramType = method.findParameterTypeByAliasOrName(item);
				realName = method.findParameterNameByAlias(item);

				AssertKripton.assertTrueOrUnknownPropertyInJQLException(paramType != null, method, item);

				// code for query arguments
				nullable = TypeUtility.isNullable(paramType);
				if (nullable) {
					methodBuilder.addCode("($L==null?\"\":", realName);
				}

				// check for string conversion
				TypeUtility.beginStringConversion(methodBuilder, paramType);

				SQLTransformer.javaMethodParam2ContentValues(methodBuilder, method, realName, paramType, null);

				// check for string conversion
				TypeUtility.endStringConversion(methodBuilder, paramType);

				if (nullable) {
					methodBuilder.addCode(")");
				}

				methodBuilder.addCode(");\n");
			}
		}

		// log for where parames
		SqlBuilderHelper.generateLog(method, methodBuilder);

		// log
		methodBuilder.addCode("\n");
		methodBuilder.addStatement("database().execSQL($S, _contentValues.whereArgsAsArray())", sql);
	}
281832
public static void generateSQL(final SQLiteModelMethod method, MethodSpec.Builder methodBuilder) {
		JQLChecker jqlChecker = JQLChecker.getInstance();

		methodBuilder.addCode("\n// generate sql\n");
		String sql = jqlChecker.replace(method, method.jql, new JQLReplacerListenerImpl(method) {
			@Override
			public String onColumnNameToUpdate(String columnName) {
				// only entity's columns
				return currentEntity.findPropertyByName(columnName).columnName;
			}

			@Override
			public String onColumnName(String columnName) {
				return currentSchema.findColumnNameByPropertyName(method, columnName);
			}

			@Override
			public String onBindParameter(String bindParameterName, boolean inStatement) {
				return "?";
			}

		});

		if (method.jql.dynamicReplace.containsKey(JQLDynamicStatementType.DYNAMIC_WHERE)) {
			methodBuilder.addStatement("String _sql=String.format($S, $L)",
					sql.replace(method.jql.dynamicReplace.get(JQLDynamicStatementType.DYNAMIC_WHERE), "%s"),
					"StringUtils.ifNotEmptyAppend(_sqlDynamicWhere,\" AND \")");
		} else {
			methodBuilder.addStatement("String _sql=$S", sql);
		}
	}
1022990
public SelectIterator<T, ID> buildIterator(BaseDaoImpl<T, ID> classDao, ConnectionSource connectionSource,
			PreparedStmt<T> preparedStmt, ObjectCache objectCache, int resultFlags) throws SQLException {
		DatabaseConnection connection = connectionSource.getReadOnlyConnection(tableInfo.getTableName());
		CompiledStatement compiledStatement = null;
		try {
			compiledStatement = preparedStmt.compile(connection, StatementType.SELECT, resultFlags);
			SelectIterator<T, ID> iterator = new SelectIterator<T, ID>(tableInfo.getDataClass(), classDao, preparedStmt,
					connectionSource, connection, compiledStatement, preparedStmt.getStatement(), objectCache);
			connection = null;
			compiledStatement = null;
			return iterator;
		} finally {
			IOUtils.closeThrowSqlException(compiledStatement, "compiled statement");
			if (connection != null) {
				connectionSource.releaseConnection(connection);
			}
		}
	}
332743
protected MethodSpec.Builder generateMethodBuilder(SQLiteModelMethod method) {
		MethodSpec.Builder methodBuilder;
		if (method.hasLiveData()) {
			methodBuilder = MethodSpec.methodBuilder(method.getName() + LIVE_DATA_PREFIX).addModifiers(Modifier.PROTECTED);
		} else {
			methodBuilder = MethodSpec.methodBuilder(method.getName()).addAnnotation(Override.class).addModifiers(Modifier.PUBLIC);
		}

		return methodBuilder;
	}
510780
protected void generateMethodSignature(SQLiteModelMethod method, MethodSpec.Builder methodBuilder, TypeName returnTypeName, ParameterSpec... additionalParameterSpec) {
		boolean finalParameter = false;
		if (method.hasLiveData() && returnTypeName.equals(method.liveDataReturnClass)) {
			finalParameter = true;
		}

		// add parameter for method
		for (Pair<String, TypeName> item : method.getParameters()) {
			ParameterSpec.Builder builder = ParameterSpec.builder(item.value1, item.value0);

			if (finalParameter) {
				builder.addModifiers(Modifier.FINAL);
			}

			methodBuilder.addParameter(builder.build());
		}

		// add additional params
		for (ParameterSpec item : additionalParameterSpec) {
			methodBuilder.addParameter(item);
		}

		// add return type
		methodBuilder.returns(returnTypeName);
	}
725866
@Nonnull
    public BugInstance addClassAndMethod(JavaClass javaClass, Method method) {
        addClass(javaClass.getClassName());
        addMethod(javaClass, method);

        if (!MemberUtils.isUserGenerated(method)) {
            foundInAutogeneratedMethod();
        }
        return this;
    }
679985
public static void generateSelect(Builder builder, SQLiteModelMethod method) throws ClassNotFoundException {
		SelectType selectResultType = SelectBuilderUtility.detectSelectType(method);

		// generate select method
		selectResultType.generate(builder, method);

		if (method.hasLiveData()) {
			// generate
			selectResultType.generateLiveData(builder, method);
		}

		if (method.contentProviderEntryPathEnabled) {
			// we need to generate UPDATE or DELETE for content provider to
			generateSelectForContentProvider(builder, method, selectResultType);
		}
	}
204586
private static JQL buildJQLDelete(SQLiteModelMethod method, final JQL result, final Map<JQLDynamicStatementType, String> dynamicReplace, String preparedJql) {
		final SQLiteDaoDefinition dao = method.getParent();

		if (StringUtils.hasText(preparedJql)) {
			// in DELETE SQL only where statement can contains bind parameter
			result.value = preparedJql;

			JQLChecker.getInstance().analyze(method, result, new JqlBaseListener() {

				@Override
				public void enterBind_parameter(Bind_parameterContext ctx) {
					result.bindParameterOnWhereStatementCounter++;
				}

				@Override
				public void enterBind_dynamic_sql(Bind_dynamic_sqlContext ctx) {
					JQLDynamicStatementType dynamicType = JQLDynamicStatementType.valueOf(ctx.bind_parameter_name().getText().toUpperCase());

					int start = ctx.getStart().getStartIndex() - 1;
					int stop = ctx.getStop().getStopIndex() + 1;

					String dynamicWhere = result.value.substring(start, stop);

					dynamicReplace.put(dynamicType, dynamicWhere);
				}
			});

			// where management
			JQLChecker.getInstance().replaceVariableStatements(method, preparedJql, new JQLReplaceVariableStatementListenerImpl() {

				@Override
				public String onWhere(String statement) {
					result.annotatedWhere = true;
					result.staticWhereConditions = true;
					return null;
				}
			});

		} else {
			StringBuilder builder = new StringBuilder();
			builder.append(DELETE_KEYWORD + " " + FROM_KEYWORD);
			// entity name
			builder.append(" " + dao.getEntitySimplyClassName());

			builder.append(defineWhereStatement(method, result, BindSqlDelete.class, dynamicReplace));

			result.value = builder.toString();
		}
		result.operationType = JQLType.DELETE;
		result.dynamicReplace = dynamicReplace;
		return result;
	}
72918
private void injectServletCallback(String method) {
        Label tryStart = new Label();
        Label tryEnd = new Label();
        Label catchStart = new Label();
        Label catchEnd = new Label();

        visitTryCatchBlock(tryStart, tryEnd, catchStart, "java/lang/NoClassDefFoundError");
        mark(tryStart); // try {
        loadArgs();
        invokeStatic(Type.getType(SERVLET_CALLBACK_TYPE), Method.getMethod(method));
        mark(tryEnd); // }
        visitJumpInsn(GOTO, catchEnd);
        mark(catchStart); // catch() {
        pop();
        mark(catchEnd); // }
    }