1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package info.magnolia.resourceloader.classpath;
35
36 import info.magnolia.resourceloader.AbstractResource;
37 import info.magnolia.resourceloader.Resource;
38
39 import java.util.ArrayList;
40 import java.util.HashSet;
41 import java.util.List;
42 import java.util.Set;
43
44 import lombok.EqualsAndHashCode;
45
46
47
48
49
50 @EqualsAndHashCode(callSuper = true, exclude = { "parent", "children" })
51 public class ClasspathResource extends AbstractResource {
52
53 private final String realPath;
54 private final boolean isFile;
55
56 private ClasspathResource parent;
57 private final Set<ClasspathResource> children;
58
59 ClasspathResource(ClasspathResourceOrigin origin, String path, boolean isFile) {
60 super(origin);
61 if (!path.startsWith("/")) {
62 throw new IllegalArgumentException("Path does not start with /: " + path);
63 }
64 this.realPath = path;
65 this.isFile = isFile;
66 this.children = !isFile ? new HashSet<ClasspathResource>() : null;
67 }
68
69 String getRealPath() {
70 return realPath;
71 }
72
73 @Override
74 public boolean isFile() {
75 return isFile;
76 }
77
78 @Override
79 public boolean isDirectory() {
80 return !isFile;
81 }
82
83
84
85
86 @Override
87 public ClasspathResource getParent() {
88 return parent;
89 }
90
91 void setParent(ClasspathResource parent) {
92 if (this.equals(parent)) {
93 throw new IllegalStateException("Cannot set self ClasspathResource as parent.");
94 }
95 if (this.parent != null) {
96 throw new IllegalStateException("Parent is already set for " + this);
97 }
98 this.parent = parent;
99 parent.addChild(this);
100 }
101
102
103
104
105 @Override
106 public List<Resource> listChildren() {
107 if (isFile) {
108 throw new IllegalStateException(getPath() + " is not a directory.");
109 }
110 return new ArrayList<Resource>(children);
111 }
112
113 public void setChildren(List<ClasspathResource> children) {
114 if (children.contains(this)) {
115 throw new IllegalStateException("Cannot add self ClasspathResource to children.");
116 }
117 this.children.clear();
118 this.children.addAll(children);
119 }
120
121 public void addChild(ClasspathResource child) {
122 if (this.equals(child)) {
123 throw new IllegalStateException("Cannot add self ClasspathResource to children.");
124 }
125 children.add(child);
126 }
127 }