Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active April 2, 2023 10:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/6d018842fa7674df00df309e1490080a to your computer and use it in GitHub Desktop.
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/17985f9802a868b0273cea221b1fb6b00dfcab3
// 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.1.1"
//> 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