1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.rat.walker;
21
22 import java.io.BufferedInputStream;
23 import java.io.ByteArrayOutputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.List;
29
30 import org.apache.commons.compress.archivers.ArchiveEntry;
31 import org.apache.commons.compress.archivers.ArchiveException;
32 import org.apache.commons.compress.archivers.ArchiveInputStream;
33 import org.apache.commons.compress.archivers.ArchiveStreamFactory;
34 import org.apache.commons.io.IOUtils;
35 import org.apache.rat.api.Document;
36 import org.apache.rat.api.RatException;
37 import org.apache.rat.document.ArchiveEntryDocument;
38 import org.apache.rat.document.ArchiveEntryName;
39 import org.apache.rat.document.DocumentName;
40 import org.apache.rat.report.RatReport;
41 import org.apache.rat.utils.DefaultLog;
42
43 import static java.lang.String.format;
44
45
46
47
48 public class ArchiveWalker extends Walker {
49
50
51
52
53
54 public ArchiveWalker(final Document document) {
55 super(document);
56 }
57
58
59
60
61
62
63
64
65 public void run(final RatReport report) throws RatException {
66 for (Document document : getDocuments()) {
67 report.report(document);
68 }
69 }
70
71
72
73
74
75
76 private InputStream createInputStream() throws IOException {
77 return new BufferedInputStream(getDocument().inputStream());
78 }
79
80
81
82
83
84 public Collection<Document> getDocuments() throws RatException {
85 List<Document> result = new ArrayList<>();
86 try (ArchiveInputStream<? extends ArchiveEntry> input = new ArchiveStreamFactory().createArchiveInputStream(createInputStream())) {
87 ArchiveEntry entry;
88 while ((entry = input.getNextEntry()) != null) {
89 if (!entry.isDirectory() && input.canReadEntryData(entry)) {
90 DocumentName innerName = DocumentName.builder().setName(entry.getName())
91 .setBaseName(".").build();
92 if (this.getDocument().getNameMatcher().matches(innerName)) {
93 ByteArrayOutputStream baos = new ByteArrayOutputStream();
94 IOUtils.copy(input, baos);
95 ArchiveEntryName entryName = new ArchiveEntryName(getDocument().getName(), entry.getName());
96 result.add(new ArchiveEntryDocument(entryName, baos.toByteArray(), getDocument().getNameMatcher()));
97 }
98 }
99 }
100 } catch (ArchiveException e) {
101 DefaultLog.getInstance().warn(format("Unable to process %s: %s", getDocument().getName(), e.getMessage()));
102 } catch (IOException e) {
103 throw RatException.makeRatException(e);
104 }
105 return result;
106 }
107 }