Permalink
Browse files

Some code cleanup

  • Loading branch information...
atooni committed Sep 2, 2018
1 parent dfe40de commit 301e1a6136f6d3451d62ae75e7411eb760523b0f
View

Large diffs are not rendered by default.

Oops, something went wrong.
@@ -1,6 +1,6 @@
implicit val scalaVersion = ScalaVersion(BlendedVersions.scalaVersion)
case class ScalaJsVersion(val version: String) {
case class ScalaJsVersion(version: String) {
val binaryVersion = version.split("\\.", 3).take(2).mkString(".")
}
@@ -4,108 +4,109 @@ import blended.util.logging.Logger
object ContainerPropertyResolver {
private[this] val log = Logger[ContainerPropertyResolver]
type Resolver = String => String
type Modifier = (String, String) => String
private[this] val log = Logger[ContainerPropertyResolver.type]
private[this] val startDelim = "$[["
private[this] val endDelim = "]]"
def extractRule(line: String) : (String, String, String) = {
private[this] def extractRule(line: String) : (String, String, String) = {
line.lastIndexOf(startDelim) match {
case -1 => ("", line, "")
case start => line.indexOf(endDelim, start) match {
case -1 => throw new PropertyResolverException(s"Error decoding replacement pattern [${line}] : missing end delimiter [$endDelim]")
case -1 => throw new PropertyResolverException(s"Error decoding replacement pattern [$line] : missing end delimiter [$endDelim]")
case end => (line.substring(0, start), line.substring(start + startDelim.length, end), line.substring(end + endDelim.length))
}
}
}
def processRule(idSvc: ContainerIdentifierService, rule: String) : String = {
// these are the valid modifiers in a resolver expression
private[this] val modifiers : Map[String, Modifier] = Map(
"upper" -> { case (s : String, _ : String) => s.toUpperCase() },
log.trace(s"Processing rule [$rule]")
type Resolver = String => String
type Modifier = (String, String) => String
// these are the valid modifiers in a resolver expression
val modifiers : Map[String, Modifier] = Map(
"upper" -> { case (s : String, param : String) => s.toUpperCase() },
"lower" -> { case (s : String, param : String) => s.toLowerCase() },
"capitalize" -> { case (s : String, param: String) => s.capitalize },
"right" -> { case (s: String, param: String) =>
val n = param.toInt
if (n >= s.length) s else s.takeRight(n)
},
"left" -> { case (s: String, param: String) =>
val n = param.toInt
if (n >= s.length) s else s.take(n)
},
"replace" -> { case (s: String, param: String) =>
val replace = param.split(":")
if (replace.length != 2) {
s
} else {
s.replaceAll(replace(0), replace(1))
}
"lower" -> { case (s : String, _ : String) => s.toLowerCase() },
"capitalize" -> { case (s : String, _ : String) => s.capitalize },
"right" -> { case (s: String, param: String) =>
val n = param.toInt
if (n >= s.length) s else s.takeRight(n)
},
"left" -> { case (s: String, param : String) =>
val n = param.toInt
if (n >= s.length) s else s.take(n)
},
"replace" -> { case (s: String, param: String) =>
val replace = param.split(":")
if (replace.length != 2) {
s
} else {
s.replaceAll(replace(0), replace(1))
}
)
}
)
private[this] def resolver(idSvc: ContainerIdentifierService) : Map[String, Resolver] = Map(
ContainerIdentifierService.containerId -> ( _ => idSvc.uuid )
)
private[this] def extractModifier(s : String) : Option[(Modifier, String)] = {
val pos = s.indexOf(":")
val (modName, params) = if (pos != -1) (s.substring(0, pos), s.substring(pos + 1)) else (s, "")
modifiers.get(modName).map { m => (m, params) }
}
private[this] def processRule(idSvc: ContainerIdentifierService, rule: String) : String = {
val resolvers : Map[String, Resolver] = Map(
ContainerIdentifierService.containerId -> ( _ => idSvc.uuid )
)
log.trace(s"Processing rule [$rule]")
// A rule can have any number of parameterized modifiers, spearated by ","
val (ruleName : String, modifier : List[String]) = rule.indexOf("(") match {
case -1 => (rule, List.empty)
case (s) => (
case s => (
rule.substring(0, s),
rule.substring(s+1, rule.indexOf(")", s)).split(",").toList
rule.substring(s + 1, rule.indexOf(")", s)).split(",").toList
)
}
log.trace(s"rule [$ruleName], [${modifier.mkString(",")}]")
val mods : List[(Modifier, String)] = modifier.map { m =>
val pos = m.indexOf(":")
if (pos != -1) (m.substring(0, pos), m.substring(pos + 1)) else (m, "")
}.filter { case (modName, param) => modifiers.contains(modName) }.map{ case (modName, param) =>
(modifiers(modName), param)
// Now we need to find the proper modifiers to apply with their parameters
val mods : List[(Modifier, String)] = modifier.map(extractModifier).collect {
case Some(m) => m
}
val props = Option(idSvc.properties).getOrElse(Map.empty)
// First, we resolve the rule from the environment vars or System properties
// The resolution is mandatory
var result : String = props.get(ruleName) match {
case Some(s) => s
case None =>
Option(System.getenv().getOrDefault(ruleName, System.getProperty(ruleName))) match {
case Some(s) => s
case None =>
resolvers.get(ruleName) match {
case Some(r) => (r(ruleName))
resolver(idSvc).get(ruleName) match {
case Some(r) => r(ruleName)
case None => throw new PropertyResolverException(s"Unable to resolve property [$rule]")
}
}
}
// Then we apply the collected modifiers left to right to the resolved value
result = mods.foldLeft[String](result)((a,b) => b._1(a, b._2))
result
}
def resolve(idSvc: ContainerIdentifierService, line: String) : String = {
var result = line
while(result.indexOf(startDelim) != -1) {
val (prefix, rule, suffix) = extractRule(result)
result = prefix + processRule(idSvc, rule) + suffix
}
log.debug(s"Resolved [$line] to [$result]")
result
def resolve(idSvc: ContainerIdentifierService, line: String) : String = line.indexOf(startDelim) match {
case n if n < 0 => line
case n if n >= 0 =>
val (prefix, rule, suffix) = extractRule(line)
resolve(idSvc, prefix + processRule(idSvc, rule) + suffix)
}
}
class ContainerPropertyResolver

This file was deleted.

Oops, something went wrong.
@@ -1,28 +1,30 @@
package blended.container.context.api
import com.typesafe.config.Config
import org.scalatest.{FreeSpec, Matchers}
import scala.util.control.NonFatal
//noinspection NotImplementedCode
class PropertyResolverSpec extends FreeSpec
with Matchers {
val ctCtxt = new ContainerContext() {
val ctCtxt : ContainerContext = new ContainerContext() {
override def getProfileDirectory() = ???
override def getProfileDirectory() : String = ???
override def getProfileConfigDirectory() = ???
override def getProfileConfigDirectory() : String = ???
override def getContainerLogDirectory() = ???
override def getContainerLogDirectory() : String = ???
override def getContainerDirectory() = ???
override def getContainerDirectory() : String = ???
override def getContainerConfigDirectory() = ???
override def getContainerConfigDirectory() : String = ???
override def getContainerHostname() = ???
override def getContainerHostname() : String = ???
override def getContainerConfig() = ???
override def getContainerConfig() : Config = ???
}
val idSvc : ContainerIdentifierService = new ContainerIdentifierService {
@@ -55,8 +57,8 @@ class PropertyResolverSpec extends FreeSpec
ContainerPropertyResolver.resolve(idSvc, "$[[foo")
fail()
} catch {
case pre : PropertyResolverException =>
case NonFatal(e) => fail()
case _ : PropertyResolverException =>
case NonFatal(e) => fail(e)
}
}
@@ -65,7 +67,7 @@ class PropertyResolverSpec extends FreeSpec
ContainerPropertyResolver.resolve(idSvc, "$[[noprop]]")
fail()
} catch {
case pre : PropertyResolverException =>
case _ : PropertyResolverException =>
case _ : Throwable => fail()
}
}
@@ -17,10 +17,11 @@ class ConfigLocator(ctContext: ContainerContext) {
val file = new File(ctContext.getProfileConfigDirectory(), fileName)
log.debug(s"Retrieving config from [${file.getAbsolutePath()}]")
if (file.exists && file.isFile && file.canRead)
if (file.exists && file.isFile && file.canRead) {
ConfigFactory.parseFile(file).withFallback(sysProps).withFallback(envProps).resolve()
else
} else {
ConfigFactory.empty()
}
}
/**
@@ -49,11 +49,11 @@ class BlendedLoginModule extends LoginModule {
val moduleBundle: Option[String] = Option(newOptions.remove(propBundle).toString())
(moduleClass, moduleBundle) match {
case (None, _) => throw new IllegalStateException(s"Option [${propBundle}] must be set to the name of the factory service bundle.")
case (_, None) => throw new IllegalStateException(s"Option [${propModule}] must be set to the name of the factory service.")
case (None, _) => throw new IllegalStateException(s"Option [$propBundle] must be set to the name of the factory service bundle.")
case (_, None) => throw new IllegalStateException(s"Option [$propModule] must be set to the name of the factory service.")
case (Some(clazz), Some(bundleName)) =>
loginBundle(bundleName) match {
case None => throw new IllegalStateException(s"Bundle [${bundleName}] not found.")
case None => throw new IllegalStateException(s"Bundle [$bundleName] not found.")
case Some(bundle) =>
try {
target = Option(bundle.loadClass(clazz).newInstance().asInstanceOf[LoginModule])
@@ -65,7 +65,7 @@ class BlendedLoginModule extends LoginModule {
))
} catch {
case _ : ClassNotFoundException =>
throw new IllegalStateException(s"Could not load Login Module [${clazz}] from bundle [${bundleName}]")
throw new IllegalStateException(s"Could not load Login Module [$clazz] from bundle [$bundleName]")
case e: Exception =>
throw new IllegalStateException(s"${e.getClass().getName()} : ${e.getMessage()}")
}
@@ -74,7 +74,7 @@ class BlendedLoginModule extends LoginModule {
}
private[this] def loginBundle(name: String): Option[Bundle] =
bundleContext.getBundles().find(_.getSymbolicName().equals(name))
bundleContext.getBundles().find( b => b.getSymbolicName().equals(name))
override def logout(): Boolean = target match {
case None => throw new LoginException(NotInitialised)
@@ -8,9 +8,9 @@ class GroupPrincipal(group: String) extends Principal {
override def hashCode(): Int = group.hashCode()
override def equals(other: scala.Any): Boolean = other match {
override def equals(other: Any): Boolean = other match {
case p : GroupPrincipal => group.equals(p.getName())
case o => false
case _ => false
}
override def toString: String = s"GroupPrincipal($group)"
@@ -7,9 +7,9 @@ class UserPrincipal(user: String) extends Principal {
override def hashCode(): Int = user.hashCode()
override def equals(other: scala.Any): Boolean = other match {
override def equals(other: Any): Boolean = other match {
case p : UserPrincipal => user.equals(p.getName())
case o => false
case _ => false
}
override def toString: String = s"UserPrincipal($user)"
@@ -20,10 +20,11 @@ lazy val projectSettings = Seq(
publishTo := {
val nexus = "https://oss.sonatype.org/"
if(isSnapshot.value)
if(isSnapshot.value) {
Some("snapshots" at nexus + "content/repositories/snapshots")
else
} else {
Some("releases" at nexus + "service/local/staging/deploy/maven2")
}
},
// avoid picking up pom.scala as source file
@@ -14,15 +14,15 @@ lazy val projectSettings = Seq(
scalaVersion := BlendedVersions.scalaVersionJS,
moduleName := appName,
publishMavenStyle := true,
publishMavenStyle := true,
publishArtifact in Test := false,
resolvers ++= Seq(
"Maven2 Local" at m2Repo
),
credentials += Credentials(Path.userHome / ".ivy2" / ".credentials"),
credentials += Credentials(Path.userHome / ".ivy2" / ".credentials"),
publishTo := {
val nexus = "https://oss.sonatype.org/"
@@ -66,7 +66,3 @@ object Logger {
* A Logger class doing nothing.
*/
class LoggerNoOp() extends Logger
@@ -29,9 +29,4 @@ class LoggerJul(underlying: jul.Logger) extends Logger {
override def info(e: Throwable)(msg: => String): Unit = log(jul.Level.INFO, msg, e)
override def debug(e: Throwable)(msg: => String): Unit = log(jul.Level.FINE, msg, e)
override def trace(e: Throwable)(msg: => String): Unit = log(jul.Level.FINER, msg, e)
}
View
@@ -24,6 +24,8 @@ inThisBuild(Seq(
"-target", "1.8"
),
coverageEnabled := true,
scalaVersion := "2.12.6",
scalacOptions ++= Seq("-deprecation", "-feature", "-Xlint", "-Ywarn-nullary-override"),
// essential to not try to compile pom.scala files
Oops, something went wrong.

0 comments on commit 301e1a6

Please sign in to comment.