001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2018 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.api;
021
022import java.io.File;
023import java.util.Arrays;
024import java.util.SortedSet;
025import java.util.TreeSet;
026
027import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
028
029/**
030 * Provides common functionality for many FileSetChecks.
031 *
032 * @author lkuehne
033 * @author oliver
034 * @noinspection NoopMethodInAbstractClass
035 */
036public abstract class AbstractFileSetCheck
037    extends AbstractViolationReporter
038    implements FileSetCheck {
039
040    /**
041     * Collects the error messages.
042     */
043    private static final ThreadLocal<SortedSet<LocalizedMessage>> MESSAGE_COLLECTOR =
044            ThreadLocal.withInitial(TreeSet::new);
045
046    /** The dispatcher errors are fired to. */
047    private MessageDispatcher messageDispatcher;
048
049    /** The file extensions that are accepted by this filter. */
050    private String[] fileExtensions = CommonUtils.EMPTY_STRING_ARRAY;
051
052    /**
053     * Called to process a file that matches the specified file extensions.
054     * @param file the file to be processed
055     * @param fileText the contents of the file.
056     * @throws CheckstyleException if error condition within Checkstyle occurs.
057     */
058    protected abstract void processFiltered(File file, FileText fileText)
059            throws CheckstyleException;
060
061    @Override
062    public void init() {
063        // No code by default, should be overridden only by demand at subclasses
064    }
065
066    @Override
067    public void destroy() {
068        // No code by default, should be overridden only by demand at subclasses
069    }
070
071    @Override
072    public void beginProcessing(String charset) {
073        // No code by default, should be overridden only by demand at subclasses
074    }
075
076    @Override
077    public final SortedSet<LocalizedMessage> process(File file, FileText fileText)
078            throws CheckstyleException {
079        final SortedSet<LocalizedMessage> messages = MESSAGE_COLLECTOR.get();
080        messages.clear();
081        // Process only what interested in
082        if (CommonUtils.matchesFileExtension(file, fileExtensions)) {
083            processFiltered(file, fileText);
084        }
085        final SortedSet<LocalizedMessage> result = new TreeSet<>(messages);
086        messages.clear();
087        return result;
088    }
089
090    @Override
091    public void finishProcessing() {
092        // No code by default, should be overridden only by demand at subclasses
093    }
094
095    @Override
096    public final void setMessageDispatcher(MessageDispatcher messageDispatcher) {
097        this.messageDispatcher = messageDispatcher;
098    }
099
100    /**
101     * A message dispatcher is used to fire violation messages to
102     * interested audit listeners.
103     *
104     * @return the current MessageDispatcher.
105     */
106    protected final MessageDispatcher getMessageDispatcher() {
107        return messageDispatcher;
108    }
109
110    /**
111     * Makes copy of file extensions and returns them.
112     * @return file extensions that identify the files that pass the
113     *     filter of this FileSetCheck.
114     */
115    public String[] getFileExtensions() {
116        return Arrays.copyOf(fileExtensions, fileExtensions.length);
117    }
118
119    /**
120     * Sets the file extensions that identify the files that pass the
121     * filter of this FileSetCheck.
122     * @param extensions the set of file extensions. A missing
123     *         initial '.' character of an extension is automatically added.
124     * @throws IllegalArgumentException is argument is null
125     */
126    public final void setFileExtensions(String... extensions) {
127        if (extensions == null) {
128            throw new IllegalArgumentException("Extensions array can not be null");
129        }
130
131        fileExtensions = new String[extensions.length];
132        for (int i = 0; i < extensions.length; i++) {
133            final String extension = extensions[i];
134            if (CommonUtils.startsWithChar(extension, '.')) {
135                fileExtensions[i] = extension;
136            }
137            else {
138                fileExtensions[i] = "." + extension;
139            }
140        }
141    }
142
143    /**
144     * Adds the sorted set of {@link LocalizedMessage} to the message collector.
145     * @param messages the sorted set of {@link LocalizedMessage}.
146     */
147    protected static void addMessages(SortedSet<LocalizedMessage> messages) {
148        MESSAGE_COLLECTOR.get().addAll(messages);
149    }
150
151    @Override
152    public final void log(int line, String key, Object... args) {
153        log(line, 0, key, args);
154    }
155
156    @Override
157    public final void log(int lineNo, int colNo, String key,
158            Object... args) {
159        MESSAGE_COLLECTOR.get().add(
160                new LocalizedMessage(lineNo,
161                        colNo,
162                        getMessageBundle(),
163                        key,
164                        args,
165                        getSeverityLevel(),
166                        getId(),
167                        getClass(),
168                        getCustomMessages().get(key)));
169    }
170
171    /**
172     * Notify all listeners about the errors in a file.
173     * Calls {@code MessageDispatcher.fireErrors()} with
174     * all logged errors and than clears errors' list.
175     * @param fileName the audited file
176     */
177    protected final void fireErrors(String fileName) {
178        final SortedSet<LocalizedMessage> errors = new TreeSet<>(MESSAGE_COLLECTOR.get());
179        MESSAGE_COLLECTOR.get().clear();
180        messageDispatcher.fireErrors(fileName, errors);
181    }
182
183}