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;
021
022import java.io.File;
023import java.io.OutputStream;
024import java.io.OutputStreamWriter;
025import java.io.PrintWriter;
026import java.nio.charset.StandardCharsets;
027
028import com.puppycrawl.tools.checkstyle.api.AuditEvent;
029import com.puppycrawl.tools.checkstyle.api.AuditListener;
030import com.puppycrawl.tools.checkstyle.api.AutomaticBean;
031
032/**
033 * Generates <b>suppressions.xml</b> file, based on violations occurred.
034 * See issue #102 https://github.com/checkstyle/checkstyle/issues/102
035 */
036public class XpathFileGeneratorAuditListener extends AutomaticBean implements AuditListener {
037
038    /** The " quote character. */
039    private static final String QUOTE_CHAR = "\"";
040
041    /**
042     * Helper writer that allows easy encoding and printing.
043     */
044    private final PrintWriter writer;
045
046    /** Close output stream in auditFinished. */
047    private final boolean closeStream;
048
049    /** Determines if xml header is printed. */
050    private boolean isXmlHeaderPrinted;
051
052    /**
053     * Creates a new {@code SuppressionFileGenerator} instance.
054     * Sets the output to a defined stream.
055     * @param out the output stream
056     * @param outputStreamOptions if {@code CLOSE} stream should be closed in auditFinished()
057     */
058    public XpathFileGeneratorAuditListener(OutputStream out,
059                                           OutputStreamOptions outputStreamOptions) {
060        writer = new PrintWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8));
061        closeStream = outputStreamOptions == OutputStreamOptions.CLOSE;
062    }
063
064    @Override
065    public void auditStarted(AuditEvent event) {
066        // No code by default
067    }
068
069    @Override
070    public void auditFinished(AuditEvent event) {
071        if (isXmlHeaderPrinted) {
072            writer.println("</suppressions>");
073        }
074        if (closeStream) {
075            writer.close();
076        }
077        else {
078            writer.flush();
079        }
080    }
081
082    @Override
083    public void fileStarted(AuditEvent event) {
084        // No code by default
085    }
086
087    @Override
088    public void fileFinished(AuditEvent event) {
089        // No code by default
090    }
091
092    @Override
093    public void addError(AuditEvent event) {
094        final String xpathQuery = XpathFileGeneratorAstFilter.findCorrespondingXpathQuery(event);
095        if (xpathQuery != null) {
096            printXmlHeader();
097
098            final File file = new File(event.getFileName());
099
100            writer.println("<suppress-xpath");
101            writer.print("       files=\"");
102            writer.print(file.getName());
103            writer.println(QUOTE_CHAR);
104
105            final String checkName =
106                    PackageObjectFactory.getShortFromFullModuleNames(event.getSourceName());
107            writer.print("       checks=\"");
108            writer.print(checkName);
109            writer.println(QUOTE_CHAR);
110
111            writer.print("       query=\"");
112            writer.print(xpathQuery);
113
114            writer.println("\"/>");
115        }
116    }
117
118    @Override
119    public void addException(AuditEvent event, Throwable throwable) {
120        throw new UnsupportedOperationException("Operation is not supported");
121    }
122
123    /**
124     * Prints XML header if only it was not printed before.
125     */
126    private void printXmlHeader() {
127        if (!isXmlHeaderPrinted) {
128            writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
129            writer.println("<!DOCTYPE suppressions PUBLIC");
130            writer.println("    \"-//Checkstyle//DTD SuppressionXpathFilter Experimental "
131                    + "Configuration 1.2//EN\"");
132            writer.println("    \"https://checkstyle.org/dtds/"
133                    + "suppressions_1_2_xpath_experimental.dtd\">");
134            writer.println("<suppressions>");
135            isXmlHeaderPrinted = true;
136        }
137    }
138
139    @Override
140    protected void finishLocalSetup() {
141        // No code by default
142    }
143}