KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cayenne > gen > ImportUtils


1 /*****************************************************************
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements. See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership. The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied. See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  ****************************************************************/

19
20
21 package org.apache.cayenne.gen;
22
23 import java.util.ArrayList JavaDoc;
24 import java.util.Collections JavaDoc;
25 import java.util.Comparator JavaDoc;
26 import java.util.HashMap JavaDoc;
27 import java.util.Iterator JavaDoc;
28 import java.util.List JavaDoc;
29 import java.util.Map JavaDoc;
30
31 import org.apache.cayenne.util.Util;
32
33 /**
34  * Methods for mangling strings.
35  *
36  * @author Mike Kienenberger
37  */

38 public class ImportUtils {
39
40     public static final String JavaDoc importOrdering[] = new String JavaDoc[] {
41         "java.", "javax.", "org.", "com." };
42
43     static final String JavaDoc primitives[] = new String JavaDoc[] {
44             "long", "double", "byte", "boolean", "float", "short", "int"
45     };
46     
47     static final String JavaDoc primitiveClasses[] = new String JavaDoc[] {
48             Long JavaDoc.class.getName(), Double JavaDoc.class.getName(), Byte JavaDoc.class.getName(),
49             Boolean JavaDoc.class.getName(), Float JavaDoc.class.getName(), Short JavaDoc.class.getName(),
50             Integer JavaDoc.class.getName()
51     };
52     
53     static Map JavaDoc classesForPrimitives = Util.toMap(primitives, primitiveClasses);
54     static Map JavaDoc primitivesForClasses = Util.toMap(primitiveClasses, primitives);
55
56     protected Map JavaDoc importTypesMap = new HashMap JavaDoc();
57     protected Map JavaDoc reservedImportTypesMap = new HashMap JavaDoc(); // Types forced to be FQN
58

59     protected String JavaDoc packageName;
60     
61     public ImportUtils()
62     {
63         super();
64     }
65     
66     protected boolean canRegisterType(String JavaDoc typeName)
67     {
68         // Not sure why this would ever happen, but it did
69
if (null == typeName) return false;
70         
71         StringUtils stringUtils = StringUtils.getInstance();
72         String JavaDoc typeClassName = stringUtils.stripPackageName(typeName);
73         String JavaDoc typePackageName = stringUtils.stripClass(typeName);
74         
75         if (typePackageName.length() == 0) return false; // disallow non-packaged types (primatives, probably)
76
if ("java.lang".equals(typePackageName)) return false;
77         
78         // Can only have one type -- rest must use fqn
79
if (reservedImportTypesMap.containsKey(typeClassName)) return false;
80         if (importTypesMap.containsKey(typeClassName)) return false;
81         
82         return true;
83     }
84     
85     /**
86      * Reserve a fully-qualified data type class name so it cannot be used by another class.
87      * No import statements will be generated for reserved types.
88      * Typically, this is the fully-qualified class name of the class being generated.
89      * @param typeName FQ data type class name.
90      */

91     public void addReservedType(String JavaDoc typeName)
92     {
93         if (! canRegisterType(typeName)) return;
94         
95         StringUtils stringUtils = StringUtils.getInstance();
96         String JavaDoc typeClassName = stringUtils.stripPackageName(typeName);
97         
98         reservedImportTypesMap.put(typeClassName, typeName);
99     }
100     
101     /**
102      * Register a fully-qualified data type class name.
103      * For example, org.apache.cayenne.CayenneDataObject
104      * @param typeName FQ data type class name.
105      */

106     public void addType(String JavaDoc typeName)
107     {
108         if (! canRegisterType(typeName)) return;
109         
110         StringUtils stringUtils = StringUtils.getInstance();
111         String JavaDoc typePackageName = stringUtils.stripClass(typeName);
112         String JavaDoc typeClassName = stringUtils.stripPackageName(typeName);
113         
114         if (typePackageName.equals(packageName)) return;
115
116         importTypesMap.put(typeClassName, typeName);
117     }
118     
119     /**
120      * Add the package name to use for this importUtil invocation.
121      * @param packageName
122      */

123     public void setPackage(String JavaDoc packageName)
124     {
125         this.packageName = packageName;
126     }
127     
128     /**
129      * Performs processing similar to <code>formatJavaType(String)</code>, with special
130      * handling of primitive types and their Java class counterparts. This method allows
131      * users to make a decision whether to use primitives or not, regardless of how type
132      * is mapped.
133      */

134     public String JavaDoc formatJavaType(String JavaDoc typeName, boolean usePrimitives) {
135         if (usePrimitives) {
136             String JavaDoc primitive = (String JavaDoc) primitivesForClasses.get(typeName);
137             return (primitive != null) ? primitive : formatJavaType(typeName);
138         }
139         else {
140             String JavaDoc primitiveClass = (String JavaDoc) classesForPrimitives.get(typeName);
141             return (primitiveClass != null)
142                     ? formatJavaType(primitiveClass)
143                     : formatJavaType(typeName);
144         }
145     }
146     
147     /**
148      * Removes registered package and non-reserved registered type name prefixes from java types
149      */

150     public String JavaDoc formatJavaType(String JavaDoc typeName) {
151         if (typeName != null) {
152             StringUtils stringUtils = StringUtils.getInstance();
153             String JavaDoc typeClassName = stringUtils.stripPackageName(typeName);
154             
155             if (! reservedImportTypesMap.containsKey(typeClassName))
156             {
157                 if (importTypesMap.containsKey(typeClassName))
158                 {
159                     if (typeName.equals(importTypesMap.get(typeClassName))) return typeClassName;
160                 }
161             }
162             
163             String JavaDoc typePackageName = stringUtils.stripClass(typeName);
164             if ("java.lang".equals(typePackageName)) return typeClassName;
165             if ((null != packageName) && (packageName.equals(typePackageName)))
166                 return typeClassName;
167         }
168
169         return typeName;
170     }
171     
172     /**
173      * Generate package and list of import statements based on the registered types.
174      */

175     public String JavaDoc generate()
176     {
177         StringBuffer JavaDoc outputBuffer = new StringBuffer JavaDoc();
178
179         if (null != packageName)
180         {
181             outputBuffer.append("package ");
182             outputBuffer.append(packageName);
183             outputBuffer.append(';');
184             outputBuffer.append(System.getProperty("line.separator"));
185             outputBuffer.append(System.getProperty("line.separator"));
186         }
187
188         List JavaDoc typesList = new ArrayList JavaDoc(importTypesMap.values());
189         Collections.sort(typesList, new Comparator JavaDoc() {
190
191             public int compare(Object JavaDoc o1, Object JavaDoc o2) {
192                 
193                 String JavaDoc s1 = (String JavaDoc)o1;
194                 String JavaDoc s2 = (String JavaDoc)o2;
195                 
196                 for (int index = 0; index < importOrdering.length; index++) {
197                     String JavaDoc ordering = importOrdering[index];
198                     
199                     if ( (s1.startsWith(ordering)) && (!s2.startsWith(ordering)) )
200                         return -1;
201                     if ( (!s1.startsWith(ordering)) && (s2.startsWith(ordering)) )
202                         return 1;
203                 }
204                     
205                 return s1.compareTo(s2);
206             }
207         });
208         
209         String JavaDoc lastStringPrefix = null;
210         Iterator JavaDoc typesIterator = typesList.iterator();
211         while (typesIterator.hasNext()) {
212             String JavaDoc typeName = (String JavaDoc)typesIterator.next();
213
214             // Output another newline if we're in a different root package.
215
// Find root package
216
String JavaDoc thisStringPrefix = typeName;
217             int dotIndex = typeName.indexOf('.');
218             if (-1 != dotIndex)
219             {
220                 thisStringPrefix = typeName.substring(0, dotIndex);
221             }
222             // if this isn't the first import,
223
if (null != lastStringPrefix)
224             {
225                 // and it's different from the last import
226
if (false == thisStringPrefix.equals(lastStringPrefix))
227                 {
228                     // output a newline
229
outputBuffer.append(System.getProperty("line.separator"));
230                 }
231             }
232             lastStringPrefix = thisStringPrefix;
233
234             outputBuffer.append("import ");
235             outputBuffer.append(typeName);
236             outputBuffer.append(';');
237             if (typesIterator.hasNext())
238             {
239                 outputBuffer.append(System.getProperty("line.separator"));
240             }
241         }
242
243         return outputBuffer.toString();
244     }
245 }
246
Popular Tags