View Javadoc
1   package org.codehaus.modello.plugin;
2   
3   /*
4    * Copyright (c) 2004, Codehaus.org
5    *
6    * Permission is hereby granted, free of charge, to any person obtaining a copy of
7    * this software and associated documentation files (the "Software"), to deal in
8    * the Software without restriction, including without limitation the rights to
9    * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10   * of the Software, and to permit persons to whom the Software is furnished to do
11   * so, subject to the following conditions:
12   *
13   * The above copyright notice and this permission notice shall be included in all
14   * copies or substantial portions of the Software.
15   *
16   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22   * SOFTWARE.
23   */
24  
25  import javax.inject.Inject;
26  
27  import java.io.File;
28  import java.io.FilterWriter;
29  import java.io.IOException;
30  import java.io.Writer;
31  import java.nio.charset.Charset;
32  import java.nio.file.Path;
33  import java.util.ArrayList;
34  import java.util.List;
35  import java.util.Properties;
36  
37  import org.codehaus.modello.ModelloException;
38  import org.codehaus.modello.ModelloParameterConstants;
39  import org.codehaus.modello.ModelloRuntimeException;
40  import org.codehaus.modello.model.Model;
41  import org.codehaus.modello.model.ModelAssociation;
42  import org.codehaus.modello.model.ModelClass;
43  import org.codehaus.modello.model.ModelDefault;
44  import org.codehaus.modello.model.ModelField;
45  import org.codehaus.modello.model.Version;
46  import org.codehaus.plexus.build.BuildContext;
47  import org.codehaus.plexus.util.StringUtils;
48  import org.codehaus.plexus.util.io.CachingWriter;
49  import org.slf4j.Logger;
50  import org.slf4j.LoggerFactory;
51  
52  /**
53   * @author <a href="mailto:jason@modello.org">Jason van Zyl</a>
54   * @author <a href="mailto:evenisse@codehaus.org">Emmanuel Venisse</a>
55   */
56  public abstract class AbstractModelloGenerator implements ModelloGenerator {
57      private final Logger logger = LoggerFactory.getLogger(getClass());
58  
59      private Model model;
60  
61      private File outputDirectory;
62  
63      private Version generatedVersion;
64  
65      private boolean packageWithVersion;
66  
67      private String encoding;
68  
69      @Inject
70      private BuildContext buildContext;
71  
72      protected Logger getLogger() {
73          return logger;
74      }
75  
76      protected void initialize(Model model, Properties parameters) throws ModelloException {
77          this.model = model;
78  
79          outputDirectory = new File(getParameter(parameters, ModelloParameterConstants.OUTPUT_DIRECTORY));
80  
81          String version = getParameter(parameters, ModelloParameterConstants.VERSION);
82  
83          generatedVersion = new Version(version);
84  
85          packageWithVersion = Boolean.valueOf(getParameter(parameters, ModelloParameterConstants.PACKAGE_WITH_VERSION));
86  
87          encoding = parameters.getProperty(ModelloParameterConstants.ENCODING);
88      }
89  
90      protected Model getModel() {
91          return model;
92      }
93  
94      protected Version getGeneratedVersion() {
95          return generatedVersion;
96      }
97  
98      protected boolean isPackageWithVersion() {
99          return packageWithVersion;
100     }
101 
102     public File getOutputDirectory() {
103         return outputDirectory;
104     }
105 
106     protected String getEncoding() {
107         return encoding;
108     }
109 
110     protected String getHeader() {
111         String version = getClass().getPackage().getImplementationVersion();
112         return "=================== DO NOT EDIT THIS FILE ====================\n"
113                 + "Generated by Modello" + ((version == null) ? "" : (' ' + version)) + ",\n"
114                 + "any modifications will be overwritten.\n"
115                 + "==============================================================";
116     }
117 
118     protected boolean isClassInModel(String fieldType, Model model) {
119         try {
120             return model.getClass(fieldType, generatedVersion) != null;
121         } catch (Exception e) {
122         }
123 
124         return false;
125     }
126 
127     /**
128      * Return the child fields of this class.
129      * @param modelClass current class
130      * @return the list of fields of this class
131      */
132     protected List<ModelField> getFieldsForClass(ModelClass modelClass) {
133         List<ModelField> fields = new ArrayList<ModelField>();
134 
135         while (modelClass != null) {
136             fields.addAll(modelClass.getFields(getGeneratedVersion()));
137 
138             String superClass = modelClass.getSuperClass();
139             if (superClass != null) {
140                 modelClass = getModel().getClass(superClass, getGeneratedVersion());
141             } else {
142                 modelClass = null;
143             }
144         }
145 
146         return fields;
147     }
148 
149     protected boolean isInnerAssociation(ModelField field) {
150         return field instanceof ModelAssociation && isClassInModel(((ModelAssociation) field).getTo(), getModel());
151     }
152 
153     protected boolean isMap(String fieldType) {
154         return ModelDefault.MAP.equals(fieldType) || ModelDefault.PROPERTIES.equals(fieldType);
155     }
156 
157     protected boolean isCollection(String fieldType) {
158         return ModelDefault.LIST.equals(fieldType) || ModelDefault.SET.equals(fieldType);
159     }
160 
161     protected String capitalise(String str) {
162         if (StringUtils.isEmpty(str)) {
163             return str;
164         }
165 
166         return new StringBuilder(str.length())
167                 .append(Character.toTitleCase(str.charAt(0)))
168                 .append(str.substring(1))
169                 .toString();
170     }
171 
172     public static String singular(String name) {
173         if (StringUtils.isEmpty(name)) {
174             return name;
175         }
176 
177         if (name.endsWith("ies")) {
178             return name.substring(0, name.length() - 3) + "y";
179         } else if (name.endsWith("es") && name.endsWith("ches")) {
180             return name.substring(0, name.length() - 2);
181         } else if (name.endsWith("xes")) {
182             return name.substring(0, name.length() - 2);
183         } else if (name.endsWith("s") && (name.length() != 1)) {
184             return name.substring(0, name.length() - 1);
185         }
186 
187         return name;
188     }
189 
190     public static String uncapitalise(String str) {
191         if (StringUtils.isEmpty(str)) {
192             return str;
193         }
194 
195         return new StringBuilder(str.length())
196                 .append(Character.toLowerCase(str.charAt(0)))
197                 .append(str.substring(1))
198                 .toString();
199     }
200 
201     // ----------------------------------------------------------------------
202     // Text utils
203     // ----------------------------------------------------------------------
204 
205     protected boolean isEmpty(String string) {
206         return string == null || string.trim().length() == 0;
207     }
208 
209     // ----------------------------------------------------------------------
210     // Parameter utils
211     // ----------------------------------------------------------------------
212 
213     /**
214      * @deprecated Use {@link #getParameter(Properties, String)} instead
215      * @param name parameter name
216      * @param parameters the properties
217      * @return the parameter value
218      */
219     @Deprecated
220     protected String getParameter(String name, Properties parameters) {
221         return getParameter(parameters, name);
222     }
223 
224     protected String getParameter(Properties parameters, String name) {
225         String value = parameters.getProperty(name);
226 
227         if (value == null) {
228             throw new ModelloRuntimeException("Missing parameter '" + name + "'.");
229         }
230 
231         return value;
232     }
233 
234     protected String getParameter(Properties parameters, String name, String defaultValue) {
235         return parameters.getProperty(name, defaultValue);
236     }
237 
238     protected BuildContext getBuildContext() {
239         return buildContext;
240     }
241 
242     protected Writer newWriter(Path path) throws IOException {
243         Charset charset = getEncoding() != null ? Charset.forName(getEncoding()) : Charset.defaultCharset();
244         return newWriter(path, charset);
245     }
246 
247     protected Writer newWriter(Path path, Charset charset) throws IOException {
248         CachingWriter cachingWriter = new CachingWriter(path, charset);
249         return new FilterWriter(cachingWriter) {
250             @Override
251             public void close() throws IOException {
252                 super.close();
253                 if (cachingWriter.isModified()) {
254                     getBuildContext().refresh(path.toFile());
255                 } else {
256                     getLogger().debug("The contents of the file " + path + " matches, skipping writing file.");
257                 }
258             }
259         };
260     }
261 }