001    /**
002     * Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.portal.kernel.util;
016    
017    import com.liferay.portal.kernel.io.unsync.UnsyncBufferedReader;
018    import com.liferay.portal.kernel.io.unsync.UnsyncStringReader;
019    import com.liferay.portal.kernel.log.Log;
020    import com.liferay.portal.kernel.log.LogFactoryUtil;
021    
022    import java.io.File;
023    import java.io.FileReader;
024    import java.io.IOException;
025    import java.io.Reader;
026    import java.io.StreamTokenizer;
027    
028    import java.net.URI;
029    import java.net.URISyntaxException;
030    import java.net.URL;
031    
032    import java.util.ArrayList;
033    import java.util.HashSet;
034    import java.util.List;
035    import java.util.Set;
036    import java.util.regex.Matcher;
037    import java.util.regex.Pattern;
038    
039    /**
040     * @author Brian Wing Shun Chan
041     * @author Sandeep Soni
042     */
043    public class ClassUtil {
044    
045            public static Set<String> getClasses(File file) throws IOException {
046                    String fileName = file.getName();
047    
048                    if (fileName.endsWith(".java")) {
049                            fileName = fileName.substring(0, fileName.length() - 5);
050                    }
051    
052                    return getClasses(
053                            new UnsyncBufferedReader(new FileReader(file)), fileName);
054            }
055    
056            public static Set<String> getClasses(Reader reader, String className)
057                    throws IOException {
058    
059                    Set<String> classes = new HashSet<String>();
060    
061                    StreamTokenizer st = new StreamTokenizer(reader);
062    
063                    _setupParseTableForAnnotationProcessing(st);
064    
065                    while (st.nextToken() != StreamTokenizer.TT_EOF) {
066                            if (st.ttype == StreamTokenizer.TT_WORD) {
067                                    if (st.sval.equals("class") || st.sval.equals("enum") ||
068                                            st.sval.equals("interface") ||
069                                            st.sval.equals("@interface")) {
070    
071                                            break;
072                                    }
073                                    else if (st.sval.startsWith("@")) {
074                                            st.ordinaryChar(' ');
075                                            st.wordChars('=', '=');
076    
077                                            String[] las = _processAnnotation(st.sval, st);
078    
079                                            for (int i = 0; i < las.length; i++) {
080                                                    classes.add(las[i]);
081                                            }
082    
083                                            _setupParseTableForAnnotationProcessing(st);
084                                    }
085                            }
086                    }
087    
088                    _setupParseTable(st);
089    
090                    while (st.nextToken() != StreamTokenizer.TT_EOF) {
091                            if (st.ttype == StreamTokenizer.TT_WORD) {
092                                    if (st.sval.indexOf('.') >= 0) {
093                                            classes.add(st.sval.substring(0, st.sval.indexOf('.')));
094                                    }
095                                    else {
096                                            classes.add(st.sval);
097                                    }
098                            }
099                            else if (st.ttype != StreamTokenizer.TT_NUMBER &&
100                                             st.ttype != StreamTokenizer.TT_EOL) {
101    
102                                    if (Character.isUpperCase((char)st.ttype)) {
103                                            classes.add(String.valueOf((char)st.ttype));
104                                    }
105                            }
106                    }
107    
108                    classes.remove(className);
109    
110                    return classes;
111            }
112    
113            public static String getParentPath(
114                    ClassLoader classLoader, String className) {
115    
116                    if (_log.isDebugEnabled()) {
117                            _log.debug("Class name " + className);
118                    }
119    
120                    if (!className.endsWith(_CLASS_EXTENSION)) {
121                            className += _CLASS_EXTENSION;
122                    }
123    
124                    className = StringUtil.replace(
125                            className, CharPool.PERIOD, CharPool.SLASH);
126    
127                    className = StringUtil.replace(className, "/class", _CLASS_EXTENSION);
128    
129                    URL url = classLoader.getResource(className);
130    
131                    String path = null;
132    
133                    try {
134                            path = url.getPath();
135    
136                            URI uri = new URI(path);
137    
138                            String scheme = uri.getScheme();
139    
140                            if (path.contains(StringPool.EXCLAMATION) &&
141                                    ((scheme == null) || (scheme.length() <= 1))) {
142    
143                                    if (!path.startsWith(StringPool.SLASH)) {
144                                            path = StringPool.SLASH + path;
145                                    }
146                            }
147                            else {
148                                    path = uri.getPath();
149                            }
150                    }
151                    catch (URISyntaxException urise) {
152                            path = url.getFile();
153                    }
154    
155                    if (_log.isDebugEnabled()) {
156                            _log.debug("Path " + path);
157                    }
158    
159                    int pos = path.indexOf(className);
160    
161                    String parentPath = path.substring(0, pos);
162    
163                    if (parentPath.startsWith("jar:")) {
164                            parentPath = parentPath.substring(4, parentPath.length());
165                    }
166    
167                    if (parentPath.startsWith("file:/")) {
168                            parentPath = parentPath.substring(6, parentPath.length());
169                    }
170    
171                    if (_log.isDebugEnabled()) {
172                            _log.debug("Parent path " + parentPath);
173                    }
174    
175                    return parentPath;
176            }
177    
178            public static boolean isSubclass(Class<?> a, Class<?> b) {
179                    if (a == b) {
180                            return true;
181                    }
182    
183                    if (a == null || b == null) {
184                            return false;
185                    }
186    
187                    for (Class<?> x = a; x != null; x = x.getSuperclass()) {
188                            if (x == b) {
189                                    return true;
190                            }
191    
192                            if (b.isInterface()) {
193                                    Class<?>[] interfaces = x.getInterfaces();
194    
195                                    for (int i = 0; i < interfaces.length; i++) {
196                                            if (isSubclass(interfaces[i], b)) {
197                                                    return true;
198                                            }
199                                    }
200                            }
201                    }
202    
203                    return false;
204            }
205    
206            public static boolean isSubclass(Class<?> a, String s) {
207                    if (a == null || s == null) {
208                            return false;
209                    }
210    
211                    if (a.getName().equals(s)) {
212                            return true;
213                    }
214    
215                    for (Class<?> x = a; x != null; x = x.getSuperclass()) {
216                            if (x.getName().equals(s)) {
217                                    return true;
218                            }
219    
220                            Class<?>[] interfaces = x.getInterfaces();
221    
222                            for (int i = 0; i < interfaces.length; i++) {
223                                    if (isSubclass(interfaces[i], s)) {
224                                            return true;
225                                    }
226                            }
227                    }
228    
229                    return false;
230            }
231    
232            private static String[] _processAnnotation(String s, StreamTokenizer st)
233                    throws IOException {
234    
235                    s = s.trim();
236    
237                    List<String> tokens = new ArrayList<String>();
238    
239                    Matcher annotationNameMatcher = _ANNOTATION_NAME_REGEXP.matcher(s);
240                    Matcher annotationParametersMatcher =
241                            _ANNOTATION_PARAMETERS_REGEXP.matcher(s);
242    
243                    if (annotationNameMatcher.matches()) {
244                            String annotationName = annotationNameMatcher.group();
245    
246                            tokens.add(annotationName.replace("@", ""));
247                    }
248                    else if (annotationParametersMatcher.matches()) {
249                            if (!s.trim().endsWith(")")) {
250                                    while (st.nextToken() != StreamTokenizer.TT_EOF) {
251                                            if (st.ttype == StreamTokenizer.TT_WORD) {
252                                                    s += st.sval;
253                                                    if (s.trim().endsWith(")")) {
254                                                            break;
255                                                    }
256                                            }
257                                    }
258                            }
259    
260                            annotationParametersMatcher =
261                                    _ANNOTATION_PARAMETERS_REGEXP.matcher(s);
262    
263                            if (annotationParametersMatcher.matches()) {
264                                    String annotationName =
265                                            annotationParametersMatcher.group(1);
266                                    String annotationParameters =
267                                            annotationParametersMatcher.group(2);
268    
269                                    tokens.add(annotationName.replace("@", ""));
270    
271                                    tokens = _processAnnotationParameters(
272                                            annotationParameters,tokens);
273                            }
274                    }
275    
276                    return tokens.toArray(new String[tokens.size()]);
277            }
278    
279            private static List<String> _processAnnotationParameters(
280                            String s, List<String> tokens)
281                    throws IOException {
282    
283                    StreamTokenizer st = new StreamTokenizer(new UnsyncStringReader(s));
284    
285                    _setupParseTable(st);
286    
287                    while (st.nextToken() != StreamTokenizer.TT_EOF) {
288                            if (st.ttype == StreamTokenizer.TT_WORD) {
289                                    if (st.sval.indexOf('.') >= 0) {
290                                            tokens.add(st.sval.substring(0, st.sval.indexOf('.')));
291                                    }
292                                    else {
293                                            tokens.add(st.sval);
294                                    }
295                            }
296                            else if ((st.ttype != StreamTokenizer.TT_NUMBER) &&
297                                             (st.ttype != StreamTokenizer.TT_EOL)) {
298    
299                                    if (Character.isUpperCase((char)st.ttype)) {
300                                            tokens.add(String.valueOf((char)st.ttype));
301                                    }
302                            }
303                    }
304    
305                    return tokens;
306            }
307    
308            private static void _setupParseTable(StreamTokenizer st) {
309                    st.resetSyntax();
310                    st.slashSlashComments(true);
311                    st.slashStarComments(true);
312                    st.wordChars('a', 'z');
313                    st.wordChars('A', 'Z');
314                    st.wordChars('.', '.');
315                    st.wordChars('0', '9');
316                    st.wordChars('_', '_');
317                    st.lowerCaseMode(false);
318                    st.eolIsSignificant(false);
319                    st.quoteChar('"');
320                    st.quoteChar('\'');
321                    st.parseNumbers();
322            }
323    
324            private static void _setupParseTableForAnnotationProcessing(
325                    StreamTokenizer st) {
326    
327                    _setupParseTable(st);
328    
329                    st.wordChars('@', '@');
330                    st.wordChars('(', '(');
331                    st.wordChars(')', ')');
332                    st.wordChars('{', '{');
333                    st.wordChars('}', '}');
334                    st.wordChars(',',',');
335            }
336    
337            private static final Pattern _ANNOTATION_NAME_REGEXP =
338                    Pattern.compile("@(\\w+)$");
339    
340            private static final Pattern _ANNOTATION_PARAMETERS_REGEXP =
341                    Pattern.compile("@(\\w+)\\({0,1}\\{{0,1}([^)}]+)\\}{0,1}\\){0,1}");
342    
343            private static final String _CLASS_EXTENSION = ".class";
344    
345            private static Log _log = LogFactoryUtil.getLog(ClassUtil.class);
346    
347    }