View Javadoc
1   /**
2    *    Copyright 2006-2016 the original author or authors.
3    *
4    *    Licensed under the Apache License, Version 2.0 (the "License");
5    *    you may not use this file except in compliance with the License.
6    *    You may obtain a copy of the License at
7    *
8    *       http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *    Unless required by applicable law or agreed to in writing, software
11   *    distributed under the License is distributed on an "AS IS" BASIS,
12   *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *    See the License for the specific language governing permissions and
14   *    limitations under the License.
15   */
16  package org.mybatis.generator.ant;
17  
18  import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;
19  import static org.mybatis.generator.internal.util.messages.Messages.getString;
20  
21  import java.io.File;
22  import java.io.IOException;
23  import java.sql.SQLException;
24  import java.util.ArrayList;
25  import java.util.HashSet;
26  import java.util.List;
27  import java.util.Properties;
28  import java.util.Set;
29  import java.util.StringTokenizer;
30  
31  import org.apache.tools.ant.BuildException;
32  import org.apache.tools.ant.Project;
33  import org.apache.tools.ant.Task;
34  import org.apache.tools.ant.types.PropertySet;
35  import org.mybatis.generator.api.MyBatisGenerator;
36  import org.mybatis.generator.config.Configuration;
37  import org.mybatis.generator.config.xml.ConfigurationParser;
38  import org.mybatis.generator.exception.InvalidConfigurationException;
39  import org.mybatis.generator.exception.XMLParserException;
40  import org.mybatis.generator.internal.DefaultShellCallback;
41  
42  /**
43   * This is an Ant task that will run the generator. The following is a sample
44   * Ant script that shows how to run the generator from Ant:
45   * 
46   * <pre>
47   *  &lt;project default="genfiles" basedir="."&gt;
48   *    &lt;property name="generated.source.dir" value="${basedir}" /&gt;
49   *    &lt;target name="genfiles" description="Generate the files"&gt;
50   *      &lt;taskdef name="mbgenerator"
51   *               classname="org.mybatis.generator.ant.GeneratorAntTask"
52   *               classpath="mybatis-generator-core-x.x.x.jar" /&gt;
53   *      &lt;mbgenerator overwrite="true" configfile="generatorConfig.xml" verbose="false" &gt;
54   *        &lt;propertyset&gt;
55   *          &lt;propertyref name="generated.source.dir"/&gt;
56   *        &lt;/propertyset&gt;
57   *      &lt;/mbgenerator&gt;
58   *    &lt;/target&gt;
59   *  &lt;/project&gt;
60   * </pre>
61   * 
62   * The task requires that the attribute "configFile" be set to an existing XML
63   * configuration file.
64   * <p>
65   * The task supports these optional attributes:
66   * <ul>
67   * <li>"overwrite" - if true, then existing Java files will be overwritten. if
68   * false (default), then existing Java files will be untouched and the generator
69   * will write new Java files with a unique name</li>
70   * <li>"verbose" - if true, then the generator will log progress messages to the
71   * Ant log. Default is false</li>
72   * <li>"contextIds" - a comma delimited list of contaxtIds to use for this run</li>
73   * <li>"fullyQualifiedTableNames" - a comma delimited list of fully qualified
74   * table names to use for this run</li>
75   * </ul>
76   * 
77   * 
78   * @author Jeff Butler
79   */
80  public class GeneratorAntTask extends Task {
81  
82      private String configfile;
83      private boolean overwrite;
84      private PropertySet propertyset;
85      private boolean verbose;
86      private String contextIds;
87      private String fullyQualifiedTableNames;
88  
89      /**
90       * 
91       */
92      public GeneratorAntTask() {
93          super();
94      }
95  
96      /*
97       * (non-Javadoc)
98       * 
99       * @see org.apache.tools.ant.Task#execute()
100      */
101     @Override
102     public void execute() throws BuildException {
103         if (!stringHasValue(configfile)) {
104             throw new BuildException(getString("RuntimeError.0")); //$NON-NLS-1$
105         }
106 
107         List<String> warnings = new ArrayList<String>();
108 
109         File configurationFile = new File(configfile);
110         if (!configurationFile.exists()) {
111             throw new BuildException(getString(
112                     "RuntimeError.1", configfile)); //$NON-NLS-1$
113         }
114 
115         Set<String> fullyqualifiedTables = new HashSet<String>();
116         if (stringHasValue(fullyQualifiedTableNames)) {
117             StringTokenizer st = new StringTokenizer(fullyQualifiedTableNames,
118                     ","); //$NON-NLS-1$
119             while (st.hasMoreTokens()) {
120                 String s = st.nextToken().trim();
121                 if (s.length() > 0) {
122                     fullyqualifiedTables.add(s);
123                 }
124             }
125         }
126 
127         Set<String> contexts = new HashSet<String>();
128         if (stringHasValue(contextIds)) {
129             StringTokenizer st = new StringTokenizer(contextIds, ","); //$NON-NLS-1$
130             while (st.hasMoreTokens()) {
131                 String s = st.nextToken().trim();
132                 if (s.length() > 0) {
133                     contexts.add(s);
134                 }
135             }
136         }
137 
138         try {
139             Properties p = propertyset == null ? null : propertyset
140                     .getProperties();
141 
142             ConfigurationParser cp = new ConfigurationParser(p, warnings);
143             Configuration config = cp.parseConfiguration(configurationFile);
144 
145             DefaultShellCallback callback = new DefaultShellCallback(overwrite);
146 
147             MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
148 
149             myBatisGenerator.generate(new AntProgressCallback(this, verbose), contexts,
150                     fullyqualifiedTables);
151 
152         } catch (XMLParserException e) {
153             for (String error : e.getErrors()) {
154                 log(error, Project.MSG_ERR);
155             }
156 
157             throw new BuildException(e.getMessage());
158         } catch (SQLException e) {
159             throw new BuildException(e.getMessage());
160         } catch (IOException e) {
161             throw new BuildException(e.getMessage());
162         } catch (InvalidConfigurationException e) {
163             for (String error : e.getErrors()) {
164                 log(error, Project.MSG_ERR);
165             }
166 
167             throw new BuildException(e.getMessage());
168         } catch (InterruptedException e) {
169             // ignore (will never happen with the DefaultShellCallback)
170         } catch (Exception e) {
171             e.printStackTrace();
172             throw new BuildException(e.getMessage());
173         }
174 
175         for (String error : warnings) {
176             log(error, Project.MSG_WARN);
177         }
178     }
179 
180     /**
181      * @return Returns the configfile.
182      */
183     public String getConfigfile() {
184         return configfile;
185     }
186 
187     /**
188      * @param configfile
189      *            The configfile to set.
190      */
191     public void setConfigfile(String configfile) {
192         this.configfile = configfile;
193     }
194 
195     /**
196      * @return Returns the overwrite.
197      */
198     public boolean isOverwrite() {
199         return overwrite;
200     }
201 
202     /**
203      * @param overwrite
204      *            The overwrite to set.
205      */
206     public void setOverwrite(boolean overwrite) {
207         this.overwrite = overwrite;
208     }
209 
210     public PropertySet createPropertyset() {
211         if (propertyset == null) {
212             propertyset = new PropertySet();
213         }
214 
215         return propertyset;
216     }
217 
218     public boolean isVerbose() {
219         return verbose;
220     }
221 
222     public void setVerbose(boolean verbose) {
223         this.verbose = verbose;
224     }
225 
226     public String getContextIds() {
227         return contextIds;
228     }
229 
230     public void setContextIds(String contextIds) {
231         this.contextIds = contextIds;
232     }
233 
234     public String getFullyQualifiedTableNames() {
235         return fullyQualifiedTableNames;
236     }
237 
238     public void setFullyQualifiedTableNames(String fullyQualifiedTableNames) {
239         this.fullyQualifiedTableNames = fullyQualifiedTableNames;
240     }
241 }