3030
3131import freemarker .template .Configuration ;
3232import freemarker .template .Template ;
33+ import freemarker .template .TemplateNotFoundException ;
3334
3435/**
3536 * Once you have your model created, use this class to generate entities and DAOs.
@@ -58,9 +59,7 @@ public DaoGenerator() throws IOException {
5859 patternKeepFields = compilePattern ("FIELDS" );
5960 patternKeepMethods = compilePattern ("METHODS" );
6061
61- Configuration config = new Configuration (Configuration .VERSION_2_3_23 );
62- config .setClassForTemplateLoading (this .getClass (), "/" );
63-
62+ Configuration config = getConfiguration ("dao.ftl" );
6463 templateDao = config .getTemplate ("dao.ftl" );
6564 templateDaoMaster = config .getTemplate ("dao-master.ftl" );
6665 templateDaoSession = config .getTemplate ("dao-session.ftl" );
@@ -69,6 +68,31 @@ public DaoGenerator() throws IOException {
6968 templateContentProvider = config .getTemplate ("content-provider.ftl" );
7069 }
7170
71+ private Configuration getConfiguration (String probingTemplate ) throws IOException {
72+ Configuration config = new Configuration (Configuration .VERSION_2_3_23 );
73+ config .setClassForTemplateLoading (getClass (), "/" );
74+
75+ try {
76+ config .getTemplate (probingTemplate );
77+ } catch (TemplateNotFoundException e ) {
78+ // When running from an IDE like IntelliJ, class loading resources may fail for some reason (Gradle is OK)
79+
80+ // Working dir is module dir
81+ File dir = new File ("src/main/resources/" );
82+ if (!dir .exists ()) {
83+ // Working dir is base module dir
84+ dir = new File ("DaoGenerator/src/main/resources/" );
85+ }
86+ if (dir .exists () && new File (dir , probingTemplate ).exists ()) {
87+ config .setDirectoryForTemplateLoading (dir );
88+ config .getTemplate (probingTemplate );
89+ } else {
90+ throw e ;
91+ }
92+ }
93+ return config ;
94+ }
95+
7296 private Pattern compilePattern (String sectionName ) {
7397 int flags = Pattern .DOTALL | Pattern .MULTILINE ;
7498 return Pattern .compile (".*^\\ s*?//\\ s*?KEEP " + sectionName + ".*?\n (.*?)^\\ s*// KEEP " + sectionName
0 commit comments