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