001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2017 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.checks.javadoc;
021
022import java.util.Arrays;
023import java.util.HashSet;
024import java.util.Set;
025import java.util.regex.Pattern;
026
027import com.google.common.base.CharMatcher;
028import com.puppycrawl.tools.checkstyle.api.DetailNode;
029import com.puppycrawl.tools.checkstyle.api.JavadocTokenTypes;
030import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
031
032/**
033 * <p>
034 * Checks that <a href=
035 * "http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html#firstsentence">
036 * Javadoc summary sentence</a> does not contain phrases that are not recommended to use.
037 * By default Check validate that first sentence is not empty:</p><br>
038 * <pre>
039 * &lt;module name=&quot;SummaryJavadocCheck&quot;/&gt;
040 * </pre>
041 *
042 * <p>To ensure that summary do not contain phrase like "This method returns",
043 *  use following config:
044 *
045 * <pre>
046 * &lt;module name=&quot;SummaryJavadocCheck&quot;&gt;
047 *     &lt;property name=&quot;forbiddenSummaryFragments&quot;
048 *     value=&quot;^This method returns.*&quot;/&gt;
049 * &lt;/module&gt;
050 * </pre>
051 * <p>
052 * To specify period symbol at the end of first javadoc sentence - use following config:
053 * </p>
054 * <pre>
055 * &lt;module name=&quot;SummaryJavadocCheck&quot;&gt;
056 *     &lt;property name=&quot;period&quot;
057 *     value=&quot;period&quot;/&gt;
058 * &lt;/module&gt;
059 * </pre>
060 *
061 *
062 * @author max
063 * @author <a href="mailto:nesterenko-aleksey@list.ru">Aleksey Nesterenko</a>
064 */
065public class SummaryJavadocCheck extends AbstractJavadocCheck {
066
067    /**
068     * A key is pointing to the warning message text in "messages.properties"
069     * file.
070     */
071    public static final String MSG_SUMMARY_FIRST_SENTENCE = "summary.first.sentence";
072
073    /**
074     * A key is pointing to the warning message text in "messages.properties"
075     * file.
076     */
077    public static final String MSG_SUMMARY_JAVADOC = "summary.javaDoc";
078    /**
079     * This regexp is used to convert multiline javadoc to single line without stars.
080     */
081    private static final Pattern JAVADOC_MULTILINE_TO_SINGLELINE_PATTERN =
082            Pattern.compile("\n[ ]+(\\*)|^[ ]+(\\*)");
083
084    /** Period literal. */
085    private static final String PERIOD = ".";
086
087    /**
088     * Stores allowed values in document for inherit doc literal.
089     */
090    private static final Set<Integer> SKIP_TOKENS = new HashSet<>(
091        Arrays.asList(JavadocTokenTypes.NEWLINE,
092                       JavadocTokenTypes.LEADING_ASTERISK,
093                       JavadocTokenTypes.EOF)
094    );
095    /**
096     * Regular expression for forbidden summary fragments.
097     */
098    private Pattern forbiddenSummaryFragments = CommonUtils.createPattern("^$");
099
100    /**
101     * Period symbol at the end of first javadoc sentence.
102     */
103    private String period = PERIOD;
104
105    /**
106     * Sets custom value of regular expression for forbidden summary fragments.
107     * @param pattern a pattern.
108     */
109    public void setForbiddenSummaryFragments(Pattern pattern) {
110        forbiddenSummaryFragments = pattern;
111    }
112
113    /**
114     * Sets value of period symbol at the end of first javadoc sentence.
115     * @param period period's value.
116     */
117    public void setPeriod(String period) {
118        this.period = period;
119    }
120
121    @Override
122    public int[] getDefaultJavadocTokens() {
123        return new int[] {
124            JavadocTokenTypes.JAVADOC,
125        };
126    }
127
128    @Override
129    public int[] getRequiredJavadocTokens() {
130        return getAcceptableJavadocTokens();
131    }
132
133    @Override
134    public void visitJavadocToken(DetailNode ast) {
135        String firstSentence = getFirstSentence(ast);
136        final int endOfSentence = firstSentence.lastIndexOf(period);
137        if (endOfSentence == -1) {
138            if (!isOnlyInheritDoc(ast)) {
139                log(ast.getLineNumber(), MSG_SUMMARY_FIRST_SENTENCE);
140            }
141        }
142        else {
143            firstSentence = firstSentence.substring(0, endOfSentence);
144            if (containsForbiddenFragment(firstSentence)) {
145                log(ast.getLineNumber(), MSG_SUMMARY_JAVADOC);
146            }
147        }
148    }
149
150    /**
151     * Finds if inheritDoc is placed properly in java doc.
152     * @param ast Javadoc root node.
153     * @return true if inheritDoc is valid or false.
154     */
155    private static boolean isOnlyInheritDoc(DetailNode ast) {
156        boolean extraTextFound = false;
157        boolean containsInheritDoc = false;
158        for (DetailNode child : ast.getChildren()) {
159            if (child.getType() == JavadocTokenTypes.TEXT) {
160                if (!CommonUtils.isBlank(child.getText())) {
161                    extraTextFound = true;
162                }
163            }
164            else if (child.getType() == JavadocTokenTypes.JAVADOC_INLINE_TAG) {
165                if (child.getChildren()[1].getType() == JavadocTokenTypes.INHERIT_DOC_LITERAL) {
166                    containsInheritDoc = true;
167                }
168                else {
169                    extraTextFound = true;
170                }
171            }
172            else if (!SKIP_TOKENS.contains(child.getType())) {
173                extraTextFound = true;
174            }
175            if (extraTextFound) {
176                break;
177            }
178        }
179        return containsInheritDoc && !extraTextFound;
180    }
181
182    /**
183     * Finds and returns first sentence.
184     * @param ast Javadoc root node.
185     * @return first sentence.
186     */
187    private static String getFirstSentence(DetailNode ast) {
188        final StringBuilder result = new StringBuilder();
189        final String periodSuffix = PERIOD + ' ';
190        for (DetailNode child : ast.getChildren()) {
191            final String text;
192            if (child.getChildren().length == 0) {
193                text = child.getText();
194            }
195            else {
196                text = getFirstSentence(child);
197            }
198
199            if (child.getType() != JavadocTokenTypes.JAVADOC_INLINE_TAG
200                && text.contains(periodSuffix)) {
201                result.append(text.substring(0, text.indexOf(periodSuffix) + 1));
202                break;
203            }
204            else {
205                result.append(text);
206            }
207        }
208        return result.toString();
209    }
210
211    /**
212     * Tests if first sentence contains forbidden summary fragment.
213     * @param firstSentence String with first sentence.
214     * @return true, if first sentence contains forbidden summary fragment.
215     */
216    private boolean containsForbiddenFragment(String firstSentence) {
217        String javadocText = JAVADOC_MULTILINE_TO_SINGLELINE_PATTERN
218                .matcher(firstSentence).replaceAll(" ");
219        javadocText = CharMatcher.WHITESPACE.trimAndCollapseFrom(javadocText, ' ');
220        return forbiddenSummaryFragments.matcher(javadocText).find();
221    }
222}