FileAnalysisCache extends AbstractAnalysisCache { @Override public void persist() { if (cacheFile.isDirectory()) { LOG.severe("Cannot persist the cache, the given path points to a directory."); return; } boolean cacheFileShouldBeCreated = !cacheFile.exists(); if (cacheFileShouldBeCreated) { final File parentFile = cacheFile.getAbsoluteFile().getParentFile(); if (parentFile != null && !parentFile.exists()) { parentFile.mkdirs(); } } try ( DataOutputStream outputStream = new DataOutputStream( new BufferedOutputStream(Files.newOutputStream(cacheFile.toPath()))) ) { outputStream.writeUTF(pmdVersion); outputStream.writeLong(rulesetChecksum); outputStream.writeLong(auxClassPathChecksum); outputStream.writeLong(executionClassPathChecksum); for (final Map.Entry<String, AnalysisResult> resultEntry : updatedResultsCache.entrySet()) { final List<RuleViolation> violations = resultEntry.getValue().getViolations(); outputStream.writeUTF(resultEntry.getKey()); outputStream.writeLong(resultEntry.getValue().getFileChecksum()); outputStream.writeInt(violations.size()); for (final RuleViolation rv : violations) { CachedRuleViolation.storeToStream(outputStream, rv); } } if (cacheFileShouldBeCreated) { LOG.info("Analysis cache created"); } else { LOG.info("Analysis cache updated"); } } catch (final IOException e) { LOG.severe("Could not persist analysis cache to file. " + e.getMessage()); } } FileAnalysisCache(final File cache); @Override void persist();  }
@Test public void testStoreCreatesFile() { final FileAnalysisCache cache = new FileAnalysisCache(unexistingCacheFile); cache.persist(); assertTrue("Cache file doesn't exist after store", unexistingCacheFile.exists()); }
@Test public void testStoreOnUnwritableFileShouldntThrow() { emptyCacheFile.setWritable(false); final FileAnalysisCache cache = new FileAnalysisCache(emptyCacheFile); cache.persist(); }
@Test public void testStorePersistsFilesWithViolations() { final FileAnalysisCache cache = new FileAnalysisCache(newCacheFile); cache.isUpToDate(sourceFile); final RuleViolation rv = mock(RuleViolation.class); when(rv.getFilename()).thenReturn(sourceFile.getPath()); final net.sourceforge.pmd.Rule rule = mock(net.sourceforge.pmd.Rule.class, Mockito.RETURNS_SMART_NULLS); when(rule.getLanguage()).thenReturn(mock(Language.class)); when(rv.getRule()).thenReturn(rule); cache.ruleViolationAdded(rv); cache.persist(); final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile); assertTrue("Cache believes unmodified file with violations is not up to date", reloadedCache.isUpToDate(sourceFile)); final List<RuleViolation> cachedViolations = reloadedCache.getCachedViolations(sourceFile); assertEquals("Cached rule violations count mismatch", 1, cachedViolations.size()); }