use of org.eclipse.ceylon.compiler.java.language.FileResource in project ceylon by eclipse.
the class ModuleImpl method resourceByPath.
@Override
@TypeInfo("ceylon.language::Resource")
public Resource resourceByPath(@Name("path") String path) {
String fullPath = path;
if (!fullPath.startsWith("/")) {
String modPath = ("default".equals(getName())) ? "" : getName().replace('.', '/') + "/";
fullPath = modPath + path;
} else {
fullPath = fullPath.substring(1);
}
fullPath = JVMModuleUtil.quoteJavaKeywordsInFilename(fullPath);
// First lets ask the module manager for the contents of the resource
RuntimeModuleManager moduleManager = Metamodel.getModuleManager();
if (moduleManager != null) {
RuntimeModelLoader modelLoader = moduleManager.getModelLoader();
if (modelLoader != null) {
byte[] contents = modelLoader.getContents(declaration, fullPath);
if (contents != null) {
URI uri = modelLoader.getContentUri(declaration, fullPath);
return new ByteArrayResource(contents, uri);
}
}
}
// Second let's see if we can find the on-disk location of the module
String moduleUnitFullPath = declaration.getUnit().getFullPath();
if (moduleUnitFullPath != null) {
final File car = new File(moduleUnitFullPath);
// Then let's look inside the car
try (ZipFile zip = new ZipFile(car)) {
ZipEntry e = zip.getEntry(fullPath);
if (e != null && !e.isDirectory()) {
return new ZipResource(car, fullPath);
}
} catch (IOException ex) {
throw new ceylon.language.Exception(new ceylon.language.String("Searching for resource " + path), ex);
}
// And finally as a fall-back let's look in the module's resource dir...
final File target = new File(new File(car.getParentFile(), "module-resources"), fullPath);
if (target.exists() && target.isFile() && target.canRead()) {
return new FileResource(target);
}
}
// One last shot: we might be in a fat jar
try (InputStream stream = getClass().getClassLoader().getResourceAsStream(fullPath)) {
if (stream != null) {
byte[] buf = new byte[16384];
ByteArrayOutputStream bout = new ByteArrayOutputStream();
int bytesRead = stream.read(buf);
while (bytesRead > 0) {
bout.write(buf, 0, bytesRead);
bytesRead = stream.read(buf);
}
return new ByteArrayResource(bout.toByteArray(), new URI("classpath:" + fullPath));
}
} catch (IOException | URISyntaxException ex) {
throw new ceylon.language.Exception(new ceylon.language.String("Searching for resource " + path), ex);
}
return null;
}
Aggregations