result = new HashMap<>();
for (int i = 0; i < nnm.getLength(); i++) {
@@ -606,6 +608,7 @@ public void readMatcherBuilders() {
nodeListConsumer(document.getElementsByTagName(XMLConfig.MATCHER), this::parseMatcherBuilder);
}
+ @SuppressFBWarnings("URLCONNECTION_SSRF_FD")
@Override
public void addMatchers(final URI uri) {
read(uri);
diff --git a/apache-rat-core/src/main/java/org/apache/rat/configuration/builders/ChildContainerBuilder.java b/apache-rat-core/src/main/java/org/apache/rat/configuration/builders/ChildContainerBuilder.java
index d40a657d2..172314fbe 100644
--- a/apache-rat-core/src/main/java/org/apache/rat/configuration/builders/ChildContainerBuilder.java
+++ b/apache-rat-core/src/main/java/org/apache/rat/configuration/builders/ChildContainerBuilder.java
@@ -59,7 +59,7 @@ protected ChildContainerBuilder() {
*/
public AbstractBuilder setResource(final String resourceName) {
// this method is called by reflection
- URL url = this.getClass().getResource(resourceName);
+ URL url = AbstractBuilder.class.getResource(resourceName);
if (url == null) {
throw new ConfigurationException("Unable to read matching text file: " + resourceName);
}
diff --git a/apache-rat-core/src/main/java/org/apache/rat/configuration/builders/MatcherRefBuilder.java b/apache-rat-core/src/main/java/org/apache/rat/configuration/builders/MatcherRefBuilder.java
index 68598d4c7..1662220f3 100644
--- a/apache-rat-core/src/main/java/org/apache/rat/configuration/builders/MatcherRefBuilder.java
+++ b/apache-rat-core/src/main/java/org/apache/rat/configuration/builders/MatcherRefBuilder.java
@@ -27,6 +27,8 @@
import org.apache.rat.config.parameters.ConfigComponent;
import org.apache.rat.config.parameters.MatcherBuilder;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+
/**
* A reference matching Matcher builder.
*
@@ -62,6 +64,7 @@ public MatcherRefBuilder setRefId(final String refId) {
* @param matchers the Map of ids to instances.
* @return this builder for chaining.
*/
+ @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "Expected external update of matchers.")
public MatcherRefBuilder setMatcherMap(final Map matchers) {
// this method is called by reflection
this.matchers = matchers;
@@ -109,6 +112,7 @@ public static class IHeaderMatcherProxy implements IHeaderMatcher {
* @param proxyId the id of the matcher to find.
* @param matchers a mapping of matchers that have been found.
*/
+ @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "Expected external update of matchers.")
public IHeaderMatcherProxy(final String proxyId, final Map matchers) {
this.proxyId = proxyId;
this.matchers = matchers;
diff --git a/apache-rat-core/src/main/java/org/apache/rat/document/ArchiveEntryDocument.java b/apache-rat-core/src/main/java/org/apache/rat/document/ArchiveEntryDocument.java
deleted file mode 100644
index dabc848bc..000000000
--- a/apache-rat-core/src/main/java/org/apache/rat/document/ArchiveEntryDocument.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- */
-
-package org.apache.rat.document;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.util.Collections;
-import java.util.SortedSet;
-
-import org.apache.rat.api.Document;
-
-/**
- * A Document that wraps an Archive entry.
- */
-public class ArchiveEntryDocument extends Document {
-
- /** The contents of the entry */
- private final byte[] contents;
-
- /**
- * Creates an Archive entry.
- * @param entryName the name of this entry from outside the archive.
- * @param contents the contents of the entry.
- * @param nameMatcher the name matcher to filter contents with.
- */
- public ArchiveEntryDocument(final ArchiveEntryName entryName, final byte[] contents, final DocumentNameMatcher nameMatcher) {
- super(entryName, nameMatcher);
- this.contents = contents;
- }
-
- @Override
- public InputStream inputStream() {
- return new ByteArrayInputStream(contents);
- }
-
- @Override
- public boolean isDirectory() {
- return false;
- }
-
- @Override
- public SortedSet listChildren() {
- return Collections.emptySortedSet();
- }
-}
diff --git a/apache-rat-core/src/main/java/org/apache/rat/header/HeaderMatcher.java b/apache-rat-core/src/main/java/org/apache/rat/header/HeaderMatcher.java
index 89b71b0a2..7f05afa3a 100644
--- a/apache-rat-core/src/main/java/org/apache/rat/header/HeaderMatcher.java
+++ b/apache-rat-core/src/main/java/org/apache/rat/header/HeaderMatcher.java
@@ -18,6 +18,7 @@
*/
package org.apache.rat.header;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.apache.rat.DeprecationReporter;
import java.io.IOException;
@@ -35,6 +36,7 @@
* Note: use only from a single thread.
*
*/
+@SuppressFBWarnings("EI_EXPOSE_REP2")
@Deprecated // since 0.17
@DeprecationReporter.Info(since = "0.17", forRemoval = true)
public class HeaderMatcher {
diff --git a/apache-rat-core/src/main/java/org/apache/rat/help/Licenses.java b/apache-rat-core/src/main/java/org/apache/rat/help/Licenses.java
index 0277186b0..bac55af54 100644
--- a/apache-rat-core/src/main/java/org/apache/rat/help/Licenses.java
+++ b/apache-rat-core/src/main/java/org/apache/rat/help/Licenses.java
@@ -43,6 +43,8 @@
import org.apache.rat.license.ILicenseFamily;
import org.apache.rat.license.LicenseSetFactory.LicenseFilter;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+
import static java.lang.String.format;
/**
@@ -64,6 +66,7 @@ public final class Licenses extends AbstractHelp {
* @param config The configuration that contains the license information.
* @param writer the writer to write the report to.
*/
+ @SuppressFBWarnings("EI_EXPOSE_REP2")
public Licenses(final ReportConfiguration config, final Writer writer) {
this.config = config;
this.licenses = config.getLicenses(LicenseFilter.ALL);
diff --git a/apache-rat-core/src/main/java/org/apache/rat/license/LicenseSetFactory.java b/apache-rat-core/src/main/java/org/apache/rat/license/LicenseSetFactory.java
index 6fe00db5a..5474501ff 100644
--- a/apache-rat-core/src/main/java/org/apache/rat/license/LicenseSetFactory.java
+++ b/apache-rat-core/src/main/java/org/apache/rat/license/LicenseSetFactory.java
@@ -20,13 +20,19 @@
import java.util.Collection;
import java.util.Collections;
+import java.util.HashSet;
import java.util.Optional;
+import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.function.Predicate;
+import java.util.stream.Collectors;
+import org.apache.commons.collections4.set.UnmodifiableSortedSet;
+import org.apache.rat.ConfigurationException;
import org.apache.rat.analysis.IHeaderMatcher;
import org.apache.rat.analysis.IHeaders;
+import org.apache.rat.utils.DefaultLog;
import org.apache.rat.utils.Log;
import org.apache.rat.utils.ReportingSet;
@@ -121,6 +127,31 @@ public LicenseSetFactory(final SortedSet licenses) {
licenses.forEach(l -> families.addIfNotPresent(l.getLicenseFamily()));
}
+ public void validate() {
+ Log log = DefaultLog.getInstance();
+
+ // verify license definitions exist
+ if (getLicenses(LicenseFilter.ALL).isEmpty()) {
+ String msg = "At least one license must be defined";
+ log.error(msg);
+ throw new ConfigurationException(msg);
+ }
+
+ // verify that all approved license families exist
+ Set exists = getLicenseFamilies(LicenseFilter.ALL)
+ .stream().map(ILicenseFamily::getFamilyCategory).collect(Collectors.toSet());
+ Set approved = new HashSet<>(approvedLicenseCategories);
+ approved.removeIf(exists::contains);
+ approved.forEach(name -> log.warn(String.format("License category '%s' was approved but does not exist.", name)));
+
+ // verify that all approved licenses exist
+ exists = getLicenses(LicenseFilter.ALL)
+ .stream().map(ILicense::getId).collect(Collectors.toSet());
+ approved = new HashSet<>(approvedLicenseIds);
+ approved.removeIf(exists::contains);
+ approved.forEach(name -> log.warn(String.format("License '%s' was approved but does not exist.", name)));
+ }
+
public void add(final LicenseSetFactory other) {
this.families.addAll(other.families);
this.licenses.addAll(other.licenses);
@@ -289,18 +320,21 @@ public Predicate getApprovedLicensePredicate() {
* @param filter the types of LicenseFamily objects to return.
* @return a SortedSet of ILicense objects.
*/
- public SortedSet getLicenses(final LicenseFilter filter) {
+ public UnmodifiableSortedSet getLicenses(final LicenseFilter filter) {
+ SortedSet result;
switch (filter) {
case ALL:
- return Collections.unmodifiableSortedSet(licenses);
+ result = licenses;
+ break;
case APPROVED:
- SortedSet result = new TreeSet<>();
+ result = new TreeSet<>();
licenses.stream().filter(getApprovedLicensePredicate()).forEach(result::add);
- return result;
+ break;
case NONE:
default:
- return Collections.emptySortedSet();
+ result = Collections.emptySortedSet();
}
+ return (UnmodifiableSortedSet) UnmodifiableSortedSet.unmodifiableSortedSet(result);
}
/**
diff --git a/apache-rat-core/src/main/java/org/apache/rat/report/IReportable.java b/apache-rat-core/src/main/java/org/apache/rat/report/Reportable.java
similarity index 96%
rename from apache-rat-core/src/main/java/org/apache/rat/report/IReportable.java
rename to apache-rat-core/src/main/java/org/apache/rat/report/Reportable.java
index 2c108af6c..9d131ed85 100644
--- a/apache-rat-core/src/main/java/org/apache/rat/report/IReportable.java
+++ b/apache-rat-core/src/main/java/org/apache/rat/report/Reportable.java
@@ -21,7 +21,7 @@
import org.apache.rat.api.RatException;
import org.apache.rat.document.DocumentName;
-public interface IReportable {
+public interface Reportable {
/**
* Adds the reportable to the RatReport.
* @param report the report to add the results to.
@@ -33,5 +33,5 @@ public interface IReportable {
* Returns the DocumentName for the reportable.
* @return the DocumentName for the reportable.
*/
- DocumentName getName();
+ DocumentName name();
}
diff --git a/apache-rat-core/src/main/java/org/apache/rat/report/claim/ClaimStatistic.java b/apache-rat-core/src/main/java/org/apache/rat/report/claim/ClaimStatistic.java
index 62572916c..f2aac3a88 100644
--- a/apache-rat-core/src/main/java/org/apache/rat/report/claim/ClaimStatistic.java
+++ b/apache-rat-core/src/main/java/org/apache/rat/report/claim/ClaimStatistic.java
@@ -19,14 +19,24 @@
package org.apache.rat.report.claim;
+import java.io.IOException;
+import java.io.InputStream;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
+import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
+import javax.xml.parsers.DocumentBuilder;
+
+import org.apache.commons.io.function.IOSupplier;
import org.apache.commons.lang3.StringUtils;
import org.apache.rat.api.Document;
+import org.apache.rat.configuration.XMLConfigurationReader;
+import org.apache.rat.report.xml.writer.XmlWriter;
+import org.apache.rat.utils.StandardXmlFactory;
+import org.xml.sax.SAXException;
/**
* This class provides a numerical overview about
@@ -113,6 +123,9 @@ public String displayName() {
/** Map of counter type to value */
private final ConcurrentHashMap counterMap = new ConcurrentHashMap<>();
+ public Serde serde() {
+ return new Serde();
+ }
/**
* Converts null counter to 0.
*
@@ -141,6 +154,15 @@ public void incCounter(final Counter counter, final int value) {
counterMap.compute(counter, (k, v) -> v == null ? new IntCounter().increment(value) : v.increment(value));
}
+ /**
+ * Increments the counts for the counter.
+ * @param counter the counter to increment.
+ * @param value the value to increment the counter by.
+ */
+ public void setCounter(final Counter counter, final int value) {
+ counterMap.put(counter, new IntCounter().increment(value));
+ }
+
/**
* Gets the counts for the Document.Type.
* @param documentType the Document.Type to get the counter for.
@@ -288,5 +310,105 @@ public IntCounter increment(final int count) {
public int value() {
return value;
}
+
+ @Override
+ public String toString() {
+ return String.valueOf(value);
+ }
+ }
+
+ /**
+ * Serialze and deserialze the claim Statistic.
+ */
+ public class Serde {
+ /** The count attribute string */
+ private static final String COUNT = "count";
+ /** the name attribute string */
+ private static final String NAME = "name";
+
+ /**
+ * Serializes the claim statistic into an appendable.
+ * @param appendable the appendable to write to
+ * @throws IOException on error.
+ */
+ public void serialize(final Appendable appendable) throws IOException {
+ try (XmlWriter writer = new XmlWriter(appendable)) {
+ writer.startDocument().startElement("ClaimStatistic")
+ .startElement("licenseNameMap");
+ for (Map.Entry entry : licenseNameMap.entrySet()) {
+ if (entry.getValue().value > 0) {
+ writer.startElement("licenseName")
+ .attribute(COUNT, entry.getValue().toString())
+ .attribute(NAME, entry.getKey()).closeElement();
+ }
+ }
+ writer.closeElement()
+ .startElement("licenseFamilyCategoryMap");
+ for (Map.Entry entry : licenseFamilyCategoryMap.entrySet()) {
+ if (entry.getValue().value > 0) {
+ writer.startElement("familyCategory")
+ .attribute(COUNT, entry.getValue().toString())
+ .attribute(NAME, entry.getKey()).closeElement();
+ }
+ }
+ writer.closeElement()
+ .startElement("documentTypeMap");
+ for (Map.Entry entry : documentTypeMap.entrySet()) {
+ if (entry.getValue().value > 0) {
+ writer.startElement("documentType")
+ .attribute(COUNT, entry.getValue().toString())
+ .attribute(NAME, entry.getKey().name()).closeElement();
+ }
+ }
+ writer.closeElement()
+ .startElement("counterMap");
+ for (Map.Entry entry : counterMap.entrySet()) {
+ if (entry.getValue().value > 0) {
+ writer.startElement("counter")
+ .attribute(COUNT, entry.getValue().toString())
+ .attribute(NAME, entry.getKey().name()).closeElement();
+ }
+ }
+ writer.closeElement();
+ }
+ }
+
+ /**
+ * Deserializes a ClaimStatistic from an input stream.
+ * @param inputStreamSupplier the supplier of the input stream to deserialize from.
+ * @throws IOException on error.
+ */
+ public void deserialize(final IOSupplier inputStreamSupplier) throws IOException {
+ DocumentBuilder builder = StandardXmlFactory.documentBuilder();
+ org.w3c.dom.Document document;
+ try (InputStream stream = inputStreamSupplier.get()) {
+ document = builder.parse(stream);
+
+ } catch (SAXException e) {
+ throw new IOException("Unable to read input", e);
+ }
+
+ XMLConfigurationReader.nodeListConsumer(document.getElementsByTagName("licenseName"), node -> {
+ Map attributes = XMLConfigurationReader.attributes(node);
+ incLicenseNameCount(attributes.get(NAME), Integer.parseInt(attributes.get(COUNT)));
+ });
+
+ XMLConfigurationReader.nodeListConsumer(document.getElementsByTagName("familyCategory"), node -> {
+ Map attributes = XMLConfigurationReader.attributes(node);
+ incLicenseCategoryCount(attributes.get(NAME), Integer.parseInt(attributes.get(COUNT)));
+ });
+
+ XMLConfigurationReader.nodeListConsumer(document.getElementsByTagName("documentType"), node -> {
+ Map attributes = XMLConfigurationReader.attributes(node);
+ Document.Type type = Document.Type.valueOf(attributes.get(NAME));
+ incCounter(type, Integer.parseInt(attributes.get(COUNT)));
+ });
+
+ XMLConfigurationReader.nodeListConsumer(document.getElementsByTagName("counter"), node -> {
+ Map attributes = XMLConfigurationReader.attributes(node);
+ Counter type = Counter.valueOf(attributes.get(NAME));
+ setCounter(type, Integer.parseInt(attributes.get(COUNT)));
+ });
+ }
}
}
diff --git a/apache-rat-core/src/test/java/org/apache/rat/testhelpers/FileUtils.java b/apache-rat-core/src/main/java/org/apache/rat/utils/FileUtils.java
similarity index 79%
rename from apache-rat-core/src/test/java/org/apache/rat/testhelpers/FileUtils.java
rename to apache-rat-core/src/main/java/org/apache/rat/utils/FileUtils.java
index 5681e7972..453f7ec60 100644
--- a/apache-rat-core/src/test/java/org/apache/rat/testhelpers/FileUtils.java
+++ b/apache-rat-core/src/main/java/org/apache/rat/utils/FileUtils.java
@@ -16,24 +16,27 @@
* specific language governing permissions and limitations *
* under the License. *
*/
-package org.apache.rat.testhelpers;
+package org.apache.rat.utils;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
+import java.nio.file.Files;
import java.util.Arrays;
import java.util.Collections;
-import static org.assertj.core.api.Fail.fail;
-public class FileUtils {
+public final class FileUtils {
+ private FileUtils() {
+ // do not instantiate
+ }
/**
* Creates a directory if it does not exist.
* @param dir the directory to make.
*/
- public static void mkDir(File dir) {
+ public static void mkDir(final File dir) {
boolean ignored = dir.mkdirs();
}
@@ -41,7 +44,7 @@ public static void mkDir(File dir) {
* Deletes a file if it exists.
* @param file the file to delete.
*/
- public static void delete(File file) {
+ public static void delete(final File file) throws IOException {
if (file.exists()) {
if (file.isDirectory()) {
try {
@@ -50,7 +53,7 @@ public static void delete(File file) {
//
}
} else {
- boolean ignored = file.delete();
+ Files.delete(file.toPath());
}
}
}
@@ -62,15 +65,16 @@ public static void delete(File file) {
* @param lines the lines to write into the file.
* @return the new File.
*/
- static public File writeFile(File dir, final String name, final Iterable lines) {
+ public static File writeFile(final File dir, final String name, final Iterable lines) {
if (dir == null) {
- fail("base directory not specified");
+ throw new IllegalArgumentException("base directory not specified");
}
+ mkDir(dir);
File file = new File(dir, name);
try (PrintWriter writer = new PrintWriter(new FileWriter(file))) {
lines.forEach(writer::println);
} catch (IOException e) {
- fail(e.getMessage());
+ throw new RuntimeException(e.getMessage(), e);
}
return file;
}
@@ -82,7 +86,7 @@ static public File writeFile(File dir, final String name, final Iterable
* @param lines the lines to write into the file.
* @return the new File.
*/
- static public File writeFile(File dir, final String name, final String... lines) {
+ public static File writeFile(final File dir, final String name, final String... lines) {
return writeFile(dir, name, Arrays.asList(lines));
}
@@ -92,7 +96,7 @@ static public File writeFile(File dir, final String name, final String... lines)
* @param name the name of the file.
* @return the new file.
*/
- public static File writeFile(File dir, String name) {
+ public static File writeFile(final File dir, final String name) {
return writeFile(dir, name, Collections.singletonList(name));
}
}
diff --git a/apache-rat-core/src/main/java/org/apache/rat/utils/StandardXmlFactory.java b/apache-rat-core/src/main/java/org/apache/rat/utils/StandardXmlFactory.java
index 38f4cd08e..9b833fbf5 100644
--- a/apache-rat-core/src/main/java/org/apache/rat/utils/StandardXmlFactory.java
+++ b/apache-rat-core/src/main/java/org/apache/rat/utils/StandardXmlFactory.java
@@ -18,7 +18,12 @@
*/
package org.apache.rat.utils;
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
import java.io.InputStream;
+import java.io.StringWriter;
+import java.util.Properties;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
@@ -27,9 +32,15 @@
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
+import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
+import org.w3c.dom.Document;
+
+
/**
* Factory to create standard XML objects. The intention of this class is to resolve in a consistent manner the
* XXE errors and similar XML IO errors.
@@ -53,16 +64,28 @@ private StandardXmlFactory() {
* @throws TransformerConfigurationException on error.
*/
public static Transformer create() throws TransformerConfigurationException {
- return create(null);
+ return create(null, new Properties());
}
/**
- * Create a transformer with the specified stylesheet.
- * @param styleIn the stylesheet to use.
+ * Create a transformer with specified style sheet.
+ * @param styleIn the style sheet input stream
* @return the transformer.
* @throws TransformerConfigurationException on error.
*/
public static Transformer create(final InputStream styleIn) throws TransformerConfigurationException {
+ return create(styleIn, new Properties());
+ }
+
+ /**
+ * Create a transformer with the specified stylesheet and additional properties.
+ * By default, the output omits the XML declaration, uses XML output, indents rsult with 4 spaces.
+ * @param styleIn the stylesheet to use.
+ * @param transformerProperties Additional output transformer properties.
+ * @return the transformer.
+ * @throws TransformerConfigurationException on error.
+ */
+ public static Transformer create(final InputStream styleIn, final Properties transformerProperties) throws TransformerConfigurationException {
TransformerFactory factory = TransformerFactory.newInstance();
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
@@ -73,6 +96,9 @@ public static Transformer create(final InputStream styleIn) throws TransformerCo
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
+ if (transformerProperties != null) {
+ transformer.setOutputProperties(transformerProperties);
+ }
return transformer;
}
@@ -94,4 +120,28 @@ public static DocumentBuilder documentBuilder() {
throw new IllegalStateException("No XML parser defined", e);
}
}
+
+ /**
+ * Write an XML document to a file.
+ * @param document the document to write
+ * @param file the file to write to.
+ */
+ public static void writeDocument(final Document document, final File file) throws IOException, TransformerException {
+ DOMSource source = new DOMSource(document);
+ FileWriter writer = new FileWriter(file);
+ StreamResult result = new StreamResult(writer);
+ create().transform(source, result);
+ }
+
+ /**
+ * Write an XML document to a file.
+ * @param document the document to write.
+ */
+ public static String serializeDocument(final Document document) throws TransformerException {
+ DOMSource source = new DOMSource(document);
+ StringWriter writer = new StringWriter();
+ StreamResult result = new StreamResult(writer);
+ create().transform(source, result);
+ return writer.toString();
+ }
}
diff --git a/apache-rat-core/src/main/java/org/apache/rat/walker/ArchiveWalker.java b/apache-rat-core/src/main/java/org/apache/rat/walker/ArchiveWalker.java
index a50aa5ef8..4ad410449 100644
--- a/apache-rat-core/src/main/java/org/apache/rat/walker/ArchiveWalker.java
+++ b/apache-rat-core/src/main/java/org/apache/rat/walker/ArchiveWalker.java
@@ -20,12 +20,15 @@
package org.apache.rat.walker;
import java.io.BufferedInputStream;
+import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
+import java.util.Collections;
import java.util.List;
+import java.util.SortedSet;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.ArchiveException;
@@ -34,9 +37,9 @@
import org.apache.commons.io.IOUtils;
import org.apache.rat.api.Document;
import org.apache.rat.api.RatException;
-import org.apache.rat.document.ArchiveEntryDocument;
import org.apache.rat.document.ArchiveEntryName;
import org.apache.rat.document.DocumentName;
+import org.apache.rat.document.DocumentNameMatcher;
import org.apache.rat.report.RatReport;
import org.apache.rat.utils.DefaultLog;
@@ -87,13 +90,29 @@ public Collection getDocuments() throws RatException {
ArchiveEntry entry;
while ((entry = input.getNextEntry()) != null) {
if (!entry.isDirectory() && input.canReadEntryData(entry)) {
- DocumentName innerName = DocumentName.builder().setName(entry.getName())
+ final DocumentName innerName = DocumentName.builder().setName(entry.getName())
.setBaseName(".").build();
- if (this.getDocument().getNameMatcher().matches(innerName)) {
+ final DocumentNameMatcher documentNameMatcher = getDocument().getNameMatcher();
+ if (documentNameMatcher.matches(innerName)) {
+ ArchiveEntryName entryName = new ArchiveEntryName(getDocument().getName(), entry.getName());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(input, baos);
- ArchiveEntryName entryName = new ArchiveEntryName(getDocument().getName(), entry.getName());
- result.add(new ArchiveEntryDocument(entryName, baos.toByteArray(), getDocument().getNameMatcher()));
+ result.add(new Document(entryName, documentNameMatcher) {
+ @Override
+ public InputStream inputStream() {
+ return new ByteArrayInputStream(baos.toByteArray());
+ }
+
+ @Override
+ public boolean isDirectory() {
+ return false;
+ }
+
+ @Override
+ public SortedSet listChildren() {
+ return Collections.emptySortedSet();
+ }
+ });
}
}
}
diff --git a/apache-rat-core/src/main/java/org/apache/rat/walker/FileListWalker.java b/apache-rat-core/src/main/java/org/apache/rat/walker/FileListWalker.java
index 056090858..eb62c0f29 100644
--- a/apache-rat-core/src/main/java/org/apache/rat/walker/FileListWalker.java
+++ b/apache-rat-core/src/main/java/org/apache/rat/walker/FileListWalker.java
@@ -29,15 +29,15 @@
import org.apache.rat.document.DocumentName;
import org.apache.rat.document.DocumentNameMatcher;
import org.apache.rat.document.FileDocument;
-import org.apache.rat.report.IReportable;
import org.apache.rat.report.RatReport;
+import org.apache.rat.report.Reportable;
import org.apache.rat.utils.DefaultLog;
/**
* Implementation of IReportable that traverses over a resource collection
* internally.
*/
-public class FileListWalker implements IReportable {
+public class FileListWalker implements Reportable {
/** The source document name. */
private final FileDocument source;
/** The root document name. */
@@ -72,7 +72,7 @@ private FileDocument createDocument(final String unixFileName) {
@Override
public void run(final RatReport report) throws RatException {
DefaultLog.getInstance().debug(String.format("Reading file name: %s due to option %s", source, Arg.SOURCE.option()));
- DocumentName sourceName = getName();
+ DocumentName sourceName = name();
try (Reader reader = source.reader()) {
for (String docName : IOUtils.readLines(reader)) {
try {
@@ -93,7 +93,7 @@ public void run(final RatReport report) throws RatException {
}
@Override
- public DocumentName getName() {
+ public DocumentName name() {
return source.getName();
}
}
diff --git a/apache-rat-core/src/main/java/org/apache/rat/walker/IReportableListWalker.java b/apache-rat-core/src/main/java/org/apache/rat/walker/ReportableListWalker.java
similarity index 85%
rename from apache-rat-core/src/main/java/org/apache/rat/walker/IReportableListWalker.java
rename to apache-rat-core/src/main/java/org/apache/rat/walker/ReportableListWalker.java
index b028b9c68..b4afad47e 100644
--- a/apache-rat-core/src/main/java/org/apache/rat/walker/IReportableListWalker.java
+++ b/apache-rat-core/src/main/java/org/apache/rat/walker/ReportableListWalker.java
@@ -24,18 +24,18 @@
import org.apache.rat.api.RatException;
import org.apache.rat.document.DocumentName;
-import org.apache.rat.report.IReportable;
import org.apache.rat.report.RatReport;
+import org.apache.rat.report.Reportable;
import org.apache.rat.utils.DefaultLog;
/**
* A Reportable that walks a list of IReportables and executes the run on each.
*/
-public final class IReportableListWalker implements IReportable {
+public final class ReportableListWalker implements Reportable {
/** The document name for this walker. */
private final DocumentName documentName;
/** The list of reportables for this walker. */
- private final List reportables;
+ private final List reportables;
/**
* Create a builder for the list walker.
@@ -50,24 +50,24 @@ public static Builder builder(final DocumentName name) {
* Construct the builder.
* @param builder for the reportable.
*/
- private IReportableListWalker(final Builder builder) {
+ private ReportableListWalker(final Builder builder) {
this.documentName = builder.documentName;
this.reportables = builder.reportables;
}
@Override
public void run(final RatReport report) {
- for (IReportable reportable : reportables) {
+ for (Reportable reportable : reportables) {
try {
reportable.run(report);
} catch (RatException e) {
- DefaultLog.getInstance().error("Error processing " + reportable.getName(), e);
+ DefaultLog.getInstance().error("Error processing " + reportable.name(), e);
}
}
}
@Override
- public DocumentName getName() {
+ public DocumentName name() {
return documentName;
}
@@ -78,7 +78,7 @@ public static final class Builder {
/** The document name for the walker. */
private final DocumentName documentName;
/** The list of IReportable objects to execute. */
- private List reportables = new ArrayList<>();
+ private List reportables = new ArrayList<>();
/**
* Constructs the builder.
@@ -94,7 +94,7 @@ private Builder(final DocumentName name) {
* @param reportable the reportable to run.
* @return this.
*/
- public Builder addReportable(final IReportable reportable) {
+ public Builder addReportable(final Reportable reportable) {
this.reportables.add(reportable);
return this;
}
@@ -104,11 +104,11 @@ public Builder addReportable(final IReportable reportable) {
* @return the reportable.
* @throws RatException on error.
*/
- public IReportable build() throws RatException {
+ public Reportable build() throws RatException {
if (reportables == null) {
throw new RatException("Builder may only be used once");
}
- IReportable result = new IReportableListWalker(this);
+ Reportable result = new ReportableListWalker(this);
this.reportables = null;
return result;
}
diff --git a/apache-rat-core/src/main/java/org/apache/rat/walker/Walker.java b/apache-rat-core/src/main/java/org/apache/rat/walker/Walker.java
index 5651f7ab9..a6df1e25c 100644
--- a/apache-rat-core/src/main/java/org/apache/rat/walker/Walker.java
+++ b/apache-rat-core/src/main/java/org/apache/rat/walker/Walker.java
@@ -21,12 +21,12 @@
import org.apache.rat.api.Document;
import org.apache.rat.document.DocumentName;
-import org.apache.rat.report.IReportable;
+import org.apache.rat.report.Reportable;
/**
* Abstract walker.
*/
-public abstract class Walker implements IReportable {
+public abstract class Walker implements Reportable {
/** The document this walker is walking */
private final Document document;
@@ -48,7 +48,7 @@ protected Document getDocument() {
}
@Override
- public DocumentName getName() {
+ public DocumentName name() {
return document.getName();
}
}
diff --git a/apache-rat-core/src/main/resources/org/apache/rat/xhtml5.xsl b/apache-rat-core/src/main/resources/org/apache/rat/xhtml5.xsl
new file mode 100644
index 000000000..b15224605
--- /dev/null
+++ b/apache-rat-core/src/main/resources/org/apache/rat/xhtml5.xsl
@@ -0,0 +1,354 @@
+
+
+
+
+
+
+
+
+ ❗
+ 🗜
+ 🔠
+ 🚫
+ ℹ
+ ✅
+ ❓
+ 📂
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Rat Report
+
+
+
+
+
+
+
+
+
+
+
+
+ Detail
+
+
+ Documents with unapproved licenses will start with a
+ The first character on the next line identifies the document type.
+
+
+
+ Symbols used in this RAT report
+
+
+ | Symbol |
+ Type |
+
+
+ |
+ Archive file |
+
+
+ |
+ Binary file |
+
+
+ |
+ Ignored file |
+
+
+ |
+ Notice file |
+
+
+ |
+ Standard file |
+
+
+ |
+ Unknown file |
+
+
+ |
+ Directory |
+
+
+
+
+
+ Resources discovered in this RAT report
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+ ID:
+
+ UUID
+
+
+
+ Family:
+
+ Unknown
+
+
+
+
+
+ |
+
+
+
+
+
+
+ Summary
+
+
+
Generated at by
+
+
+
+
+
+ Table 1: A summary of statistics from this RAT report.
+
+
+ | Name: |
+ Count: |
+ Description: |
+
+
+
+ |
+
+
+
+
+ Unknown
+
+
+ |
+ |
+ |
+
+
+
+
+
License Statistics
+
+
Categories
+
+
+
+ Table 2: License categories found in this RAT report.
+
+
+ | Name: |
+ Count: |
+
+
+
+
+ |
+
+
+
+
+ Unknown
+
+
+ |
+ |
+
+
+
+
+
+
Licenses
+
+
+
+ Table 3: Licenses found in this RAT report.
+
+
+ | Name: |
+ Count: |
+
+
+
+
+ |
+
+
+
+
+ Unknown
+
+
+ |
+ |
+
+
+
+
+
+
+
Document types
+
+
+
+ Table 4: Document types found in this RAT report.
+
+
+ | Name: |
+ Count: |
+
+
+
+
+ |
+ |
+
+
+
+
+
+
+
+
+ Files with unapproved licenses
+
+
+
+
+
+ Archives
+
+
+
+
+
+
+
+
+
+
+
+ | |
+
+
+ |
+
+
+
diff --git a/apache-rat-core/src/test/java/org/apache/rat/DefaultsTest.java b/apache-rat-core/src/test/java/org/apache/rat/DefaultsTest.java
index bfd5f31e7..db9edb03f 100644
--- a/apache-rat-core/src/test/java/org/apache/rat/DefaultsTest.java
+++ b/apache-rat-core/src/test/java/org/apache/rat/DefaultsTest.java
@@ -22,6 +22,7 @@
import java.util.Set;
import java.util.TreeSet;
+import org.apache.commons.collections4.set.UnmodifiableSortedSet;
import org.apache.rat.license.ILicense;
import org.apache.rat.license.LicenseSetFactory.LicenseFilter;
import org.junit.jupiter.api.Test;
@@ -36,7 +37,7 @@ public class DefaultsTest {
public void defaultConfigTest() {
Defaults defaults = Defaults.builder().build();
- Set licenses = defaults.getLicenseSetFactory().getLicenses(LicenseFilter.ALL);
+ UnmodifiableSortedSet licenses = defaults.getLicenseSetFactory().getLicenses(LicenseFilter.ALL);
Set names = new TreeSet<>();
licenses.forEach(x -> names.add(x.getLicenseFamily().getFamilyCategory()));
diff --git a/apache-rat-core/src/test/java/org/apache/rat/OptionCollectionParserTest.java b/apache-rat-core/src/test/java/org/apache/rat/OptionCollectionParserTest.java
index f18ee2ab9..2b2411497 100644
--- a/apache-rat-core/src/test/java/org/apache/rat/OptionCollectionParserTest.java
+++ b/apache-rat-core/src/test/java/org/apache/rat/OptionCollectionParserTest.java
@@ -19,7 +19,7 @@
package org.apache.rat;
import org.apache.commons.cli.Option;
-import org.apache.commons.cli.ParseException;
+import org.apache.rat.api.RatException;
import org.apache.rat.commandline.ArgumentContext;
import org.apache.rat.ui.UIOption;
import org.apache.rat.ui.UIOptionCollection;
@@ -28,7 +28,6 @@
import org.junit.jupiter.api.io.CleanupMode;
import org.junit.jupiter.api.io.TempDir;
-import java.io.IOException;
import java.nio.file.Path;
import static org.assertj.core.api.Assertions.assertThat;
@@ -42,7 +41,7 @@ class OptionCollectionParserTest {
private final OptionCollectionParser underTest = new OptionCollectionParser(optionCollection);
@Test
- void parseCommands() throws IOException, ParseException {
+ void parseCommands() throws RatException {
String[] args = {"arg1", "arg2"};
ArgumentContext ctxt = underTest.parseCommands(testPath.toFile(), args);
assertThat(ctxt.getCommandLine().getArgList()).containsExactly(args);
diff --git a/apache-rat-core/src/test/java/org/apache/rat/OptionCollectionTest.java b/apache-rat-core/src/test/java/org/apache/rat/OptionCollectionTest.java
index 238bc69c1..9b2592acf 100644
--- a/apache-rat-core/src/test/java/org/apache/rat/OptionCollectionTest.java
+++ b/apache-rat-core/src/test/java/org/apache/rat/OptionCollectionTest.java
@@ -30,20 +30,20 @@
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
-import org.apache.commons.cli.CommandLine;
-import org.apache.commons.cli.DefaultParser;
+
import org.apache.commons.cli.Option;
import org.apache.commons.cli.ParseException;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.rat.commandline.ArgumentContext;
import org.apache.rat.document.DocumentName;
import org.apache.rat.license.LicenseSetFactory;
-import org.apache.rat.report.IReportable;
+import org.apache.rat.report.Reportable;
import org.apache.rat.test.AbstractConfigurationOptionsProvider;
import org.apache.rat.test.utils.OptionFormatter;
import org.apache.rat.testhelpers.TestingLog;
import org.apache.rat.utils.CasedString;
import org.apache.rat.utils.DefaultLog;
+import org.apache.rat.utils.FileUtils;
import org.apache.rat.utils.Log;
import org.apache.rat.walker.ArchiveWalker;
import org.apache.rat.walker.DirectoryWalker;
@@ -181,6 +181,7 @@ public static Map processTestFunctionAnnotations(Object test
public void testDeprecatedUseLogged() throws IOException {
TestingLog log = new TestingLog();
try {
+ FileUtils.mkDir(testPath.resolve("target").toFile());
DefaultLog.setInstance(log);
String[] args = {"--dir", "target", "-a"};
ReportConfiguration config = OptionCollection.parseCommands(testPath.toFile(), args, o -> fail("Help printed"), true);
@@ -220,8 +221,7 @@ public void testShortenedOptions() throws IOException {
@Test
public void testDefaultConfiguration() throws ParseException {
String[] empty = {};
- CommandLine cl = new DefaultParser().parse(OptionCollection.buildOptions(), empty);
- ArgumentContext context = new ArgumentContext(new File("."), cl);
+ ArgumentContext context = new ArgumentContext(new File("."), OptionCollection.buildOptions(), empty);
ReportConfiguration config = OptionCollection.createConfiguration(context);
ReportConfigurationTest.validateDefault(config);
}
@@ -233,9 +233,9 @@ public void getReportableTest(String fName) throws IOException {
DocumentName.FSInfo fsInfo = new DocumentName.FSInfo(testPath.getFileSystem());
String expected = fsInfo.normalize(base.getAbsolutePath());
ReportConfiguration config = OptionCollection.parseCommands(testPath.toFile(), new String[]{fName}, o -> fail("Help called"), false);
- IReportable reportable = OptionCollection.getReportable(base, config);
+ Reportable reportable = OptionCollection.getReportable(base, config);
assertThat(reportable).as(() -> format("'%s' returned null", fName)).isNotNull();
- assertThat(reportable.getName().getName()).isEqualTo(expected);
+ assertThat(reportable.name().getName()).isEqualTo(expected);
}
@Test
@@ -250,7 +250,7 @@ void getReportable() throws IOException {
reportConfiguration.addExcludedPatterns(List.of(dir2.getName()));
assertThat(OptionCollection.getReportable(dir2, reportConfiguration)).isNull();
- IReportable reportable = OptionCollection.getReportable(dir1, new ReportConfiguration());
+ Reportable reportable = OptionCollection.getReportable(dir1, new ReportConfiguration());
assertThat(reportable).isInstanceOf(DirectoryWalker.class);
File file1 = new File(dir1, "file1");
diff --git a/apache-rat-core/src/test/java/org/apache/rat/OutputTest.java b/apache-rat-core/src/test/java/org/apache/rat/OutputTest.java
new file mode 100644
index 000000000..32602b60e
--- /dev/null
+++ b/apache-rat-core/src/test/java/org/apache/rat/OutputTest.java
@@ -0,0 +1,160 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one *
+ * or more contributor license agreements. See the NOTICE file *
+ * distributed with this work for additional information *
+ * regarding copyright ownership. The ASF licenses this file *
+ * to you under the Apache License, Version 2.0 (the *
+ * "License"); you may not use this file except in compliance *
+ * with the License. You may obtain a copy of the License at *
+ * *
+ * https://www.apache.org/licenses/LICENSE-2.0 *
+ * *
+ * Unless required by applicable law or agreed to in writing, *
+ * software distributed under the License is distributed on an *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
+ * KIND, either express or implied. See the License for the *
+ * specific language governing permissions and limitations *
+ * under the License. *
+ */
+package org.apache.rat;
+
+import org.apache.rat.commandline.StyleSheets;
+import org.apache.rat.config.AddLicenseHeaders;
+import org.apache.rat.config.exclusion.StandardCollection;
+import org.apache.rat.config.results.ClaimValidator;
+import org.apache.rat.document.DocumentName;
+import org.apache.rat.document.DocumentNameMatcher;
+import org.apache.rat.license.LicenseSetFactory;
+import org.apache.rat.report.claim.ClaimStatistic;
+import org.apache.rat.report.claim.ClaimStatisticTest;
+import org.apache.rat.utils.FileUtils;
+import org.apache.rat.utils.StandardXmlFactory;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.w3c.dom.Document;
+import org.xml.sax.SAXException;
+import org.xmlunit.assertj3.XmlAssert;
+
+import javax.xml.transform.TransformerException;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.StringWriter;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+
+class OutputTest {
+
+ static Path tempPath;
+
+ @BeforeAll
+ static void setup() throws IOException {
+ tempPath = Files.createTempDirectory("outputTest").toAbsolutePath();
+ }
+
+ @AfterAll
+ static void teardown() throws IOException {
+ FileUtils.delete(tempPath.toFile());
+ }
+
+ @Test
+ void documentReadingTest() throws IOException, SAXException, TransformerException {
+ Path testPath = tempPath.resolve("documentReading");
+ File testFile = testPath.toFile();
+ FileUtils.mkDir(testFile);
+ DocumentName workingDirectory = DocumentName.builder(testPath.toFile()).setBaseName(testFile).build();
+ Document document;
+ DocumentName documentFile = workingDirectory.resolve("document.xml");
+ try (InputStream inputStream = OutputTest.class.getClassLoader().getResourceAsStream("XmlOutputExamples/elements.xml");) {
+ document = StandardXmlFactory.documentBuilder().parse(inputStream);
+ StandardXmlFactory.writeDocument(document, documentFile.asFile());
+ }
+
+ Reporter.Output.Builder builder = Reporter.Output.builder().document(documentFile.getName(), workingDirectory);
+
+ Reporter.Output output = builder.build();
+ XmlAssert.assertThat(output.getDocument()).and(document)
+ .ignoreWhitespace()
+ .areIdentical();
+ }
+
+ @Test
+ void stasticReadingTest() throws IOException {
+ Path testPath = tempPath.resolve("statisticReading");
+ File testFile = testPath.toFile();
+ FileUtils.mkDir(testFile);
+ DocumentName workingDirectory = DocumentName.builder(testPath.toFile()).setBaseName(testFile).build();
+ DocumentName documentFile = workingDirectory.resolve("statistic.xml");
+
+ ClaimStatistic underTest = new ClaimStatistic();
+ underTest.incLicenseCategoryCount("familyCagegory", 1);
+ underTest.incCounter(ClaimStatistic.Counter.APPROVED, 2);
+ underTest.incCounter(org.apache.rat.api.Document.Type.IGNORED, 3);
+ underTest.incLicenseNameCount("licenseName", 4);
+
+ ClaimStatistic.Serde serde = underTest.serde();
+ StringWriter stringWriter = new StringWriter();
+ serde.serialize(stringWriter);
+ try (FileOutputStream fos = new FileOutputStream(documentFile.asFile())) {
+ fos.write(stringWriter.toString().getBytes(StandardCharsets.UTF_8));
+ }
+
+ Reporter.Output.Builder builder = Reporter.Output.builder().statistic(documentFile.getName(), workingDirectory);
+
+ Reporter.Output output = builder.build();
+ ClaimStatisticTest.assertSame(output.getStatistic(), underTest);
+ }
+
+ @Test
+ void configurationReadingTest() throws IOException {
+ Path testPath = tempPath.resolve("configurationReading");
+ File testFile = testPath.toFile();
+ FileUtils.mkDir(testFile);
+ DocumentName workingDirectory = DocumentName.builder(testPath.toFile()).setBaseName(testFile).build();
+ DocumentName documentFile = workingDirectory.resolve("configuration.xml");
+
+ ReportConfiguration underTest = new ReportConfiguration();
+ underTest.setAddLicenseHeaders(AddLicenseHeaders.FORCED);
+ underTest.listFamilies(LicenseSetFactory.LicenseFilter.APPROVED);
+ underTest.listLicenses(LicenseSetFactory.LicenseFilter.ALL);
+ underTest.setDryRun(true);
+ underTest.setArchiveProcessing(ReportConfiguration.Processing.NOTIFICATION);
+ underTest.setStandardProcessing(ReportConfiguration.Processing.ABSENCE);
+ underTest.setStyleSheet(StyleSheets.MISSING_HEADERS.getStyleSheet());
+ underTest.setOut(new File("/some/file/somewhere"));
+ underTest.setCopyrightMessage("the copyright message");
+ underTest.addSource(new File("/my/file"));
+ underTest.addSource(new ReportConfigurationTest.TestingReportable());
+ underTest.addExcludedPatterns(List.of("pattern/**", "pattern2/**"));
+ underTest.addExcludedCollection(StandardCollection.BAZAAR);
+ underTest.addExcludedCollection(StandardCollection.MISC);
+ underTest.addExcludedFileProcessor(StandardCollection.HIDDEN_FILE);
+ underTest.addExcludedMatcher(DocumentNameMatcher.MATCHES_ALL);
+ underTest.addIncludedPatterns(List.of("**/pattern3", "**/pattern4"));
+ underTest.addIncludedCollection(StandardCollection.ARCH);
+ underTest.addIncludedCollection(StandardCollection.BITKEEPER);
+ underTest.addIncludedMatcher(DocumentNameMatcher.MATCHES_NONE);
+
+ ClaimValidator claimValidator = underTest.getClaimValidator();
+ claimValidator.setMax(ClaimStatistic.Counter.APPROVED, 5);
+ claimValidator.setMin(ClaimStatistic.Counter.APPROVED, 3);
+ claimValidator.setMax(ClaimStatistic.Counter.ARCHIVES, 10);
+ claimValidator.setMin(ClaimStatistic.Counter.BINARIES, 4);
+
+ StringWriter stringWriter = new StringWriter();
+ underTest.serde().serialize(stringWriter);
+
+ try (FileOutputStream fos = new FileOutputStream(documentFile.asFile())) {
+ fos.write(stringWriter.toString().getBytes(StandardCharsets.UTF_8));
+ }
+
+ Reporter.Output.Builder builder = Reporter.Output.builder().configuration(documentFile.getName(), workingDirectory);
+
+ Reporter.Output output = builder.build();
+ ReportConfigurationTest.assertSame(output.getConfiguration(), underTest);
+ }
+}
diff --git a/apache-rat-core/src/test/java/org/apache/rat/ReportConfigurationTest.java b/apache-rat-core/src/test/java/org/apache/rat/ReportConfigurationTest.java
index 69af88b2b..d6c492c15 100644
--- a/apache-rat-core/src/test/java/org/apache/rat/ReportConfigurationTest.java
+++ b/apache-rat-core/src/test/java/org/apache/rat/ReportConfigurationTest.java
@@ -24,6 +24,7 @@
import static org.mockito.Mockito.when;
import java.io.BufferedReader;
+import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
@@ -31,31 +32,41 @@
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
+import java.io.StringWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
+import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.SortedSet;
import java.util.function.Function;
+import java.util.stream.Collectors;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.output.CloseShieldOutputStream;
import org.apache.rat.analysis.IHeaderMatcher;
+import org.apache.rat.api.RatException;
+import org.apache.rat.commandline.StyleSheets;
import org.apache.rat.config.AddLicenseHeaders;
+import org.apache.rat.config.exclusion.ExclusionProcessorTest;
import org.apache.rat.config.exclusion.StandardCollection;
+import org.apache.rat.config.results.ClaimValidator;
import org.apache.rat.configuration.XMLConfigurationReaderTest;
import org.apache.rat.document.DocumentName;
import org.apache.rat.document.DocumentNameMatcher;
import org.apache.rat.license.ILicense;
import org.apache.rat.license.ILicenseFamily;
import org.apache.rat.license.LicenseSetFactory.LicenseFilter;
-import org.apache.rat.report.IReportable;
+import org.apache.rat.report.RatReport;
+import org.apache.rat.report.Reportable;
+import org.apache.rat.report.claim.ClaimStatistic;
import org.apache.rat.testhelpers.TestingLog;
import org.apache.rat.testhelpers.TestingLicense;
import org.apache.rat.testhelpers.TestingMatcher;
import org.apache.rat.utils.DefaultLog;
+import org.apache.rat.utils.Log;
import org.apache.rat.utils.Log.Level;
import org.apache.rat.utils.ReportingSet.Options;
import org.junit.jupiter.api.AfterEach;
@@ -64,6 +75,7 @@
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Mockito;
+
public class ReportConfigurationTest {
private ReportConfiguration underTest;
@@ -456,7 +468,7 @@ public void outputTest() throws IOException {
assertThat(underTest.getWriter()).isNotNull();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
- underTest.setOut(() -> stream);
+ underTest.setOut(new ReportConfiguration.IODescriptor<>("outputTest", () -> stream));
assertThat(underTest.getOutput().get()).isEqualTo(stream);
PrintWriter writer = underTest.getWriter().get();
assertThat(writer).isNotNull();
@@ -468,10 +480,10 @@ public void outputTest() throws IOException {
@Test
public void reportableTest() {
assertThat(underTest.hasSource()).isFalse();
- IReportable reportable = mock(IReportable.class);
+ Reportable reportable = mock(Reportable.class);
underTest.addSource(reportable);
assertThat(underTest.hasSource()).isTrue();
- assertThatThrownBy(() -> underTest.addSource((IReportable)null)).isExactlyInstanceOf(ConfigurationException.class)
+ assertThatThrownBy(() -> underTest.addSource((Reportable)null)).isExactlyInstanceOf(ConfigurationException.class)
.hasMessageContaining("Reportable may not be null.");
}
@@ -480,9 +492,9 @@ public void stylesheetTest() throws IOException, URISyntaxException {
URL url = this.getClass().getResource("ReportConfigurationTestFile");
assertThat(url).isNotNull();
- assertThat(underTest.getStyleSheet()).isNull();
+ assertThat(underTest.getStyleSheetDescriptor()).isNull();
InputStream stream = mock(InputStream.class);
- underTest.setStyleSheet(() -> stream);
+ underTest.setStyleSheet(new ReportConfiguration.IODescriptor<>("stylesheetTest", () -> stream));
assertThat(underTest.getStyleSheet().get()).isEqualTo(stream);
File file = mock(File.class);
@@ -515,32 +527,37 @@ public void testFlags() {
@Test
public void testValidate() {
- final StringBuilder sb = new StringBuilder();
+ TestingLog testLog = new TestingLog();
+ Log oldLog = DefaultLog.getInstance();
+ try {
+ DefaultLog.setInstance(testLog);
+
String msg = "At least one source must be specified";
- assertThatThrownBy(() -> underTest.validate(sb::append)).isExactlyInstanceOf(ConfigurationException.class)
+ assertThatThrownBy(underTest::validate).isExactlyInstanceOf(ConfigurationException.class)
.hasMessageContaining(msg);
- assertThat(sb.toString()).isEqualTo(msg);
+ testLog.assertContains(msg);
+ testLog.clear();
- sb.setLength(0);
- msg = "You must specify at least one license";
- underTest.addSource(mock(IReportable.class));
+ msg = "At least one license must be defined";
+ underTest.addSource(mock(Reportable.class));
- assertThatThrownBy(() -> underTest.validate(sb::append)).isExactlyInstanceOf(ConfigurationException.class)
+ assertThatThrownBy(underTest::validate).isExactlyInstanceOf(ConfigurationException.class)
.hasMessageContaining(msg);
- assertThat(sb.toString()).isEqualTo(msg);
+ testLog.assertContains(msg);
- sb.setLength(0);
underTest.addLicense(testingLicense("valid", "Validation testing license"));
- underTest.validate(sb::append);
- assertThat(sb.length()).isEqualTo(0);
+ underTest.validate();
+ } finally {
+ DefaultLog.setInstance(oldLog);
+ }
}
@Test
public void testSetOut() throws IOException {
ReportConfiguration config = new ReportConfiguration();
try (OutputStreamInterceptor osi = new OutputStreamInterceptor()) {
- config.setOut(() -> osi);
+ config.setOut(new ReportConfiguration.IODescriptor<>("testSetOut", () -> osi));
assertThat(osi.closeCount).isEqualTo(0);
try (OutputStream os = config.getOutput().get()) {
assertThat(os).isNotNull();
@@ -563,16 +580,18 @@ public void logFamilyCollisionTest() {
// verify default collision logs WARNING
underTest.addFamily(ILicenseFamily.builder().setLicenseFamilyCategory("CAT").setLicenseFamilyName("name2"));
- assertThat(log.getCaptured().contains("WARN")).as("default value not WARN").isTrue();
- assertThat(log.getCaptured().contains("CAT")).as("'CAT' not found").isTrue();
+ assertThat(log.getCaptured()).contains("WARN").contains("CAT");
// verify level setting works.
for (Level l : Level.values()) {
log.clear();
underTest.logFamilyCollisions(l);
underTest.addFamily(ILicenseFamily.builder().setLicenseFamilyCategory("CAT").setLicenseFamilyName("name2"));
- assertThat(log.getCaptured().contains("CAT")).as("'CAT' not found").isTrue();
- assertThat(log.getCaptured().contains(l.name())).as("logging not set to "+l).isTrue();
+ if (DefaultLog.getInstance().isEnabled(l)) {
+ assertThat(log.getCaptured()).contains("CAT").contains(l.name());
+ } else {
+ assertThat(log.getCaptured()).doesNotContain("CAT").doesNotContain(l.name());
+ }
}
}
@@ -662,51 +681,52 @@ public void licenseDuplicateOptionsTest() {
.isExactlyInstanceOf(IllegalArgumentException.class);
}
- /**
- * Validates that the configuration contains the default approved licenses.
- * @param config The configuration to test.
- */
- public static void validateDefaultApprovedLicenses(ReportConfiguration config) {
- validateDefaultApprovedLicenses(config, 0);
- }
/**
* Validates that the configuration contains the default approved licenses.
* @param config The configuration to test.
*/
- public static void validateDefaultApprovedLicenses(ReportConfiguration config, int additionalIdCount) {
- assertThat(config.getLicenseCategories(LicenseFilter.APPROVED)).hasSize(XMLConfigurationReaderTest.APPROVED_IDS.length + additionalIdCount);
- for (String s : XMLConfigurationReaderTest.APPROVED_IDS) {
- assertThat(config.getLicenseCategories(LicenseFilter.APPROVED)).contains(ILicenseFamily.makeCategory(s));
+ public static void validateDefaultApprovedLicenses(ReportConfiguration config, String... additionalIds) {
+ validateLicenses(config, Arrays.asList(additionalIds), LicenseFilter.APPROVED, XMLConfigurationReaderTest.APPROVED_LICENSES);
}
+
+ /**
+ * Validates that the configuration contains all the default licenses along with any addiitonal licenses
+ * @param config the configuration to test.
+ * @param additionalLicenses Additional licence IDs that are expected.
+ */
+ public static void validateDefaultLicenses(ReportConfiguration config, String...additionalLicenses) {
+ validateLicenses(config, Arrays.asList(additionalLicenses), LicenseFilter.ALL, XMLConfigurationReaderTest.EXPECTED_LICENSES);
+ }
+
+ private static void validateLicenses(ReportConfiguration config, List additionalIds, LicenseFilter filter, String[] approvedIds) {
+ List expected = new ArrayList<>(Arrays.asList(approvedIds));
+ expected.addAll(additionalIds);
+ assertThat(config.getLicenses(filter).stream().map(ILicense::getId).collect(Collectors.toSet())).containsExactlyInAnyOrderElementsOf(expected);
}
+
/**
* Validates that the configuration contains the default license families.
* @param config the configuration to test.
*/
public static void validateDefaultLicenseFamilies(ReportConfiguration config, String...additionalIds) {
- assertThat(config.getLicenseFamilies(LicenseFilter.ALL)).hasSize(XMLConfigurationReaderTest.EXPECTED_IDS.length + additionalIds.length);
- List expected = new ArrayList<>();
- expected.addAll(Arrays.asList(XMLConfigurationReaderTest.EXPECTED_IDS));
- expected.addAll(Arrays.asList(additionalIds));
- for (ILicenseFamily family : config.getLicenseFamilies(LicenseFilter.ALL)) {
- assertThat(expected).contains(family.getFamilyCategory().trim());
- }
+ validateLicenseFamilies(config, Arrays.asList(additionalIds), LicenseFilter.ALL, XMLConfigurationReaderTest.EXPECTED_IDS);
}
/**
- * Validates that the configuration contains the default licenses.
+ * Validates that the configuration contains the default license families.
* @param config the configuration to test.
*/
- public static void validateDefaultLicenses(ReportConfiguration config, String...additionalLicenses) {
- assertThat(config.getLicenses(LicenseFilter.ALL)).hasSize(XMLConfigurationReaderTest.EXPECTED_LICENSES.length + additionalLicenses.length);
- List expected = new ArrayList<>();
- expected.addAll(Arrays.asList(XMLConfigurationReaderTest.EXPECTED_LICENSES));
- expected.addAll(Arrays.asList(additionalLicenses));
- for (ILicense license : config.getLicenses(LicenseFilter.ALL)) {
- assertThat(expected).contains(license.getId());
+ public static void validateDefaultApprovedLicenseFamilies(ReportConfiguration config, String...additionalIds) {
+ validateLicenseFamilies(config, Arrays.asList(additionalIds), LicenseFilter.APPROVED, XMLConfigurationReaderTest.APPROVED_IDS);
}
+
+ private static void validateLicenseFamilies(ReportConfiguration config, List additionalIds, LicenseFilter filter, String[] approvedIds) {
+ List expected = new ArrayList<>(Arrays.asList(approvedIds));
+ expected.addAll(additionalIds);
+ assertThat(config.getLicenseFamilies(filter).stream().map(lf -> lf.getFamilyCategory().trim())
+ .collect(Collectors.toSet())).containsExactlyInAnyOrderElementsOf(expected);
}
/**
@@ -719,9 +739,68 @@ public static void validateDefault(ReportConfiguration config) {
assertThat(config.getCopyrightMessage()).isNull();
assertThat(config.getStyleSheet()).withFailMessage("Stylesheet should not be null").isNotNull();
- validateDefaultApprovedLicenses(config);
validateDefaultLicenseFamilies(config);
+ validateDefaultApprovedLicenseFamilies(config);
validateDefaultLicenses(config);
+ validateDefaultApprovedLicenses(config);
+ }
+
+ public static void assertSame(ReportConfiguration actual, ReportConfiguration expected) {
+ assertThat(actual.isAddingLicenses()).isEqualTo(expected.isAddingLicenses());
+ assertThat(actual.isAddingLicensesForced()).isEqualTo(expected.isAddingLicensesForced());
+ assertThat(actual.listFamilies()).isEqualTo(expected.listFamilies());
+ assertThat(actual.listLicenses()).isEqualTo(expected.listLicenses());
+ assertThat(actual.isDryRun()).isEqualTo(expected.isDryRun());
+ assertThat(actual.getArchiveProcessing()).isEqualTo(expected.getArchiveProcessing());
+ assertThat(actual.getStandardProcessing()).isEqualTo(expected.getStandardProcessing());
+ assertThat(actual.getStyleSheetDescriptor().name()).isEqualTo(expected.getStyleSheetDescriptor().name());
+ assertThat(actual.getOutputDescriptor().name()).isEqualTo(expected.getOutputDescriptor().name());
+
+ assertThat(actual.getCopyrightMessage()).isEqualTo(expected.getCopyrightMessage());
+
+ assertThat(actual.sources()).containsExactlyElementsOf(expected.sources());
+ assertThat(actual.reportables()).containsExactlyElementsOf(expected.reportables().toList());
+ ExclusionProcessorTest.assertSame(actual.getExclusionProcessor(), expected.getExclusionProcessor());
+
+ }
+ @Test
+ void serdeTest() throws IOException {
+ underTest.setAddLicenseHeaders(AddLicenseHeaders.FORCED);
+ underTest.listFamilies(LicenseFilter.APPROVED);
+ underTest.listLicenses(LicenseFilter.ALL);
+ underTest.setDryRun(true);
+ underTest.setArchiveProcessing(ReportConfiguration.Processing.NOTIFICATION);
+ underTest.setStandardProcessing(ReportConfiguration.Processing.ABSENCE);
+ underTest.setStyleSheet(StyleSheets.MISSING_HEADERS.getStyleSheet());
+ underTest.setOut(new File("/some/file/somewhere"));
+ underTest.setCopyrightMessage("the copyright message");
+ underTest.addSource(new File("/my/file"));
+ underTest.addSource(new TestingReportable());
+
+ underTest.addExcludedPatterns(List.of("pattern/**", "pattern2/**"));
+ underTest.addExcludedCollection(StandardCollection.BAZAAR);
+ underTest.addExcludedCollection(StandardCollection.MISC);
+ underTest.addExcludedFileProcessor(StandardCollection.HIDDEN_FILE);
+ underTest.addExcludedMatcher(DocumentNameMatcher.MATCHES_ALL);
+ underTest.addIncludedPatterns(List.of("**/pattern3", "**/pattern4"));
+ underTest.addIncludedCollection(StandardCollection.ARCH);
+ underTest.addIncludedCollection(StandardCollection.BITKEEPER);
+ underTest.addIncludedMatcher(DocumentNameMatcher.MATCHES_NONE);
+
+ ClaimValidator claimValidator = underTest.getClaimValidator();
+
+ claimValidator.setMax(ClaimStatistic.Counter.APPROVED, 5);
+ claimValidator.setMin(ClaimStatistic.Counter.APPROVED, 3);
+ claimValidator.setMax(ClaimStatistic.Counter.ARCHIVES, 10);
+ claimValidator.setMin(ClaimStatistic.Counter.BINARIES, 4);
+
+ StringWriter stringWriter = new StringWriter();
+ underTest.serde().serialize(stringWriter);
+
+ ReportConfiguration actual = new ReportConfiguration();
+ actual.serde().deserialize(() -> new ByteArrayInputStream(stringWriter.toString().getBytes(StandardCharsets.UTF_8)),
+ DocumentName.builder(new File("/rootDir")).build());
+ assertSame(actual, underTest);
}
/**
@@ -734,10 +813,26 @@ static class OutputStreamInterceptor extends OutputStream {
public void write(int arg0) {
throw new UnsupportedOperationException();
}
-
+
@Override
public void close() {
++closeCount;
}
}
+
+ /**
+ * A reportable that only reports its name. Does no actual work.
+ */
+ static class TestingReportable implements Reportable {
+
+ @Override
+ public void run(RatReport report) throws RatException {
+ // does nothing
+ }
+
+ @Override
+ public DocumentName name() {
+ return DocumentName.builder().setBaseName("").setName("TestingReportable").build();
+ }
+ }
}
diff --git a/apache-rat-core/src/test/java/org/apache/rat/ReporterOptionsProvider.java b/apache-rat-core/src/test/java/org/apache/rat/ReporterOptionsProvider.java
index 0ef6f019c..67ad8fd7b 100644
--- a/apache-rat-core/src/test/java/org/apache/rat/ReporterOptionsProvider.java
+++ b/apache-rat-core/src/test/java/org/apache/rat/ReporterOptionsProvider.java
@@ -20,7 +20,6 @@
import java.io.ByteArrayOutputStream;
import java.io.File;
-import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
@@ -54,7 +53,7 @@
import org.apache.rat.test.AbstractOptionsProvider;
import org.apache.rat.test.utils.OptionFormatter;
import org.apache.rat.test.utils.Resources;
-import org.apache.rat.testhelpers.FileUtils;
+import org.apache.rat.utils.FileUtils;
import org.apache.rat.testhelpers.TestingLog;
import org.apache.rat.testhelpers.TextUtils;
import org.apache.rat.testhelpers.XmlUtils;
@@ -65,6 +64,7 @@
import static org.apache.rat.commandline.Arg.HELP_LICENSES;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Fail.fail;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
@@ -114,18 +114,26 @@ protected final ReportConfiguration generateConfig(List>
return config;
}
- private File configureRatDir(Option option) {
- configureSourceDir(option);
- File result = new File(sourceDir, ".rat");
- FileUtils.mkDir(result);
- return result;
- }
-
+ /**
+ * Creates the srcDir.,.
+ * @param option the name for the srcDir.
+ */
private void configureSourceDir(Option option) {
sourceDir = new File(baseDir, OptionFormatter.getName(option));
FileUtils.mkDir(sourceDir);
}
+ /**
+ * Creates the option/.rat directory
+ * @param option the name for the sourceDirectory.
+ */
+ private File configureRatDir(Option option) {
+ configureSourceDir(option);
+ File ratDir = new File(sourceDir, ".rat");
+ FileUtils.mkDir(ratDir);
+ return ratDir;
+ }
+
private void validateNoArgSetup() throws IOException, RatException {
// verify that without args the report is ok.
TestingLog log = new TestingLog();
@@ -133,9 +141,9 @@ private void validateNoArgSetup() throws IOException, RatException {
try {
ReportConfiguration config = generateConfig(Collections.emptyList());
Reporter reporter = new Reporter(config);
- ClaimStatistic claimStatistic = reporter.execute();
+ Reporter.Output output = reporter.execute();
ClaimValidator validator = config.getClaimValidator();
- assertThat(validator.listIssues(claimStatistic)).isEmpty();
+ assertThat(validator.listIssues(output.getStatistic())).isEmpty();
} finally {
DefaultLog.setInstance(null);
}
@@ -160,8 +168,8 @@ private void editLicenseTest(final Option option) {
FileUtils.delete(resultFile);
Reporter reporter = new Reporter(config);
- ClaimStatistic claimStatistic = reporter.execute();
- assertThat(claimStatistic).isNotNull();
+ Reporter.Output output = reporter.execute();
+ assertThat(output.getStatistic()).isNotNull();
String contents = String.join("\n", IOUtils.readLines(new FileReader(testFile)));
assertThat(contents).isEqualTo("class NoLicense {}");
assertThat(resultFile).exists();
@@ -214,9 +222,9 @@ private void execLicensesDeniedTest(final Option option, final String[] args) {
ReportConfiguration config = generateConfig(ImmutablePair.of(option, args));
Reporter reporter = new Reporter(config);
- ClaimStatistic claimStatistic = reporter.execute();
+ Reporter.Output output = reporter.execute();
ClaimValidator validator = config.getClaimValidator();
- assertThat(validator.listIssues(claimStatistic)).containsExactly("UNAPPROVED");
+ assertThat(validator.listIssues(output.getStatistic())).containsExactly("UNAPPROVED");
});
}
@@ -228,8 +236,7 @@ protected void licensesDeniedTest() {
@OptionCollectionTest.TestFunction
protected void licensesDeniedFileTest() {
Option option = Arg.LICENSES_DENIED_FILE.find("licenses-denied-file");
- File ratDir = configureRatDir(option);
- File outputFile = FileUtils.writeFile(ratDir, "licensesDenied.txt", Collections.singletonList("ILLUMOS"));
+ File outputFile = FileUtils.writeFile(configureRatDir(option), "licensesDenied.txt", Collections.singletonList("ILLUMOS"));
execLicensesDeniedTest(option, new String[]{outputFile.getAbsolutePath()});
}
@@ -240,17 +247,11 @@ private void noDefaultsTest(final Option option) {
"*/\n\n", "class Test {}\n"));
validateNoArgSetup();
-
ReportConfiguration config = generateConfig(ImmutablePair.of(option, null));
Reporter reporter = new Reporter(config);
- try {
- reporter.execute();
- fail("Should have thrown exception");
- } catch (RatException e) {
- ClaimStatistic claimStatistic = reporter.getClaimsStatistic();
- ClaimValidator validator = config.getClaimValidator();
- assertThat(validator.listIssues(claimStatistic)).containsExactlyInAnyOrder("DOCUMENT_TYPES", "LICENSE_CATEGORIES", "LICENSE_NAMES", "STANDARDS");
- }
+ assertThatThrownBy(reporter::execute)
+ .isInstanceOf(RatException.class)
+ .hasMessageContaining("At least one license must be defined");
});
}
@@ -276,16 +277,16 @@ protected void counterMaxTest() {
ReportConfiguration config = generateConfig(Collections.emptyList());
Reporter reporter = new Reporter(config);
- ClaimStatistic claimStatistic = reporter.execute();
+ Reporter.Output output = reporter.execute();
ClaimValidator validator = config.getClaimValidator();
- assertThat(validator.listIssues(claimStatistic)).containsExactly("UNAPPROVED");
+ assertThat(validator.listIssues(output.getStatistic())).containsExactly("UNAPPROVED");
arg[0] = "Unapproved:1";
config = generateConfig(ImmutablePair.of(option, arg));
reporter = new Reporter(config);
- claimStatistic = reporter.execute();
+ output = reporter.execute();
validator = config.getClaimValidator();
- assertThat(validator.listIssues(claimStatistic)).isEmpty();
+ assertThat(validator.listIssues(output.getStatistic())).isEmpty();
});
}
@@ -301,21 +302,26 @@ protected void counterMinTest() {
ReportConfiguration config = generateConfig(Collections.emptyList());
Reporter reporter = new Reporter(config);
- ClaimStatistic claimStatistic = reporter.execute();
+ Reporter.Output output = reporter.execute();
ClaimValidator validator = config.getClaimValidator();
- assertThat(validator.listIssues(claimStatistic)).containsExactly("UNAPPROVED");
+ assertThat(validator.listIssues(output.getStatistic())).containsExactly("UNAPPROVED");
arg[0] = "Unapproved:1";
config = generateConfig(ImmutablePair.of(option, arg));
reporter = new Reporter(config);
- claimStatistic = reporter.execute();
+ output = reporter.execute();
validator = config.getClaimValidator();
- assertThat(validator.listIssues(claimStatistic)).isEmpty();
+ assertThat(validator.listIssues(output.getStatistic())).isEmpty();
});
}
- // exclude tests
- private void execExcludeTest(final Option option, final String[] args, final boolean addIgnored) {
+ /**
+ * Runs the exclude tests.
+ * @param option The exclude option to run.
+ * @param args the arguments for the command line.
+ * @param includesRatDir @{code true} if the .rat directory was created.
+ */
+ private void execExcludeTest(final Option option, final String[] args, final boolean includesRatDir) {
String[] notExcluded = {"notbaz", "well._afile"};
String[] excluded = {"some.foo", "B.bar", "justbaz"};
@@ -329,22 +335,21 @@ private void execExcludeTest(final Option option, final String[] args, final boo
ReportConfiguration config = generateConfig(Collections.emptyList());
Reporter reporter = new Reporter(config);
- ClaimStatistic claimStatistic = reporter.execute();
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(5);
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(addIgnored ? 1 : 0);
+ Reporter.Output output = reporter.execute();
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(5);
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(includesRatDir ? 1 : 0);
// filter out source
config = generateConfig(ImmutablePair.of(option, args));
reporter = new Reporter(config);
- claimStatistic = reporter.execute();
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(2);
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(addIgnored ? 4 : 3);
+ output = reporter.execute();
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(2);
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(includesRatDir ? 4 : 3);
});
}
private void excludeFileTest(final Option option) {
- File ratDir = configureRatDir(option);
- File outputFile = FileUtils.writeFile(ratDir, "exclude.txt", Arrays.asList(EXCLUDE_ARGS));
+ File outputFile = FileUtils.writeFile(configureRatDir(option), "exclude.txt", Arrays.asList(EXCLUDE_ARGS));
execExcludeTest(option, new String[]{outputFile.getAbsolutePath()}, true);
}
@@ -381,16 +386,16 @@ protected void inputExcludeSizeTest() {
ReportConfiguration config = generateConfig(Collections.emptyList());
Reporter reporter = new Reporter(config);
- ClaimStatistic claimStatistic = reporter.execute();
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(3);
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(0);
+ Reporter.Output output = reporter.execute();
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(3);
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.IGNORED)).isZero();
// filter out source
config = generateConfig(ImmutablePair.of(option, args));
reporter = new Reporter(config);
- claimStatistic = reporter.execute();
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(2);
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(1);
+ output = reporter.execute();
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(2);
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(1);
});
}
@@ -415,15 +420,15 @@ protected void inputExcludeStdTest() {
ReportConfiguration config = generateConfig(Collections.emptyList());
Reporter reporter = new Reporter(config);
- ClaimStatistic claimStatistic = reporter.execute();
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(5);
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(4);
+ Reporter.Output output = reporter.execute();
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(5);
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(4);
config = generateConfig(ImmutablePair.of(option, args));
reporter = new Reporter(config);
- claimStatistic = reporter.execute();
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(4);
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(5);
+ output = reporter.execute();
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(4);
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(5);
});
}
@@ -471,21 +476,26 @@ protected void inputExcludeParsedScmTest() {
ReportConfiguration config = generateConfig(Collections.emptyList());
Reporter reporter = new Reporter(config);
- ClaimStatistic claimStatistic = reporter.execute();
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(11);
+ Reporter.Output output = reporter.execute();
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(11);
// .gitignore is ignored by default as it is hidden but not counted
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(0);
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.IGNORED)).isZero();
config = generateConfig(ImmutablePair.of(option, args));
reporter = new Reporter(config);
- claimStatistic = reporter.execute();
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(3);
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(8);
+ output = reporter.execute();
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(3);
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(8);
});
}
- // include tests
- private void execIncludeTest(final Option option, final String[] args, boolean addIgnored) {
+ /**
+ * Runs the include tests.
+ * @param option The include option to run.
+ * @param args the arguments for the command line.
+ * @param includesRatDir @{code true} if the .rat directory was created.
+ */
+ private void execIncludeTest(final Option option, final String[] args, final boolean includesRatDir) {
Option excludeOption = Arg.EXCLUDE.option();
String[] notExcluded = {"B.bar", "justbaz", "notbaz"};
String[] excluded = {"some.foo"};
@@ -499,31 +509,31 @@ private void execIncludeTest(final Option option, final String[] args, boolean a
ReportConfiguration config = generateConfig(Collections.emptyList());
Reporter reporter = new Reporter(config);
- ClaimStatistic claimStatistic = reporter.execute();
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(4);
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(addIgnored ? 1 : 0);
+ Reporter.Output output = reporter.execute();
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(4);
+
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(includesRatDir ? 1 : 0);
// verify exclude removes most files.
config = generateConfig(ImmutablePair.of(excludeOption, EXCLUDE_ARGS));
reporter = new Reporter(config);
- claimStatistic = reporter.execute();
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(1);
+ output = reporter.execute();
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(1);
// .gitignore is ignored by default as it is hidden but not counted
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(addIgnored ? 4 : 3);
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(includesRatDir ? 4 : 3);
// verify include pust them back
config = generateConfig(ImmutablePair.of(option, args), ImmutablePair.of(excludeOption, EXCLUDE_ARGS));
reporter = new Reporter(config);
- claimStatistic = reporter.execute();
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(3);
+ output = reporter.execute();
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(3);
// .gitignore is ignored by default as it is hidden but not counted
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(addIgnored ? 2 : 1);
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(includesRatDir ? 2 : 1 );
});
}
private void includeFileTest(final Option option) {
- File ratDir = configureRatDir(option);
- File outputFile = FileUtils.writeFile(ratDir, "include.txt", Arrays.asList(INCLUDE_ARGS));
+ File outputFile = FileUtils.writeFile(configureRatDir(option), "include.txt", Arrays.asList(INCLUDE_ARGS));
execIncludeTest(option, new String[]{outputFile.getAbsolutePath()}, true);
}
@@ -569,15 +579,15 @@ protected void inputIncludeStdTest() {
ReportConfiguration config = generateConfig(Collections.singletonList(excludes));
Reporter reporter = new Reporter(config);
- ClaimStatistic claimStatistic = reporter.execute();
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(3);
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(5);
+ Reporter.Output output = reporter.execute();
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(3);
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(5);
config = generateConfig(excludes, ImmutablePair.of(option, args));
reporter = new Reporter(config);
- claimStatistic = reporter.execute();
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(7);
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(1);
+ output = reporter.execute();
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(7);
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(1);
});
}
@@ -594,15 +604,15 @@ protected void inputSourceTest() {
ReportConfiguration config = generateConfig();
Reporter reporter = new Reporter(config);
- ClaimStatistic claimStatistic = reporter.execute();
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(3);
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(0);
+ Reporter.Output output = reporter.execute();
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(3);
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.IGNORED)).isZero();
config = generateConfig(ImmutablePair.of(option, new String[]{inputFile.getAbsolutePath()}));
reporter = new Reporter(config);
- claimStatistic = reporter.execute();
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(1);
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(0);
+ output = reporter.execute();
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(1);
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.IGNORED)).isZero();
});
}
@@ -624,18 +634,18 @@ private void execLicenseFamiliesApprovedTest(final Option option, final String[]
ReportConfiguration config = addCatzLicense(generateConfig());
Reporter reporter = new Reporter(config);
- ClaimStatistic claimStatistic = reporter.execute();
+ Reporter.Output output = reporter.execute();
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(1);
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.APPROVED)).isEqualTo(0);
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.UNAPPROVED)).isEqualTo(1);
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(1);
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.APPROVED)).isZero();
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.UNAPPROVED)).isEqualTo(1);
config = addCatzLicense(generateConfig(arg1));
reporter = new Reporter(config);
- claimStatistic = reporter.execute();
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(1);
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.APPROVED)).isEqualTo(1);
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.UNAPPROVED)).isEqualTo(0);
+ output = reporter.execute();
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(1);
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.APPROVED)).isEqualTo(1);
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.UNAPPROVED)).isZero();
});
}
@@ -664,17 +674,17 @@ private void execLicenseFamiliesDeniedTest(final Option option, final String[] a
ReportConfiguration config = generateConfig();
Reporter reporter = new Reporter(config);
- ClaimStatistic claimStatistic = reporter.execute();
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(1);
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.APPROVED)).isEqualTo(1);
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.UNAPPROVED)).isEqualTo(0);
+ Reporter.Output output = reporter.execute();
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(1);
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.APPROVED)).isEqualTo(1);
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.UNAPPROVED)).isZero();
config = generateConfig(arg1);
reporter = new Reporter(config);
- claimStatistic = reporter.execute();
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(1);
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.APPROVED)).isEqualTo(0);
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.UNAPPROVED)).isEqualTo(1);
+ output = reporter.execute();
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(1);
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.APPROVED)).isZero();
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.UNAPPROVED)).isEqualTo(1);
});
}
@@ -705,26 +715,26 @@ private void configTest(final Option option) {
ReportConfiguration config = generateConfig();
Reporter reporter = new Reporter(config);
- ClaimStatistic claimStatistic = reporter.execute();
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(2);
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.APPROVED)).isEqualTo(1);
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.UNAPPROVED)).isEqualTo(1);
+ Reporter.Output output = reporter.execute();
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(2);
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.APPROVED)).isEqualTo(1);
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.UNAPPROVED)).isEqualTo(1);
config = generateConfig(arg1);
reporter = new Reporter(config);
- claimStatistic = reporter.execute();
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(2);
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.APPROVED)).isEqualTo(2);
- assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.UNAPPROVED)).isEqualTo(0);
+ output = reporter.execute();
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(2);
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.APPROVED)).isEqualTo(2);
+ assertThat(output.getStatistic().getCounter(ClaimStatistic.Counter.UNAPPROVED)).isZero();
Pair