001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2017 the original author or authors.
004//
005// This library is free software; you can redistribute it and/or
006// modify it under the terms of the GNU Lesser General Public
007// License as published by the Free Software Foundation; either
008// version 2.1 of the License, or (at your option) any later version.
009//
010// This library is distributed in the hope that it will be useful,
011// but WITHOUT ANY WARRANTY; without even the implied warranty of
012// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013// Lesser General Public License for more details.
014//
015// You should have received a copy of the GNU Lesser General Public
016// License along with this library; if not, write to the Free Software
017// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
018////////////////////////////////////////////////////////////////////////////////
019
020package com.puppycrawl.tools.checkstyle.utils;
021
022import java.io.Closeable;
023import java.io.File;
024import java.io.IOException;
025import java.lang.reflect.Constructor;
026import java.lang.reflect.InvocationTargetException;
027import java.net.MalformedURLException;
028import java.net.URI;
029import java.net.URISyntaxException;
030import java.net.URL;
031import java.nio.file.Path;
032import java.nio.file.Paths;
033import java.util.regex.Matcher;
034import java.util.regex.Pattern;
035import java.util.regex.PatternSyntaxException;
036
037import org.apache.commons.beanutils.ConversionException;
038
039import com.google.common.base.CharMatcher;
040import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
041
042/**
043 * Contains utility methods.
044 *
045 * @author <a href="mailto:nesterenko-aleksey@list.ru">Aleksey Nesterenko</a>
046 */
047public final class CommonUtils {
048
049    /** Copied from org.apache.commons.lang3.ArrayUtils. */
050    public static final String[] EMPTY_STRING_ARRAY = new String[0];
051    /** Copied from org.apache.commons.lang3.ArrayUtils. */
052    public static final Integer[] EMPTY_INTEGER_OBJECT_ARRAY = new Integer[0];
053    /** Copied from org.apache.commons.lang3.ArrayUtils. */
054    public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];
055    /** Copied from org.apache.commons.lang3.ArrayUtils. */
056    public static final int[] EMPTY_INT_ARRAY = new int[0];
057    /** Copied from org.apache.commons.lang3.ArrayUtils. */
058    public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
059    /** Copied from org.apache.commons.lang3.ArrayUtils. */
060    public static final double[] EMPTY_DOUBLE_ARRAY = new double[0];
061
062    /** Prefix for the exception when unable to find resource. */
063    private static final String UNABLE_TO_FIND_EXCEPTION_PREFIX = "Unable to find: ";
064
065    /** Stop instances being created. **/
066    private CommonUtils() {
067
068    }
069
070    /**
071     * Helper method to create a regular expression.
072     *
073     * @param pattern
074     *            the pattern to match
075     * @return a created regexp object
076     * @throws ConversionException
077     *             if unable to create Pattern object.
078     **/
079    public static Pattern createPattern(String pattern) {
080        return createPattern(pattern, 0);
081    }
082
083    /**
084     * Helper method to create a regular expression with a specific flags.
085     *
086     * @param pattern
087     *            the pattern to match
088     * @param flags
089     *            the flags to set
090     * @return a created regexp object
091     * @throws IllegalArgumentException
092     *             if unable to create Pattern object.
093     **/
094    public static Pattern createPattern(String pattern, int flags) {
095        try {
096            return Pattern.compile(pattern, flags);
097        }
098        catch (final PatternSyntaxException ex) {
099            throw new IllegalArgumentException(
100                "Failed to initialise regular expression " + pattern, ex);
101        }
102    }
103
104    /**
105     * Returns whether the file extension matches what we are meant to process.
106     *
107     * @param file
108     *            the file to be checked.
109     * @param fileExtensions
110     *            files extensions, empty property in config makes it matches to all.
111     * @return whether there is a match.
112     */
113    public static boolean matchesFileExtension(File file, String... fileExtensions) {
114        boolean result = false;
115        if (fileExtensions == null || fileExtensions.length == 0) {
116            result = true;
117        }
118        else {
119            // normalize extensions so all of them have a leading dot
120            final String[] withDotExtensions = new String[fileExtensions.length];
121            for (int i = 0; i < fileExtensions.length; i++) {
122                final String extension = fileExtensions[i];
123                if (startsWithChar(extension, '.')) {
124                    withDotExtensions[i] = extension;
125                }
126                else {
127                    withDotExtensions[i] = "." + extension;
128                }
129            }
130
131            final String fileName = file.getName();
132            for (final String fileExtension : withDotExtensions) {
133                if (fileName.endsWith(fileExtension)) {
134                    result = true;
135                    break;
136                }
137            }
138        }
139
140        return result;
141    }
142
143    /**
144     * Returns whether the specified string contains only whitespace up to the specified index.
145     *
146     * @param index
147     *            index to check up to
148     * @param line
149     *            the line to check
150     * @return whether there is only whitespace
151     */
152    public static boolean hasWhitespaceBefore(int index, String line) {
153        boolean result = true;
154        for (int i = 0; i < index; i++) {
155            if (!Character.isWhitespace(line.charAt(i))) {
156                result = false;
157                break;
158            }
159        }
160        return result;
161    }
162
163    /**
164     * Returns the length of a string ignoring all trailing whitespace.
165     * It is a pity that there is not a trim() like
166     * method that only removed the trailing whitespace.
167     *
168     * @param line
169     *            the string to process
170     * @return the length of the string ignoring all trailing whitespace
171     **/
172    public static int lengthMinusTrailingWhitespace(String line) {
173        int len = line.length();
174        for (int i = len - 1; i >= 0; i--) {
175            if (!Character.isWhitespace(line.charAt(i))) {
176                break;
177            }
178            len--;
179        }
180        return len;
181    }
182
183    /**
184     * Returns the length of a String prefix with tabs expanded.
185     * Each tab is counted as the number of characters is
186     * takes to jump to the next tab stop.
187     *
188     * @param inputString
189     *            the input String
190     * @param toIdx
191     *            index in string (exclusive) where the calculation stops
192     * @param tabWidth
193     *            the distance between tab stop position.
194     * @return the length of string.substring(0, toIdx) with tabs expanded.
195     */
196    public static int lengthExpandedTabs(String inputString,
197            int toIdx,
198            int tabWidth) {
199        int len = 0;
200        for (int idx = 0; idx < toIdx; idx++) {
201            if (inputString.charAt(idx) == '\t') {
202                len = (len / tabWidth + 1) * tabWidth;
203            }
204            else {
205                len++;
206            }
207        }
208        return len;
209    }
210
211    /**
212     * Validates whether passed string is a valid pattern or not.
213     *
214     * @param pattern
215     *            string to validate
216     * @return true if the pattern is valid false otherwise
217     */
218    public static boolean isPatternValid(String pattern) {
219        boolean isValid = true;
220        try {
221            Pattern.compile(pattern);
222        }
223        catch (final PatternSyntaxException ignored) {
224            isValid = false;
225        }
226        return isValid;
227    }
228
229    /**
230     * @param type
231     *            the fully qualified name. Cannot be null
232     * @return the base class name from a fully qualified name
233     */
234    public static String baseClassName(String type) {
235        final String className;
236        final int index = type.lastIndexOf('.');
237        if (index == -1) {
238            className = type;
239        }
240        else {
241            className = type.substring(index + 1);
242        }
243        return className;
244    }
245
246    /**
247     * Constructs a normalized relative path between base directory and a given path.
248     *
249     * @param baseDirectory
250     *            the base path to which given path is relativized
251     * @param path
252     *            the path to relativize against base directory
253     * @return the relative normalized path between base directory and
254     *     path or path if base directory is null.
255     */
256    public static String relativizeAndNormalizePath(final String baseDirectory, final String path) {
257        final String resultPath;
258        if (baseDirectory == null) {
259            resultPath = path;
260        }
261        else {
262            final Path pathAbsolute = Paths.get(path).normalize();
263            final Path pathBase = Paths.get(baseDirectory).normalize();
264            resultPath = pathBase.relativize(pathAbsolute).toString();
265        }
266        return resultPath;
267    }
268
269    /**
270     * Tests if this string starts with the specified prefix.
271     * <p>
272     * It is faster version of {@link String#startsWith(String)} optimized for
273     *  one-character prefixes at the expense of
274     * some readability. Suggested by SimplifyStartsWith PMD rule:
275     * http://pmd.sourceforge.net/pmd-5.3.1/pmd-java/rules/java/optimizations.html#SimplifyStartsWith
276     * </p>
277     *
278     * @param value
279     *            the {@code String} to check
280     * @param prefix
281     *            the prefix to find
282     * @return {@code true} if the {@code char} is a prefix of the given {@code String};
283     *  {@code false} otherwise.
284     */
285    public static boolean startsWithChar(String value, char prefix) {
286        return !value.isEmpty() && value.charAt(0) == prefix;
287    }
288
289    /**
290     * Tests if this string ends with the specified suffix.
291     * <p>
292     * It is faster version of {@link String#endsWith(String)} optimized for
293     *  one-character suffixes at the expense of
294     * some readability. Suggested by SimplifyStartsWith PMD rule:
295     * http://pmd.sourceforge.net/pmd-5.3.1/pmd-java/rules/java/optimizations.html#SimplifyStartsWith
296     * </p>
297     *
298     * @param value
299     *            the {@code String} to check
300     * @param suffix
301     *            the suffix to find
302     * @return {@code true} if the {@code char} is a suffix of the given {@code String};
303     *  {@code false} otherwise.
304     */
305    public static boolean endsWithChar(String value, char suffix) {
306        return !value.isEmpty() && value.charAt(value.length() - 1) == suffix;
307    }
308
309    /**
310     * Gets constructor of targetClass.
311     * @param targetClass
312     *            from which constructor is returned
313     * @param parameterTypes
314     *            of constructor
315     * @param <T> type of the target class object.
316     * @return constructor of targetClass or {@link IllegalStateException} if any exception occurs
317     * @see Class#getConstructor(Class[])
318     */
319    public static <T> Constructor<T> getConstructor(Class<T> targetClass,
320                                                    Class<?>... parameterTypes) {
321        try {
322            return targetClass.getConstructor(parameterTypes);
323        }
324        catch (NoSuchMethodException ex) {
325            throw new IllegalStateException(ex);
326        }
327    }
328
329    /**
330     * @param constructor
331     *            to invoke
332     * @param parameters
333     *            to pass to constructor
334     * @param <T>
335     *            type of constructor
336     * @return new instance of class or {@link IllegalStateException} if any exception occurs
337     * @see Constructor#newInstance(Object...)
338     */
339    public static <T> T invokeConstructor(Constructor<T> constructor, Object... parameters) {
340        try {
341            return constructor.newInstance(parameters);
342        }
343        catch (InstantiationException | IllegalAccessException | InvocationTargetException ex) {
344            throw new IllegalStateException(ex);
345        }
346    }
347
348    /**
349     * Closes a stream re-throwing IOException as IllegalStateException.
350     *
351     * @param closeable
352     *            Closeable object
353     */
354    public static void close(Closeable closeable) {
355        if (closeable != null) {
356            try {
357                closeable.close();
358            }
359            catch (IOException ex) {
360                throw new IllegalStateException("Cannot close the stream", ex);
361            }
362        }
363    }
364
365    /**
366     * Resolve the specified filename to a URI.
367     * @param filename name os the file
368     * @return resolved header file URI
369     * @throws CheckstyleException on failure
370     */
371    public static URI getUriByFilename(String filename) throws CheckstyleException {
372        // figure out if this is a File or a URL
373        URI uri;
374        try {
375            final URL url = new URL(filename);
376            uri = url.toURI();
377        }
378        catch (final URISyntaxException | MalformedURLException ignored) {
379            uri = null;
380        }
381
382        if (uri == null) {
383            final File file = new File(filename);
384            if (file.exists()) {
385                uri = file.toURI();
386            }
387            else {
388                // check to see if the file is in the classpath
389                try {
390                    final URL configUrl = CommonUtils.class
391                            .getResource(filename);
392                    if (configUrl == null) {
393                        throw new CheckstyleException(UNABLE_TO_FIND_EXCEPTION_PREFIX + filename);
394                    }
395                    uri = configUrl.toURI();
396                }
397                catch (final URISyntaxException ex) {
398                    throw new CheckstyleException(UNABLE_TO_FIND_EXCEPTION_PREFIX + filename, ex);
399                }
400            }
401        }
402
403        return uri;
404    }
405
406    /**
407     * Puts part of line, which matches regexp into given template
408     * on positions $n where 'n' is number of matched part in line.
409     * @param template the string to expand.
410     * @param lineToPlaceInTemplate contains expression which should be placed into string.
411     * @param regexp expression to find in comment.
412     * @return the string, based on template filled with given lines
413     */
414    public static String fillTemplateWithStringsByRegexp(
415        String template, String lineToPlaceInTemplate, Pattern regexp) {
416        final Matcher matcher = regexp.matcher(lineToPlaceInTemplate);
417        String result = template;
418        if (matcher.find()) {
419            for (int i = 0; i <= matcher.groupCount(); i++) {
420                // $n expands comment match like in Pattern.subst().
421                result = result.replaceAll("\\$" + i, matcher.group(i));
422            }
423        }
424        return result;
425    }
426
427    /**
428     * Check if a string is blank.
429     * A string is considered blank if it is null, empty or contains only  whitespace characters,
430     * as determined by {@link CharMatcher#WHITESPACE}.
431     * @param str the string to check
432     * @return true if str is either null, empty or whitespace-only.
433     */
434    public static boolean isBlank(String str) {
435        return str == null || CharMatcher.WHITESPACE.matchesAllOf(str);
436    }
437
438    /**
439     * Returns file name without extension.
440     * We do not use the method from Guava library to reduce Checkstyle's dependencies
441     * on external libraries.
442     * @param fullFilename file name with extension.
443     * @return file name without extension.
444     */
445    public static String getFileNameWithoutExtension(String fullFilename) {
446        final String fileName = new File(fullFilename).getName();
447        final int dotIndex = fileName.lastIndexOf('.');
448        final String fileNameWithoutExtension;
449        if (dotIndex == -1) {
450            fileNameWithoutExtension = fileName;
451        }
452        else {
453            fileNameWithoutExtension = fileName.substring(0, dotIndex);
454        }
455        return fileNameWithoutExtension;
456    }
457
458    /**
459     * Returns file extension for the given file name
460     * or empty string if file does not have an extension.
461     * We do not use the method from Guava library to reduce Checkstyle's dependencies
462     * on external libraries.
463     * @param fileNameWithExtension file name with extension.
464     * @return file extension for the given file name
465     *         or empty string if file does not have an extension.
466     */
467    public static String getFileExtension(String fileNameWithExtension) {
468        final String fileName = Paths.get(fileNameWithExtension).toString();
469        final int dotIndex = fileName.lastIndexOf('.');
470        final String extension;
471        if (dotIndex == -1) {
472            extension = "";
473        }
474        else {
475            extension = fileName.substring(dotIndex + 1);
476        }
477        return extension;
478    }
479
480    /**
481     * Checks whether the given string is a valid identifier.
482     * @param str A string to check.
483     * @return true when the given string contains valid identifier.
484     */
485    public static boolean isIdentifier(String str) {
486        boolean isIdentifier = !str.isEmpty();
487
488        for (int i = 0; isIdentifier && i < str.length(); i++) {
489            if (i == 0) {
490                isIdentifier = Character.isJavaIdentifierStart(str.charAt(0));
491            }
492            else {
493                isIdentifier = Character.isJavaIdentifierPart(str.charAt(i));
494            }
495        }
496
497        return isIdentifier;
498    }
499
500    /**
501     * Checks whether the given string is a valid name.
502     * @param str A string to check.
503     * @return true when the given string contains valid name.
504     */
505    public static boolean isName(String str) {
506        boolean isName = !str.isEmpty();
507
508        final String[] identifiers = str.split("\\.", -1);
509        for (int i = 0; isName && i < identifiers.length; i++) {
510            isName = isIdentifier(identifiers[i]);
511        }
512
513        return isName;
514    }
515}