001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2015 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;
021
022import org.apache.commons.lang3.ArrayUtils;
023
024import com.puppycrawl.tools.checkstyle.api.Check;
025import com.puppycrawl.tools.checkstyle.api.DetailAST;
026import com.puppycrawl.tools.checkstyle.api.FileContents;
027
028/**
029 * Holds the current file contents for global access when configured
030 * as a TreeWalker sub-module. For example,
031 * a filter can access the current file contents through this module.
032 * @author Mike McMahon
033 * @author Rick Giles
034 */
035public class FileContentsHolder
036    extends Check {
037    /** The current file contents. */
038    private static final ThreadLocal<FileContents> FILE_CONTENTS = new ThreadLocal<>();
039
040    /**
041     * @return the current file contents.
042     */
043    public static FileContents getContents() {
044        return FILE_CONTENTS.get();
045    }
046
047    @Override
048    public int[] getDefaultTokens() {
049        return getAcceptableTokens();
050    }
051
052    @Override
053    public int[] getAcceptableTokens() {
054        return ArrayUtils.EMPTY_INT_ARRAY;
055    }
056
057    @Override
058    public int[] getRequiredTokens() {
059        return getAcceptableTokens();
060    }
061
062    @Override
063    public void beginTree(DetailAST rootAST) {
064        FILE_CONTENTS.set(getFileContents());
065    }
066
067    @Override
068    public void destroy() {
069        // This needs to be called in destroy, rather than finishTree()
070        // as finishTree() is called before the messages are passed to the
071        // filters. Without calling remove, there is a memory leak.
072        FILE_CONTENTS.remove();
073    }
074}