KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > puppycrawl > tools > checkstyle > api > Utils


1 ////////////////////////////////////////////////////////////////////////////////
2
// checkstyle: Checks Java source code for adherence to a set of rules.
3
// Copyright (C) 2001-2005 Oliver Burn
4
//
5
// This library is free software; you can redistribute it and/or
6
// modify it under the terms of the GNU Lesser General Public
7
// License as published by the Free Software Foundation; either
8
// version 2.1 of the License, or (at your option) any later version.
9
//
10
// This library is distributed in the hope that it will be useful,
11
// but WITHOUT ANY WARRANTY; without even the implied warranty of
12
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13
// Lesser General Public License for more details.
14
//
15
// You should have received a copy of the GNU Lesser General Public
16
// License along with this library; if not, write to the Free Software
17
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
////////////////////////////////////////////////////////////////////////////////
19

20 package com.puppycrawl.tools.checkstyle.api;
21
22 import java.io.FileInputStream JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.io.InputStreamReader JavaDoc;
25 import java.io.LineNumberReader JavaDoc;
26 import java.io.File JavaDoc;
27 import java.io.UnsupportedEncodingException JavaDoc;
28 import java.util.ArrayList JavaDoc;
29 import java.util.HashMap JavaDoc;
30 import java.util.Map JavaDoc;
31 import java.util.regex.Pattern JavaDoc;
32 import java.util.regex.PatternSyntaxException JavaDoc;
33
34 import org.apache.commons.beanutils.ConversionException;
35
36 import org.apache.commons.logging.Log;
37 import org.apache.commons.logging.LogFactory;
38
39 /**
40  * Contains utility methods.
41  *
42  * @author Oliver Burn
43  * @version 1.0
44  */

45 public final class Utils
46 {
47     /** Map of all created regular expressions **/
48     private static final Map JavaDoc CREATED_RES = new HashMap JavaDoc();
49     /** Shared instance of logger for exception logging. */
50     private static final Log EXCEPTION_LOG =
51         LogFactory.getLog("com.puppycrawl.tools.checkstyle.ExceptionLog");
52
53     ///CLOVER:OFF
54
/** stop instances being created **/
55     private Utils()
56     {
57     }
58     ///CLOVER:ON
59

60     /**
61      * Accessor for shared instance of logger which should be
62      * used to log all exceptions occured during <code>FileSetCheck</code>
63      * work (<code>debug()</code> should be used).
64      * @return shared exception logger.
65      */

66     public static Log getExceptionLogger()
67     {
68         return EXCEPTION_LOG;
69     }
70
71     /**
72      * Returns whether the specified string contains only whitespace up to the
73      * specified index.
74      *
75      * @param aIndex index to check up to
76      * @param aLine the line to check
77      * @return whether there is only whitespace
78      */

79     public static boolean whitespaceBefore(int aIndex, String JavaDoc aLine)
80     {
81         for (int i = 0; i < aIndex; i++) {
82             if (!Character.isWhitespace(aLine.charAt(i))) {
83                 return false;
84             }
85         }
86         return true;
87     }
88
89     /**
90      * Returns the length of a string ignoring all trailing whitespace. It is a
91      * pity that there is not a trim() like method that only removed the
92      * trailing whitespace.
93      * @param aLine the string to process
94      * @return the length of the string ignoring all trailing whitespace
95      **/

96     public static int lengthMinusTrailingWhitespace(String JavaDoc aLine)
97     {
98         int len = aLine.length();
99         for (int i = len - 1; i >= 0; i--) {
100             if (!Character.isWhitespace(aLine.charAt(i))) {
101                 break;
102             }
103             len--;
104         }
105         return len;
106     }
107
108     /**
109      * Returns the length of a String prefix with tabs expanded.
110      * Each tab is counted as the number of characters is takes to
111      * jump to the next tab stop.
112      * @param aString the input String
113      * @param aToIdx index in aString (exclusive) where the calculation stops
114      * @param aTabWidth the distance betweeen tab stop position.
115      * @return the length of aString.substring(0, aToIdx) with tabs expanded.
116      */

117     public static int lengthExpandedTabs(String JavaDoc aString,
118                                          int aToIdx,
119                                          int aTabWidth)
120     {
121         int len = 0;
122         final char[] chars = aString.toCharArray();
123         for (int idx = 0; idx < aToIdx; idx++) {
124             if (chars[idx] == '\t') {
125                 len = (len / aTabWidth + 1) * aTabWidth;
126             }
127             else {
128                 len++;
129             }
130         }
131         return len;
132     }
133
134     /**
135      * This is a factory method to return an Pattern object for the specified
136      * regular expression. It calls {@link #getPattern(String, int)} with the
137      * compile flags defaults to 0.
138      * @return an Pattern object for the supplied pattern
139      * @param aPattern the regular expression pattern
140      * @throws PatternSyntaxException an invalid pattern was supplied
141      **/

142     public static Pattern JavaDoc getPattern(String JavaDoc aPattern)
143         throws PatternSyntaxException JavaDoc
144     {
145         return getPattern(aPattern, 0);
146     }
147
148     /**
149      * This is a factory method to return an Pattern object for the specified
150      * regular expression and compile flags.
151      * <p>
152      * This method is not MT safe, but neither are the returned Pattern objects.
153      * @return an Pattern object for the supplied pattern
154      * @param aPattern the regular expression pattern
155      * @param aCompileFlags the compilation flags
156      * @throws PatternSyntaxException an invalid pattern was supplied
157      **/

158     public static Pattern JavaDoc getPattern(String JavaDoc aPattern, int aCompileFlags)
159         throws PatternSyntaxException JavaDoc
160     {
161         final String JavaDoc key = aPattern + ":flags-" + aCompileFlags;
162         Pattern JavaDoc retVal = (Pattern JavaDoc) CREATED_RES.get(key);
163         if (retVal == null) {
164             retVal = Pattern.compile(aPattern, aCompileFlags);
165             CREATED_RES.put(key, retVal);
166         }
167         return retVal;
168     }
169     /**
170      * Loads the contents of a file in a String array.
171      * @return the lines in the file
172      * @param aFileName the name of the file to load
173      * @throws IOException error occurred
174      **/

175     public static String JavaDoc[] getLines(String JavaDoc aFileName)
176         throws IOException JavaDoc
177     {
178         return getLines(
179             aFileName,
180             System.getProperty("file.encoding", "UTF-8"));
181     }
182
183     /**
184      * Loads the contents of a file in a String array using
185      * the named charset.
186      * @return the lines in the file
187      * @param aFileName the name of the file to load
188      * @param aCharsetName the name of a supported charset
189      * @throws IOException error occurred
190      **/

191     public static String JavaDoc[] getLines(String JavaDoc aFileName, String JavaDoc aCharsetName)
192         throws IOException JavaDoc
193     {
194         final ArrayList JavaDoc lines = new ArrayList JavaDoc();
195         final FileInputStream JavaDoc fr = new FileInputStream JavaDoc(aFileName);
196         LineNumberReader JavaDoc lnr = null;
197         try {
198             lnr = new LineNumberReader JavaDoc(new InputStreamReader JavaDoc(fr, aCharsetName));
199         }
200         catch (final UnsupportedEncodingException JavaDoc ex) {
201             final String JavaDoc message = "unsupported charset: " + ex.getMessage();
202             throw new UnsupportedEncodingException JavaDoc(message);
203         }
204         try {
205             while (true) {
206                 final String JavaDoc l = lnr.readLine();
207                 if (l == null) {
208                     break;
209                 }
210                 lines.add(l);
211             }
212         }
213         finally {
214             try {
215                 lnr.close();
216             }
217             catch (final IOException JavaDoc e) {
218                 ; // silently ignore
219
}
220         }
221
222         return (String JavaDoc[]) lines.toArray(new String JavaDoc[0]);
223     }
224
225     /**
226      * Helper method to create a regular expression.
227      * @param aPattern the pattern to match
228      * @return a created regexp object
229      * @throws ConversionException if unable to create Pattern object.
230      **/

231     public static Pattern JavaDoc createPattern(String JavaDoc aPattern)
232         throws ConversionException
233     {
234         Pattern JavaDoc retVal = null;
235         try {
236             retVal = getPattern(aPattern);
237         }
238         catch (final PatternSyntaxException JavaDoc e) {
239             throw new ConversionException(
240                 "Failed to initialise regexp expression " + aPattern, e);
241         }
242         return retVal;
243     }
244
245     /**
246      * @return the base class name from a fully qualified name
247      * @param aType the fully qualified name. Cannot be null
248      */

249     public static String JavaDoc baseClassname(String JavaDoc aType)
250     {
251         final int i = aType.lastIndexOf(".");
252         return (i == -1) ? aType : aType.substring(i + 1);
253     }
254
255     /**
256      * Create a stripped down version of a filename.
257      * @param aBasedir the prefix to strip off the original filename
258      * @param aFileName the original filename
259      * @return the filename where an initial prefix of basedir is stripped
260      */

261     public static String JavaDoc getStrippedFileName(
262             final String JavaDoc aBasedir, final String JavaDoc aFileName)
263     {
264         final String JavaDoc stripped;
265         if ((aBasedir == null) || !aFileName.startsWith(aBasedir)) {
266             stripped = aFileName;
267         }
268         else {
269             // making the assumption that there is text after basedir
270
final int skipSep = aBasedir.endsWith(File.separator) ? 0 : 1;
271             stripped = aFileName.substring(aBasedir.length() + skipSep);
272         }
273         return stripped;
274     }
275
276 }
277
Popular Tags