Last active
May 25, 2024 10:18
-
-
Save dacr/6d018842fa7674df00df309e1490080a to your computer and use it in GitHub Desktop.
scala list available resources. / published by https://github.com/dacr/code-examples-manager #a8328208-2218-4c90-8530-e3143e0ce4fa/114ed8a3e4dd6f2adf0854017d6a2f9bf814651e
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// summary : scala list available resources. | |
// keywords : scala, classloader, resources, @testable | |
// publish : gist | |
// authors : David Crosson | |
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2) | |
// id : a8328208-2218-4c90-8530-e3143e0ce4fa | |
// created-on : 2020-05-31T19:54:52Z | |
// managed-by : https://github.com/dacr/code-examples-manager | |
// run-with : scala-cli $file | |
// --------------------- | |
//> using scala "3.4.2" | |
//> using dep "org.scalatest::scalatest:3.2.10" | |
//> using dep "fr.janalyse::drools-scripting:1.0.16" | |
// --------------------- | |
import org.scalatest.flatspec._, org.scalatest.matchers._ | |
import java.io.File, java.net.{URL,URLDecoder}, java.util.jar.JarFile | |
import scala.jdk.CollectionConverters._ | |
def resourcesList(from: String): List[String] = { | |
val goodFrom = | |
from | |
.trim | |
.replaceAll("/{2,}", "/") | |
.replaceAll("/$","") | |
.replaceAll("^/","") + "/" | |
def listContent(url:URL):List[String] = { | |
url.getProtocol match { | |
case "file" => new File(url.getPath).list().toList | |
case "jar" => | |
val jarPath = url.getPath().substring(5, url.getPath().indexOf("!")) | |
val jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8")) | |
val entries = jar.entries().asScala | |
entries | |
.filter(entry => entry.getName.startsWith(goodFrom)) | |
.flatMap(_.getName.drop(goodFrom.size).split("/").headOption) | |
.toList | |
} | |
} | |
val cl = Thread.currentThread().getContextClassLoader | |
cl.getResources(goodFrom) | |
.asScala | |
.toList | |
.flatMap(listContent) | |
.filter(_.size>0) | |
.distinct | |
} | |
object ResourcesListTest extends AnyFlatSpec with should.Matchers { | |
override def suiteName: String = "ResourcesListTest" | |
"resourcesList" should "list accessible resources" in { | |
val r = resourcesList("META-INF") | |
info("Discovered (distinct): "+r.sorted.mkString(", ")) | |
r.size shouldBe > (2) | |
r should contain allElementsOf List( "services", "maven", "kie.conf", "LICENSE") | |
} | |
it should "not list anything when file resources" in { | |
val r = resourcesList("META-INF/MANIFEST.MF") | |
r.size shouldBe 0 | |
} | |
} | |
ResourcesListTest.execute() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment