DaoのJavaコードを生成します。

@param daoDesc Dao記述
18624
protected void generateDao(DaoDesc daoDesc) {
    File javaFile = FileUtil.createJavaFile(daoConfig.getDestDir(), daoDesc.getQualifiedName());
    GenerationContext context =
        new GenerationContext(
            daoDesc,
            javaFile,
            daoDesc.getTemplateName(),
            daoConfig.getEncoding(),
            daoConfig.isOverwrite());
    generator.generate(context);
  }
1237976
public void setDagNodes(java.util.Collection<CodeGenNode> dagNodes) {
        if (dagNodes == null) {
            this.dagNodes = null;
            return;
        }

        this.dagNodes = new java.util.ArrayList<CodeGenNode>(dagNodes);
    }
265088
protected DaoDescFactory createDaoDescFactory() {
    return globalFactory.createDaoDescFactory(
        daoConfig.getPackageName(), daoConfig.getSuffix(), daoConfig.getConfigClassName());
  }
413288
public TypeSpec.Builder buildDaoFactoryInterfaceInternal(Elements elementUtils, Filer filer, SQLiteDatabaseSchema schema) throws Exception {
		String schemaName = buildDaoFactoryName(schema);

		classBuilder = TypeSpec.interfaceBuilder(schemaName).addModifiers(Modifier.PUBLIC).addSuperinterface(BindDaoFactory.class);

		classBuilder.addJavadoc("<p>\n");
		classBuilder.addJavadoc("Represents dao factory interface for $L.\n", schema.getName());
		classBuilder.addJavadoc("This class expose database interface through Dao attribute.\n", schema.getName());
		classBuilder.addJavadoc("</p>\n\n");

		JavadocUtility.generateJavadocGeneratedBy(classBuilder);
		classBuilder.addJavadoc("@see $T\n", TypeUtility.typeName(schema.getElement()));

		for (SQLiteDaoDefinition dao : schema.getCollection()) {
			TypeName daoName = BindDaoBuilder.daoInterfaceTypeName(dao);
			TypeName daoImplName = BindDaoBuilder.daoTypeName(dao);

			classBuilder.addJavadoc("@see $T\n", daoName);
			classBuilder.addJavadoc("@see $T\n", daoImplName);

			String entity = BindDataSourceSubProcessor.generateEntityName(dao, dao.getEntity());

			classBuilder.addJavadoc("@see $T\n", TypeUtility.typeName(entity));
		}

		for (SQLiteDaoDefinition dao : schema.getCollection()) {
			TypeName daoImplName = BindDaoBuilder.daoTypeName(dao);

			// dao with external connections
			{
				MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("get" + dao.getName())
						.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT).addJavadoc("Retrieve dao $L.\n\n@return dao implementation\n", dao.getName())
						.returns(daoImplName);
				classBuilder.addMethod(methodBuilder.build());
			}
		}
		
		SchemaUtility.generateTransaction(classBuilder, schema, true);

		return classBuilder;
	}
991293
public <T, K> DAO<T, K> getDAO(
                    final Class<T> entityClass
                    )
    {
        if (entityClass == null) {
            throw new ObjectTypeException( "entity type NOT specified (null)" );
        }

        DAO<T, K>  dao = null;
        try {
            @SuppressWarnings( "unchecked" )
            DAO<T, K>  dao_tmp = (DAO<T, K>)_daoMap.get( entityClass );
                                 //throws ClassCastException
            dao = dao_tmp;
        } catch (Exception ex) {
            throw new RepositoryConfigurationException( ex );
        }

        if (dao == null) {
            throw new RepositoryConfigurationException( "unknown entity type: " + entityClass );
        }

        return dao;
    }
458771
private DataColumnsDao getDataColumnsDao() throws SQLException {
		if (dataColumnsDao == null) {
			dataColumnsDao = DaoManager.createDao(connectionSource,
					DataColumns.class);
		}
		return dataColumnsDao;
	}
214533
private static <T, ID, I extends GenericDAO<T, ID>> Class<? extends I> completeDAO(Class<T> modelClass,
                                                                                       Class<I> daoInterface,
                                                                                       Class<? extends QueryModelDAO<T, ID>> partialDAOClass,
                                                                                       boolean accessControlEnabled,
                                                                                       boolean metricsEnabled) {
        try {
            ClassPool pool = ClassPool.getDefault();

            pool.insertClassPath(new ClassClassPath(daoInterface));

            CtClass fullDAOCtClass = pool.makeClass(String.format("%s$%d", daoInterface.getName(), count.incrementAndGet()));
            CtClass partialDAOCtClass = pool.get(partialDAOClass.getName());
            CtClass daoInterfaceCtClass = pool.get(daoInterface.getName());

            fullDAOCtClass.setSuperclass(partialDAOCtClass);
            fullDAOCtClass.addInterface(daoInterfaceCtClass);

            buildConstructor(fullDAOCtClass, accessControlEnabled);
            buildNeededMethods(fullDAOCtClass, partialDAOCtClass, daoInterfaceCtClass, modelClass, accessControlEnabled, metricsEnabled);

            return ClassLoadingUtil.toClass(fullDAOCtClass);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
682615
public synchronized static <D extends Dao<T, ?>, T> D createDao(ConnectionSource connectionSource,
			DatabaseTableConfig<T> tableConfig) throws SQLException {
		if (connectionSource == null) {
			throw new IllegalArgumentException("connectionSource argument cannot be null");
		}
		return doCreateDao(connectionSource, tableConfig);
	}
1138064
@Override
    public DaoResult updateOrCreate(T bo) {
        if (bo == null) {
            return new DaoResult(DaoOperationStatus.NOT_FOUND);
        }
        try (Connection conn = getConnection(upsertInTransaction)) {
            return updateOrCreate(conn, bo);
        } catch (SQLException e) {
            throw new DaoException(e);
        }
    }
598927
public DaoDesc createDaoDesc(EntityDesc entityDesc) {
    DaoDesc daoDesc = new DaoDesc();
    daoDesc.setPackageName(packageName);
    String entityPrefix = StringUtil.defaultString(entityDesc.getEntityPrefix(), "");
    String entitySuffix = StringUtil.defaultString(entityDesc.getEntitySuffix(), "");
    String simpleName = entityPrefix + entityDesc.getSimpleName() + entitySuffix + suffix;
    daoDesc.setSimpleName(simpleName);
    if (configClassName != null) {
      daoDesc.setConfigClassSimpleName(ClassUtil.getSimpleName(configClassName));
    }
    daoDesc.setEntityDesc(entityDesc);
    daoDesc.setTemplateName(Constants.DAO_TEMPLATE);
    handleImportName(daoDesc, entityDesc);
    return daoDesc;
  }
978290
protected <L, S extends Persistable<L>>
    S _daoLoadOrCreate(
                    final Class<S> type,
                    final S object
                    )
    {
        CastorDao<L, S>  dao = getForwardingDao( type );
        S  p_object = dao._loadCorrespondent( object );
        if (p_object == null) {
            dao._create( object );
        }

        return p_object;
    }
1037366
public void generateMethodExecuteBatch(String daoFactory) {
		// create interface
		String transationExecutorName = "Batch";
		// @formatter:off
		// ParameterizedTypeName parameterizedTypeName =
		// ParameterizedTypeName.get(className(AbstractExecutable.class),
		// className(daoFactory));
		classBuilder.addType(TypeSpec.interfaceBuilder(transationExecutorName).addModifiers(Modifier.PUBLIC)
				.addTypeVariable(TypeVariableName.get("T"))
				// .addSuperinterface(parameterizedTypeName)
				.addJavadoc("Rapresents batch operation.\n")
				.addMethod(MethodSpec.methodBuilder("onExecute").addJavadoc("Execute batch operations.")
						.addJavadoc("\n\n@param daoFactory\n@throws Throwable\n")
						.addParameter(className(daoFactory), "daoFactory")
						.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT).returns(TypeVariableName.get("T")).build())
				.build());
		// @formatter:on

		// @formatter:on
		{
			// execute read/write mode
			MethodSpec.Builder executeMethod = MethodSpec.methodBuilder("executeBatch")
					// generate javadoc
					.addTypeVariable(TypeVariableName.get("T"))
					.addJavadoc(
							"<p>Executes a batch opening a read only connection. This method <strong>is thread safe</strong> to avoid concurrent problems.</p>\n\n")
					.addJavadoc("@param commands\n\tbatch to execute\n").addModifiers(Modifier.PUBLIC)
					.addParameter(
							ParameterizedTypeName.get(className(transationExecutorName), TypeVariableName.get("T")),
							"commands")
					.returns(TypeVariableName.get("T"));

			executeMethod.addStatement("return executeBatch(commands, false)");
			classBuilder.addMethod(executeMethod.build());
		}

		{
			// execute read/write mode
			MethodSpec.Builder executeMethod = MethodSpec.methodBuilder("executeBatch")
					// generate javadoc
					.addJavadoc(
							"<p>Executes a batch. This method <strong>is thread safe</strong> to avoid concurrent problems. The "
									+ "drawback is only one transaction at time can be executed. if <code>writeMode</code> is set to false, multiple batch operations is allowed.</p>\n")
					.addTypeVariable(TypeVariableName.get("T")).addJavadoc("\n")
					.addJavadoc("@param commands\n\tbatch to execute\n")
					.addJavadoc(
							"@param writeMode\n\ttrue to open connection in write mode, false to open connection in read only mode\n")
					.addModifiers(Modifier.PUBLIC)
					.addParameter(
							ParameterizedTypeName.get(className(transationExecutorName), TypeVariableName.get("T")),
							"commands")
					.addParameter(Boolean.TYPE, "writeMode").returns(TypeVariableName.get("T"));

			executeMethod.addStatement("boolean needToOpened=writeMode?!this.isOpenInWriteMode(): !this.isOpen()");
			executeMethod.addCode(
					"if (needToOpened) { if (writeMode) { openWritableDatabase(); } else { openReadOnlyDatabase(); }}\n",
					SQLiteDatabase.class);

			// support for live data
			executeMethod.addStatement("$L currentDaoFactory=new DataSourceSingleThread()",
					DATA_SOURCE_SINGLE_THREAD_NAME);
			executeMethod.addStatement("currentDaoFactory.onSessionOpened()");

			executeMethod.beginControlFlow("try");
			executeMethod.beginControlFlow("if (commands!=null)");
			executeMethod.addStatement("return commands.onExecute(currentDaoFactory)");

			executeMethod.endControlFlow();

			executeMethod.nextControlFlow("catch($T e)", Throwable.class);

			executeMethod.addStatement("$T.error(e.getMessage())", Logger.class);
			executeMethod.addStatement("e.printStackTrace()");
			executeMethod.addStatement("throw(e)");

			executeMethod.nextControlFlow("finally");
			executeMethod.addCode("if (needToOpened) { close(); }\n");
			// support for live data
			executeMethod.addStatement("currentDaoFactory.onSessionClosed()");
			executeMethod.endControlFlow();
			executeMethod.addStatement("return null");

			classBuilder.addMethod(executeMethod.build());
		}
	}
617322
public synchronized static <D extends Dao<T, ?>, T> D createDao(ConnectionSource connectionSource, Class<T> clazz)
			throws SQLException {
		if (connectionSource == null) {
			throw new IllegalArgumentException("connectionSource argument cannot be null");
		}
		ClassConnectionSource key = new ClassConnectionSource(connectionSource, clazz);
		Dao<?, ?> dao = lookupDao(key);
		if (dao != null) {
			@SuppressWarnings("unchecked")
			D castDao = (D) dao;
			return castDao;
		}

		// see if we can build it from source
		dao = createDaoFromConfig(connectionSource, clazz);
		if (dao != null) {
			@SuppressWarnings("unchecked")
			D castDao = (D) dao;
			return castDao;
		}

		DatabaseTable databaseTable = clazz.getAnnotation(DatabaseTable.class);
		if (databaseTable == null || databaseTable.daoClass() == Void.class
				|| databaseTable.daoClass() == BaseDaoImpl.class) {
			// see if the database type has some special table config extract method (Android)
			DatabaseType databaseType = connectionSource.getDatabaseType();
			DatabaseTableConfig<T> config = databaseType.extractDatabaseTableConfig(connectionSource, clazz);
			Dao<T, ?> daoTmp;
			if (config == null) {
				daoTmp = BaseDaoImpl.createDao(connectionSource, clazz);
			} else {
				daoTmp = BaseDaoImpl.createDao(connectionSource, config);
			}
			dao = daoTmp;
			logger.debug("created dao for class {} with reflection", clazz);
		} else {
			Class<?> daoClass = databaseTable.daoClass();
			Object[] arguments = new Object[] { connectionSource, clazz };
			// look first for the constructor with a class parameter in case it is a generic dao
			Constructor<?> daoConstructor = findConstructor(daoClass, arguments);
			if (daoConstructor == null) {
				// then look for the constructor with just the ConnectionSource
				arguments = new Object[] { connectionSource };
				daoConstructor = findConstructor(daoClass, arguments);
				if (daoConstructor == null) {
					throw new SQLException(
							"Could not find public constructor with ConnectionSource and optional Class parameters "
									+ daoClass + ".  Missing static on class?");
				}
			}
			try {
				dao = (Dao<?, ?>) daoConstructor.newInstance(arguments);
				logger.debug("created dao for class {} from constructor", clazz);
			} catch (Exception e) {
				throw SqlExceptionUtil.create("Could not call the constructor in class " + daoClass, e);
			}
		}

		registerDao(connectionSource, dao);
		@SuppressWarnings("unchecked")
		D castDao = (D) dao;
		return castDao;
	}
987742
protected void generateEntity(EntityDesc entityDesc) {
    File javaFile =
        FileUtil.createJavaFile(entityConfig.getDestDir(), entityDesc.getQualifiedName());
    GenerationContext context =
        new GenerationContext(
            entityDesc,
            javaFile,
            entityDesc.getTemplateName(),
            entityConfig.getEncoding(),
            entityConfig.isOverwrite());
    generator.generate(context);
  }
1257255
public <T> int createWithForeignDao(T foreignData) throws SQLException {
		@SuppressWarnings("unchecked")
		Dao<T, ?> castDao = (Dao<T, ?>) foreignDao;
		return castDao.create(foreignData);
	}
258391
public static <T> int createTable(ConnectionSource connectionSource, Class<T> dataClass) throws SQLException {
		Dao<T, ?> dao = DaoManager.createDao(connectionSource, dataClass);
		return doCreateTable(dao, false);
	}
1150804
@Override
	public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
		for (TypeElement dataSource : dataSets) {
			SQLiteDatabaseSchema currentSchema = createDataSource(dataSource);

			// Analyze beans BEFORE daos, because beans are needed for DAO
			// definition
			for (String daoName : currentSchema.getDaoNameSet()) {
				// check dao into bean definition
				createSQLEntityFromDao(currentSchema, dataSource, daoName);

			} // end foreach bean

			// sort table by its name, BEFORE inject generated tables and entities
			Collections.sort(currentSchema.getCollection(), new Comparator<SQLiteDaoDefinition>() {
				@Override
				public int compare(SQLiteDaoDefinition o1, SQLiteDaoDefinition o2) {
					return o1.getTableName().compareTo(o2.getTableName());
				}
			});

			// DAO analysis
			// Get all generated dao definitions
			for (String generatedDaoItem : currentSchema.getDaoNameSet()) {
				createSQLDaoDefinition(currentSchema, globalBeanElements, globalDaoElements, generatedDaoItem);
			}

			analyzeForeignKey(currentSchema);

			// Relation must be done AFTER foreign key building!!!
			analyzeRelations(currentSchema);

			// Analyze custom bean
			analyzeCustomBeanForSelect(currentSchema);
			
			if (currentSchema.getCollection().size() == 0) {
				AssertKripton.fail("DataSource class %s with @%s annotation has no defined DAOs",
						currentSchema.getElement().getSimpleName().toString(),
						BindDataSource.class.getSimpleName(),
						BindDao.class.getSimpleName()
						);
				// info(msg);				
				return true;
			}

			// for each dao definition, we define its uid
			int uid = 0;
			for (SQLiteDaoDefinition daoDefinition : currentSchema.getCollection()) {
				String daoFieldName = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, daoDefinition.getName())
						+ "_UID";

				daoDefinition.daoUidName = daoFieldName;
				daoDefinition.daoUidValue = uid;

				uid++;
			}

			schemas.add(currentSchema);
		} // end foreach dataSource

		return true;
	}