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.internal.util;
17  
18  import static org.mybatis.generator.internal.util.StringUtility.isTrue;
19  
20  import java.util.Locale;
21  import java.util.Properties;
22  
23  import org.mybatis.generator.api.IntrospectedColumn;
24  import org.mybatis.generator.api.IntrospectedTable;
25  import org.mybatis.generator.api.dom.java.Field;
26  import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
27  import org.mybatis.generator.api.dom.java.JavaVisibility;
28  import org.mybatis.generator.api.dom.java.Method;
29  import org.mybatis.generator.api.dom.java.Parameter;
30  import org.mybatis.generator.config.Context;
31  import org.mybatis.generator.config.PropertyRegistry;
32  import org.mybatis.generator.config.TableConfiguration;
33  
34  /**
35   * The Class JavaBeansUtil.
36   *
37   * @author Jeff Butler
38   */
39  public class JavaBeansUtil {
40  
41      /**
42       * Instantiates a new java beans util.
43       */
44      private JavaBeansUtil() {
45          super();
46      }
47  
48      /**
49       * JavaBeans rules:
50       * 
51       * eMail > geteMail() firstName > getFirstName() URL $gt; getURL() XAxis > getXAxis() a > getA() B >
52       * invalid - this method assumes that this is not the case. Call getValidPropertyName first. Yaxis > invalid -
53       * this method assumes that this is not the case. Call getValidPropertyName first.
54       *
55       * @param property
56       *            the property
57       * @param fullyQualifiedJavaType
58       *            the fully qualified java type
59       * @return the getter method name
60       */
61      public static String getGetterMethodName(String property,
62              FullyQualifiedJavaType fullyQualifiedJavaType) {
63          StringBuilder sb = new StringBuilder();
64  
65          sb.append(property);
66          if (Character.isLowerCase(sb.charAt(0))) {
67              if (sb.length() == 1 || !Character.isUpperCase(sb.charAt(1))) {
68                  sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
69              }
70          }
71  
72          if (fullyQualifiedJavaType.equals(FullyQualifiedJavaType
73                  .getBooleanPrimitiveInstance())) {
74              sb.insert(0, "is"); //$NON-NLS-1$
75          } else {
76              sb.insert(0, "get"); //$NON-NLS-1$
77          }
78  
79          return sb.toString();
80      }
81  
82      /**
83       * JavaBeans rules:
84       * 
85       * eMail > seteMail() firstName > setFirstName() URL > setURL() XAxis > setXAxis() a > setA() B >
86       * invalid - this method assumes that this is not the case. Call getValidPropertyName first. Yaxis > invalid -
87       * this method assumes that this is not the case. Call getValidPropertyName first.
88       *
89       * @param property
90       *            the property
91       * @return the setter method name
92       */
93      public static String getSetterMethodName(String property) {
94          StringBuilder sb = new StringBuilder();
95  
96          sb.append(property);
97          if (Character.isLowerCase(sb.charAt(0))) {
98              if (sb.length() == 1 || !Character.isUpperCase(sb.charAt(1))) {
99                  sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
100             }
101         }
102 
103         sb.insert(0, "set"); //$NON-NLS-1$
104 
105         return sb.toString();
106     }
107 
108     /**
109      * Gets the camel case string.
110      *
111      * @param inputString
112      *            the input string
113      * @param firstCharacterUppercase
114      *            the first character uppercase
115      * @return the camel case string
116      */
117     public static String getCamelCaseString(String inputString,
118             boolean firstCharacterUppercase) {
119         StringBuilder sb = new StringBuilder();
120 
121         boolean nextUpperCase = false;
122         for (int i = 0; i < inputString.length(); i++) {
123             char c = inputString.charAt(i);
124 
125             switch (c) {
126             case '_':
127             case '-':
128             case '@':
129             case '$':
130             case '#':
131             case ' ':
132             case '/':
133             case '&':
134                 if (sb.length() > 0) {
135                     nextUpperCase = true;
136                 }
137                 break;
138 
139             default:
140                 if (nextUpperCase) {
141                     sb.append(Character.toUpperCase(c));
142                     nextUpperCase = false;
143                 } else {
144                     sb.append(Character.toLowerCase(c));
145                 }
146                 break;
147             }
148         }
149 
150         if (firstCharacterUppercase) {
151             sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
152         }
153 
154         return sb.toString();
155     }
156 
157     /**
158      * This method ensures that the specified input string is a valid Java property name. The rules are as follows:
159      * 
160      * 1. If the first character is lower case, then OK 2. If the first two characters are upper case, then OK 3. If the
161      * first character is upper case, and the second character is lower case, then the first character should be made
162      * lower case
163      * 
164      * eMail &gt; eMail firstName &gt; firstName URL &gt; URL XAxis &gt; XAxis a &gt; a B &gt; b Yaxis &gt; yaxis
165      *
166      * @param inputString
167      *            the input string
168      * @return the valid property name
169      */
170     public static String getValidPropertyName(String inputString) {
171         String answer;
172 
173         if (inputString == null) {
174             answer = null;
175         } else if (inputString.length() < 2) {
176             answer = inputString.toLowerCase(Locale.US);
177         } else {
178             if (Character.isUpperCase(inputString.charAt(0))
179                     && !Character.isUpperCase(inputString.charAt(1))) {
180                 answer = inputString.substring(0, 1).toLowerCase(Locale.US)
181                         + inputString.substring(1);
182             } else {
183                 answer = inputString;
184             }
185         }
186 
187         return answer;
188     }
189 
190     /**
191      * Gets the java beans getter.
192      *
193      * @param introspectedColumn
194      *            the introspected column
195      * @param context
196      *            the context
197      * @param introspectedTable
198      *            the introspected table
199      * @return the java beans getter
200      */
201     public static Method getJavaBeansGetter(IntrospectedColumn introspectedColumn,
202             Context context,
203             IntrospectedTable introspectedTable) {
204         FullyQualifiedJavaType fqjt = introspectedColumn
205                 .getFullyQualifiedJavaType();
206         String property = introspectedColumn.getJavaProperty();
207 
208         Method method = new Method();
209         method.setVisibility(JavaVisibility.PUBLIC);
210         method.setReturnType(fqjt);
211         method.setName(getGetterMethodName(property, fqjt));
212         context.getCommentGenerator().addGetterComment(method,
213                 introspectedTable, introspectedColumn);
214 
215         StringBuilder sb = new StringBuilder();
216         sb.append("return "); //$NON-NLS-1$
217         sb.append(property);
218         sb.append(';');
219         method.addBodyLine(sb.toString());
220 
221         return method;
222     }
223 
224     /**
225      * Gets the java beans field.
226      *
227      * @param introspectedColumn
228      *            the introspected column
229      * @param context
230      *            the context
231      * @param introspectedTable
232      *            the introspected table
233      * @return the java beans field
234      */
235     public static Field getJavaBeansField(IntrospectedColumn introspectedColumn,
236             Context context,
237             IntrospectedTable introspectedTable) {
238         FullyQualifiedJavaType fqjt = introspectedColumn
239                 .getFullyQualifiedJavaType();
240         String property = introspectedColumn.getJavaProperty();
241 
242         Field field = new Field();
243         field.setVisibility(JavaVisibility.PRIVATE);
244         field.setType(fqjt);
245         field.setName(property);
246         context.getCommentGenerator().addFieldComment(field,
247                 introspectedTable, introspectedColumn);
248 
249         return field;
250     }
251 
252     /**
253      * Gets the java beans setter.
254      *
255      * @param introspectedColumn
256      *            the introspected column
257      * @param context
258      *            the context
259      * @param introspectedTable
260      *            the introspected table
261      * @return the java beans setter
262      */
263     public static Method getJavaBeansSetter(IntrospectedColumn introspectedColumn,
264             Context context,
265             IntrospectedTable introspectedTable) {
266         FullyQualifiedJavaType fqjt = introspectedColumn
267                 .getFullyQualifiedJavaType();
268         String property = introspectedColumn.getJavaProperty();
269 
270         Method method = new Method();
271         method.setVisibility(JavaVisibility.PUBLIC);
272         method.setName(getSetterMethodName(property));
273         method.addParameter(new Parameter(fqjt, property));
274         context.getCommentGenerator().addSetterComment(method,
275                 introspectedTable, introspectedColumn);
276 
277         StringBuilder sb = new StringBuilder();
278         if (introspectedColumn.isStringColumn() && isTrimStringsEnabled(introspectedColumn)) {
279             sb.append("this."); //$NON-NLS-1$
280             sb.append(property);
281             sb.append(" = "); //$NON-NLS-1$
282             sb.append(property);
283             sb.append(" == null ? null : "); //$NON-NLS-1$
284             sb.append(property);
285             sb.append(".trim();"); //$NON-NLS-1$
286             method.addBodyLine(sb.toString());
287         } else {
288             sb.append("this."); //$NON-NLS-1$
289             sb.append(property);
290             sb.append(" = "); //$NON-NLS-1$
291             sb.append(property);
292             sb.append(';');
293             method.addBodyLine(sb.toString());
294         }
295 
296         return method;
297     }
298 
299     /**
300      * Checks if is trim strings enabled.
301      *
302      * @param context
303      *            the context
304      * @return true, if is trim strings enabled
305      */
306     private static boolean isTrimStringsEnabled(Context context) {
307         Properties properties = context
308                 .getJavaModelGeneratorConfiguration().getProperties();
309         boolean rc = isTrue(properties
310                 .getProperty(PropertyRegistry.MODEL_GENERATOR_TRIM_STRINGS));
311         return rc;
312     }
313 
314     /**
315      * Checks if is trim strings enabled.
316      *
317      * @param table
318      *            the table
319      * @return true, if is trim strings enabled
320      */
321     private static boolean isTrimStringsEnabled(IntrospectedTable table) {
322         TableConfiguration tableConfiguration = table.getTableConfiguration();
323         String trimSpaces = tableConfiguration.getProperties().getProperty(PropertyRegistry.MODEL_GENERATOR_TRIM_STRINGS);
324         if (trimSpaces != null) {
325             return isTrue(trimSpaces);
326         }
327         return isTrimStringsEnabled(table.getContext());
328     }
329 
330     /**
331      * Checks if is trim strings enabled.
332      *
333      * @param column
334      *            the column
335      * @return true, if is trim strings enabled
336      */
337     private static boolean isTrimStringsEnabled(IntrospectedColumn column) {
338         String trimSpaces = column.getProperties().getProperty(PropertyRegistry.MODEL_GENERATOR_TRIM_STRINGS);
339         if (trimSpaces != null) {
340             return isTrue(trimSpaces);
341         }
342         return isTrimStringsEnabled(column.getIntrospectedTable());
343     }
344 
345 }