001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2020 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.ByteArrayOutputStream;
023import java.io.File;
024import java.io.IOException;
025import java.io.InputStream;
026import java.io.ObjectOutputStream;
027import java.io.OutputStream;
028import java.io.Serializable;
029import java.math.BigInteger;
030import java.net.URI;
031import java.nio.file.Files;
032import java.nio.file.Path;
033import java.nio.file.Paths;
034import java.security.MessageDigest;
035import java.security.NoSuchAlgorithmException;
036import java.util.HashSet;
037import java.util.Locale;
038import java.util.Objects;
039import java.util.Properties;
040import java.util.Set;
041
042import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
043import com.puppycrawl.tools.checkstyle.api.Configuration;
044import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
045
046/**
047 * This class maintains a persistent(on file-system) store of the files
048 * that have checked ok(no validation events) and their associated
049 * timestamp. It is used to optimize Checkstyle between few launches.
050 * It is mostly useful for plugin and extensions of Checkstyle.
051 * It uses a property file
052 * for storage.  A hashcode of the Configuration is stored in the
053 * cache file to ensure the cache is invalidated when the
054 * configuration has changed.
055 *
056 */
057public final class PropertyCacheFile {
058
059    /**
060     * The property key to use for storing the hashcode of the
061     * configuration. To avoid name clashes with the files that are
062     * checked the key is chosen in such a way that it cannot be a
063     * valid file name.
064     */
065    public static final String CONFIG_HASH_KEY = "configuration*?";
066
067    /**
068     * The property prefix to use for storing the hashcode of an
069     * external resource. To avoid name clashes with the files that are
070     * checked the prefix is chosen in such a way that it cannot be a
071     * valid file name and makes it clear it is a resource.
072     */
073    public static final String EXTERNAL_RESOURCE_KEY_PREFIX = "module-resource*?:";
074
075    /** Size of default byte array for buffer. */
076    private static final int BUFFER_SIZE = 1024;
077
078    /** Default buffer for reading from streams. */
079    private static final byte[] BUFFER = new byte[BUFFER_SIZE];
080
081    /** Default number for base 16 encoding. */
082    private static final int BASE_16 = 16;
083
084    /** The details on files. **/
085    private final Properties details = new Properties();
086
087    /** Configuration object. **/
088    private final Configuration config;
089
090    /** File name of cache. **/
091    private final String fileName;
092
093    /** Generated configuration hash. **/
094    private String configHash;
095
096    /**
097     * Creates a new {@code PropertyCacheFile} instance.
098     *
099     * @param config the current configuration, not null
100     * @param fileName the cache file
101     * @throws IllegalArgumentException when either arguments are null
102     */
103    public PropertyCacheFile(Configuration config, String fileName) {
104        if (config == null) {
105            throw new IllegalArgumentException("config can not be null");
106        }
107        if (fileName == null) {
108            throw new IllegalArgumentException("fileName can not be null");
109        }
110        this.config = config;
111        this.fileName = fileName;
112    }
113
114    /**
115     * Load cached values from file.
116     * @throws IOException when there is a problems with file read
117     */
118    public void load() throws IOException {
119        // get the current config so if the file isn't found
120        // the first time the hash will be added to output file
121        configHash = getHashCodeBasedOnObjectContent(config);
122        final File file = new File(fileName);
123        if (file.exists()) {
124            try (InputStream inStream = Files.newInputStream(file.toPath())) {
125                details.load(inStream);
126                final String cachedConfigHash = details.getProperty(CONFIG_HASH_KEY);
127                if (!configHash.equals(cachedConfigHash)) {
128                    // Detected configuration change - clear cache
129                    reset();
130                }
131            }
132        }
133        else {
134            // put the hash in the file if the file is going to be created
135            reset();
136        }
137    }
138
139    /**
140     * Cleans up the object and updates the cache file.
141     * @throws IOException  when there is a problems with file save
142     */
143    public void persist() throws IOException {
144        final Path path = Paths.get(fileName);
145        final Path directory = path.getParent();
146        if (directory != null) {
147            Files.createDirectories(directory);
148        }
149        try (OutputStream out = Files.newOutputStream(path)) {
150            details.store(out, null);
151        }
152    }
153
154    /**
155     * Resets the cache to be empty except for the configuration hash.
156     */
157    public void reset() {
158        details.clear();
159        details.setProperty(CONFIG_HASH_KEY, configHash);
160    }
161
162    /**
163     * Checks that file is in cache.
164     * @param uncheckedFileName the file to check
165     * @param timestamp the timestamp of the file to check
166     * @return whether the specified file has already been checked ok
167     */
168    public boolean isInCache(String uncheckedFileName, long timestamp) {
169        final String lastChecked = details.getProperty(uncheckedFileName);
170        return Objects.equals(lastChecked, Long.toString(timestamp));
171    }
172
173    /**
174     * Records that a file checked ok.
175     * @param checkedFileName name of the file that checked ok
176     * @param timestamp the timestamp of the file
177     */
178    public void put(String checkedFileName, long timestamp) {
179        details.setProperty(checkedFileName, Long.toString(timestamp));
180    }
181
182    /**
183     * Retrieves the hash of a specific file.
184     * @param name The name of the file to retrieve.
185     * @return The has of the file or {@code null}.
186     */
187    public String get(String name) {
188        return details.getProperty(name);
189    }
190
191    /**
192     * Removed a specific file from the cache.
193     * @param checkedFileName The name of the file to remove.
194     */
195    public void remove(String checkedFileName) {
196        details.remove(checkedFileName);
197    }
198
199    /**
200     * Calculates the hashcode for the serializable object based on its content.
201     * @param object serializable object.
202     * @return the hashcode for serializable object.
203     * @throws IllegalStateException when some unexpected happened.
204     */
205    private static String getHashCodeBasedOnObjectContent(Serializable object) {
206        try {
207            final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
208            // in-memory serialization of Configuration
209            serialize(object, outputStream);
210            // Instead of hexEncoding outputStream.toByteArray() directly we
211            // use a message digest here to keep the length of the
212            // hashcode reasonable
213
214            final MessageDigest digest = MessageDigest.getInstance("SHA-1");
215            digest.update(outputStream.toByteArray());
216
217            return new BigInteger(1, digest.digest()).toString(BASE_16).toUpperCase(Locale.ROOT);
218        }
219        catch (final IOException | NoSuchAlgorithmException ex) {
220            // rethrow as unchecked exception
221            throw new IllegalStateException("Unable to calculate hashcode.", ex);
222        }
223    }
224
225    /**
226     * Serializes object to output stream.
227     * @param object object to be serialized
228     * @param outputStream serialization stream
229     * @throws IOException if an error occurs
230     */
231    private static void serialize(Serializable object,
232                                  OutputStream outputStream) throws IOException {
233        try (ObjectOutputStream oos = new ObjectOutputStream(outputStream)) {
234            oos.writeObject(object);
235        }
236    }
237
238    /**
239     * Puts external resources in cache.
240     * If at least one external resource changed, clears the cache.
241     * @param locations locations of external resources.
242     */
243    public void putExternalResources(Set<String> locations) {
244        final Set<ExternalResource> resources = loadExternalResources(locations);
245        if (areExternalResourcesChanged(resources)) {
246            reset();
247            fillCacheWithExternalResources(resources);
248        }
249    }
250
251    /**
252     * Loads a set of {@link ExternalResource} based on their locations.
253     * @param resourceLocations locations of external configuration resources.
254     * @return a set of {@link ExternalResource}.
255     */
256    private static Set<ExternalResource> loadExternalResources(Set<String> resourceLocations) {
257        final Set<ExternalResource> resources = new HashSet<>();
258        for (String location : resourceLocations) {
259            try {
260                final byte[] content = loadExternalResource(location);
261                final String contentHashSum = getHashCodeBasedOnObjectContent(content);
262                resources.add(new ExternalResource(EXTERNAL_RESOURCE_KEY_PREFIX + location,
263                        contentHashSum));
264            }
265            catch (CheckstyleException | IOException ex) {
266                // if exception happened (configuration resource was not found, connection is not
267                // available, resource is broken, etc), we need to calculate hash sum based on
268                // exception object content in order to check whether problem is resolved later
269                // and/or the configuration is changed.
270                final String contentHashSum = getHashCodeBasedOnObjectContent(ex);
271                resources.add(new ExternalResource(EXTERNAL_RESOURCE_KEY_PREFIX + location,
272                        contentHashSum));
273            }
274        }
275        return resources;
276    }
277
278    /**
279     * Loads the content of external resource.
280     * @param location external resource location.
281     * @return array of bytes which represents the content of external resource in binary form.
282     * @throws IOException if error while loading occurs.
283     * @throws CheckstyleException if error while loading occurs.
284     */
285    private static byte[] loadExternalResource(String location)
286            throws IOException, CheckstyleException {
287        final URI uri = CommonUtil.getUriByFilename(location);
288
289        try (InputStream is = uri.toURL().openStream()) {
290            return toByteArray(is);
291        }
292    }
293
294    /**
295     * Reads all the contents of an input stream and returns it as a byte array.
296     * @param stream The input stream to read from.
297     * @return The resulting byte array of the stream.
298     * @throws IOException if there is an error reading the input stream.
299     */
300    private static byte[] toByteArray(InputStream stream) throws IOException {
301        final ByteArrayOutputStream content = new ByteArrayOutputStream();
302
303        while (true) {
304            final int size = stream.read(BUFFER);
305            if (size == -1) {
306                break;
307            }
308
309            content.write(BUFFER, 0, size);
310        }
311
312        return content.toByteArray();
313    }
314
315    /**
316     * Checks whether the contents of external configuration resources were changed.
317     * @param resources a set of {@link ExternalResource}.
318     * @return true if the contents of external configuration resources were changed.
319     */
320    private boolean areExternalResourcesChanged(Set<ExternalResource> resources) {
321        return resources.stream().anyMatch(resource -> {
322            boolean changed = false;
323            if (isResourceLocationInCache(resource.location)) {
324                final String contentHashSum = resource.contentHashSum;
325                final String cachedHashSum = details.getProperty(resource.location);
326                if (!cachedHashSum.equals(contentHashSum)) {
327                    changed = true;
328                }
329            }
330            else {
331                changed = true;
332            }
333            return changed;
334        });
335    }
336
337    /**
338     * Fills cache with a set of {@link ExternalResource}.
339     * If external resource from the set is already in cache, it will be skipped.
340     * @param externalResources a set of {@link ExternalResource}.
341     */
342    private void fillCacheWithExternalResources(Set<ExternalResource> externalResources) {
343        externalResources
344            .forEach(resource -> details.setProperty(resource.location, resource.contentHashSum));
345    }
346
347    /**
348     * Checks whether resource location is in cache.
349     * @param location resource location.
350     * @return true if resource location is in cache.
351     */
352    private boolean isResourceLocationInCache(String location) {
353        final String cachedHashSum = details.getProperty(location);
354        return cachedHashSum != null;
355    }
356
357    /**
358     * Class which represents external resource.
359     */
360    private static class ExternalResource {
361
362        /** Location of resource. */
363        private final String location;
364        /** Hash sum which is calculated based on resource content. */
365        private final String contentHashSum;
366
367        /**
368         * Creates an instance.
369         * @param location resource location.
370         * @param contentHashSum content hash sum.
371         */
372        /* package */ ExternalResource(String location, String contentHashSum) {
373            this.location = location;
374            this.contentHashSum = contentHashSum;
375        }
376
377    }
378
379}