KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > riotfamily > common > util > PackageLister


1 /* ***** BEGIN LICENSE BLOCK *****
2  * Version: MPL 1.1
3  * The contents of this file are subject to the Mozilla Public License Version
4  * 1.1 (the "License"); you may not use this file except in compliance with
5  * the License. You may obtain a copy of the License at
6  * http://www.mozilla.org/MPL/
7  *
8  * Software distributed under the License is distributed on an "AS IS" basis,
9  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
10  * for the specific language governing rights and limitations under the
11  * License.
12  *
13  * The Original Code is Riot.
14  *
15  * The Initial Developer of the Original Code is
16  * Neteye GmbH.
17  * Portions created by the Initial Developer are Copyright (C) 2006
18  * the Initial Developer. All Rights Reserved.
19  *
20  * Contributor(s):
21  * Felix Gnass [fgnass at neteye dot de]
22  *
23  * ***** END LICENSE BLOCK ***** */

24 package org.riotfamily.common.util;
25
26 import java.util.ArrayList JavaDoc;
27 import java.util.Collection JavaDoc;
28 import java.util.Collections JavaDoc;
29 import java.util.Comparator JavaDoc;
30 import java.util.HashMap JavaDoc;
31
32 import org.springframework.beans.support.PropertyComparator;
33
34 public final class PackageLister {
35
36     private static final Comparator JavaDoc PACKAGE_COMPARATOR =
37             new PropertyComparator("implementationTitle", true, true);
38     
39     private PackageLister() {
40     }
41
42     public static Collection JavaDoc listPackages(String JavaDoc[] patterns) {
43         HashMap JavaDoc map = new HashMap JavaDoc();
44         Package JavaDoc[] packages = Package.getPackages();
45         for (int i = 0; i < packages.length; i++) {
46             String JavaDoc name = packages[i].getImplementationTitle();
47             if (name != null && matches(packages[i].getName(), patterns)) {
48                 map.put(name, packages[i]);
49             }
50         }
51         ArrayList JavaDoc result = new ArrayList JavaDoc(map.values());
52         Collections.sort(result, PACKAGE_COMPARATOR);
53         return result;
54     }
55     
56     private static boolean matches(String JavaDoc name, String JavaDoc[] patterns) {
57         if (patterns == null) {
58             return true;
59         }
60         for (int i = 0; i < patterns.length; i++) {
61             String JavaDoc pattern = patterns[i];
62             if (pattern.indexOf('*') != -1) {
63                 pattern = pattern.substring(0, pattern.indexOf('*'));
64                 if (name.startsWith(pattern)) {
65                     return true;
66                 }
67             }
68             else {
69                 if (name.equals(pattern)) {
70                     return true;
71                 }
72             }
73         }
74         return false;
75     }
76 }
77
Popular Tags