001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2019 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
075        writer.flush();
076        if (closeStream) {
077            writer.close();
078        }
079    }
080
081    @Override
082    public void fileStarted(AuditEvent event) {
083        // No code by default
084    }
085
086    @Override
087    public void fileFinished(AuditEvent event) {
088        // No code by default
089    }
090
091    @Override
092    public void addError(AuditEvent event) {
093        final String xpathQuery = XpathFileGeneratorAstFilter.findCorrespondingXpathQuery(event);
094        if (xpathQuery != null) {
095            printXmlHeader();
096
097            final File file = new File(event.getFileName());
098
099            writer.println("<suppress-xpath");
100            writer.print("       files=\"");
101            writer.print(file.getName());
102            writer.println(QUOTE_CHAR);
103
104            if (event.getModuleId() == null) {
105                final String checkName =
106                        PackageObjectFactory.getShortFromFullModuleNames(event.getSourceName());
107                writer.print("       checks=\"");
108                writer.print(checkName);
109            }
110            else {
111                writer.print("       id=\"");
112                writer.print(event.getModuleId());
113            }
114            writer.println(QUOTE_CHAR);
115
116            writer.print("       query=\"");
117            writer.print(xpathQuery);
118
119            writer.println("\"/>");
120        }
121    }
122
123    @Override
124    public void addException(AuditEvent event, Throwable throwable) {
125        throw new UnsupportedOperationException("Operation is not supported");
126    }
127
128    /**
129     * Prints XML header if only it was not printed before.
130     */
131    private void printXmlHeader() {
132        if (!isXmlHeaderPrinted) {
133            writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
134            writer.println("<!DOCTYPE suppressions PUBLIC");
135            writer.println("    \"-//Checkstyle//DTD SuppressionXpathFilter Experimental "
136                    + "Configuration 1.2//EN\"");
137            writer.println("    \"https://checkstyle.org/dtds/"
138                    + "suppressions_1_2_xpath_experimental.dtd\">");
139            writer.println("<suppressions>");
140            isXmlHeaderPrinted = true;
141        }
142    }
143
144    @Override
145    protected void finishLocalSetup() {
146        // No code by default
147    }
148}