Skip to content

Commit

Permalink
#419 throw exception including path in ClasspathRuleSource if an inva…
Browse files Browse the repository at this point in the history
…lid resource is referenced
  • Loading branch information
yaseno2186 committed Jul 12, 2024
1 parent 8987da7 commit 86eebb7
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,24 +17,27 @@ public class ClasspathRuleSource extends RuleSource {
public static final String RULE_RESOURCE_PATH = "META-INF/jqassistant-rules";

private final ClassLoader classLoader;
private final String resource;
private final String relativePath;
private final URL resource;

public ClasspathRuleSource(ClassLoader classLoader, String relativePath) {
this.classLoader = classLoader;
this.relativePath = relativePath;
this.resource = RULE_RESOURCE_PATH + "/" + relativePath;

String classpathResource = RULE_RESOURCE_PATH + "/" + relativePath;
this.resource = getClassLoader().getResource(classpathResource);
if (this.resource == null) {
throw new IllegalArgumentException("Cannot find rule resource in classpath: " + classpathResource);
}
}

@Override
public String getId() {
return resource;
return resource.toString();
}

@Override
public URL getURL() {
return getClassLoader().getResource(resource);
return resource;
}

@Override
Expand All @@ -49,12 +52,7 @@ public String getRelativePath() {

@Override
public InputStream getInputStream() throws IOException {
ClassLoader currentClassloader = getClassLoader();
InputStream stream = currentClassloader.getResourceAsStream(resource);
if (stream == null) {
throw new IOException("Cannot load resource from " + resource);
}
return stream;
return resource.openStream();
}

private ClassLoader getClassLoader() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,24 @@
import java.util.List;
import java.util.stream.Stream;

import org.junit.jupiter.api.Test;

import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;

class ClasspathRuleSourceTest extends AbstractRuleSourceTest {

@Override
protected List<RuleSource> getRuleSources() {
return Stream.of("rules.xml", "index.adoc", "readme.md", "subdirectory/rules.xml")
.map(relativePath -> new ClasspathRuleSource(ClasspathRuleSourceTest.class.getClassLoader(), relativePath)).collect(toList());
.map(relativePath -> new ClasspathRuleSource(ClasspathRuleSourceTest.class.getClassLoader(), relativePath))
.collect(toList());
}

@Test
void nonExistingResource() {
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> new ClasspathRuleSource(this.getClass()
.getClassLoader(), "non-existing.xml"));
}

}

0 comments on commit 86eebb7

Please sign in to comment.