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