Skip to content
Permalink
Browse files

Scala Style code fixes

  • Loading branch information...
atooni committed Jun 5, 2019
1 parent f8f00e3 commit 2e44436a4dbf016e729470d1fafbcc95227d54fa
Showing with 237 additions and 231 deletions.
  1. +10 −10 ....activemq.brokerstarter/src/main/scala/blended/activemq/brokerstarter/internal/BrokerConfig.scala
  2. +7 −6 blended.jms.bridge/src/main/scala/blended/jms/bridge/internal/JmsRetryProcessor.scala
  3. +4 −4 blended.jolokia/src/main/scala/blended/jolokia/MBeanSearchDef.scala
  4. +3 −5 blended.security.ssl/src/main/scala/blended/security/ssl/CertificateHolder.scala
  5. +2 −1 blended.security.ssl/src/main/scala/blended/security/ssl/CertificateSigner.scala
  6. +2 −2 blended.security.ssl/src/main/scala/blended/security/ssl/MemoryKeystore.scala
  7. +3 −1 blended.security.ssl/src/main/scala/blended/security/ssl/SelfSignedConfig.scala
  8. +1 −1 blended.security.ssl/src/main/scala/blended/security/ssl/SslContextInfo.scala
  9. +0 −7 blended.security.ssl/src/main/scala/blended/security/ssl/internal/CertificateManagerConfig.scala
  10. +5 −5 blended.security.ssl/src/main/scala/blended/security/ssl/internal/CertificateManagerImpl.scala
  11. +4 −1 blended.security.ssl/src/main/scala/blended/security/ssl/internal/CertificateRefresher.scala
  12. +4 −2 blended.security.ssl/src/main/scala/blended/security/ssl/internal/JavaKeystore.scala
  13. +2 −0 blended.security.ssl/src/main/scala/blended/security/ssl/internal/SslContextProvider.scala
  14. +1 −1 blended.security.ssl/src/main/scala/blended/security/ssl/internal/TrustStoreRefresher.scala
  15. +4 −4 blended.security.ssl/src/test/scala/blended/security/ssl/CertificateHolderSpec.scala
  16. +3 −3 blended.security.ssl/src/test/scala/blended/security/ssl/SecurityTestSupport.scala
  17. +2 −4 blended.security.ssl/src/test/scala/blended/security/ssl/SelfSignedProviderSpec.scala
  18. +1 −1 blended.security.ssl/src/test/scala/blended/security/ssl/internal/CertificateActivatorSpec.scala
  19. +4 −2 blended.security.ssl/src/test/scala/blended/security/ssl/internal/CertificateCheckerSpec.scala
  20. +6 −2 blended.security.ssl/src/test/scala/blended/security/ssl/internal/CertificateRefresherSpec.scala
  21. +6 −8 blended.security.ssl/src/test/scala/blended/security/ssl/internal/JavaKeystoreSpec.scala
  22. +20 −23 blended.security.ssl/src/test/scala/blended/security/ssl/internal/MemoryKeystoreSpec.scala
  23. +2 −2 blended.security.ssl/src/test/scala/blended/security/ssl/internal/PasswordHasherSpec.scala
  24. +5 −5 blended.security.ssl/src/test/scala/blended/security/ssl/internal/TrustStoreRefresherSpec.scala
  25. +39 −38 ...eams.dispatcher/src/main/scala/blended/streams/dispatcher/internal/ResourceTypeRouterConfig.scala
  26. +3 −4 ...ms.dispatcher/src/main/scala/blended/streams/dispatcher/internal/builder/RunnableDispatcher.scala
  27. +7 −8 ...s.dispatcher/src/main/scala/blended/streams/dispatcher/internal/builder/TransactionOutbound.scala
  28. +9 −10 ...treams.dispatcher/src/test/scala/blended/streams/dispatcher/internal/builder/DispatcherSpec.scala
  29. +17 −14 blended.streams/src/main/scala/blended/streams/jms/JmsSinkStage.scala
  30. +11 −11 blended.streams/src/main/scala/blended/streams/jms/JmsSourceStage.scala
  31. +20 −20 blended.streams/src/main/scala/blended/streams/jms/JmsStreamSupport.scala
  32. +10 −10 blended.streams/src/main/scala/blended/streams/transaction/FlowTransactionActor.scala
  33. +4 −4 blended.streams/src/main/scala/blended/streams/transaction/FlowTransactionStream.scala
  34. +16 −12 blended.streams/src/test/scala/blended/streams/AckSourceLogicSpec.scala
@@ -9,7 +9,7 @@ import org.apache.activemq.ActiveMQConnectionFactory
import scala.concurrent.duration.FiniteDuration
import scala.util.Try

case class BrokerConfig (
case class BrokerConfig(
override val vendor : String,
override val provider : String,
override val clientId : String,
@@ -27,14 +27,14 @@ case class BrokerConfig (
file : String,
withSsl : Boolean
) extends ConnectionConfig {
override val enabled: Boolean = true
override val defaultUser: Option[String] = None
override val defaultPassword: Option[String] = None
override val useJndi: Boolean = false
override val cfEnabled: Option[ConnectionConfig => Boolean] = None
override val cfClassName: Option[String] = Some(classOf[ActiveMQConnectionFactory].getName())
override val ctxtClassName: Option[String] = None
override val jmsClassloader: Option[ClassLoader] = None
override val enabled : Boolean = true
override val defaultUser : Option[String] = None
override val defaultPassword : Option[String] = None
override val useJndi : Boolean = false
override val cfEnabled : Option[ConnectionConfig => Boolean] = None
override val cfClassName : Option[String] = Some(classOf[ActiveMQConnectionFactory].getName())
override val ctxtClassName : Option[String] = None
override val jmsClassloader : Option[ClassLoader] = None
}

object BrokerConfig {
@@ -56,7 +56,7 @@ object BrokerConfig {

val ssl : Config => Boolean = cfg => cfg.getBoolean("withSsl", true)

def create(brokerName : String, idSvc: ContainerIdentifierService, cfg: Config) : Try[BrokerConfig] = Try {
def create(brokerName : String, idSvc : ContainerIdentifierService, cfg : Config) : Try[BrokerConfig] = Try {

val resolve : String => Try[Any] = value => idSvc.resolvePropertyString(value)

@@ -58,12 +58,13 @@ case class JmsRetryConfig(
maxRetries : Long = -1,
retryTimeout : FiniteDuration = 1.day
) {
override def toString: String = s"${getClass().getSimpleName}[${cf.vendor}:${cf.provider}](retryDestination=$retryDestName," +
override def toString : String = s"${getClass().getSimpleName}[${cf.vendor}:${cf.provider}](retryDestination=$retryDestName," +
s"failedDestination=$failedDestName,retryInterval=$retryInterval,maxRetries=$maxRetries,retryTimeout=$retryTimeout)"
}

class JmsRetryProcessor(name : String, retryCfg : JmsRetryConfig)(
implicit system : ActorSystem, materializer : Materializer
implicit
system : ActorSystem, materializer : Materializer
) extends JmsStreamSupport {

private[this] val id : String = retryCfg.headerCfg.prefix + ".retry." + retryCfg.retryDestName
@@ -80,7 +81,7 @@ class JmsRetryProcessor(name : String, retryCfg : JmsRetryConfig)(
val validator : FlowProcessor.IntegrationStep
) extends FlowHeaderConfigAware with JmsEnvelopeHeader {

override def sendParameter(session: Session, env: FlowEnvelope): Try[JmsSendParameter] = Try {
override def sendParameter(session : Session, env : FlowEnvelope) : Try[JmsSendParameter] = Try {

val dest : JmsDestination = env.exception match {
// If the envelope does not have an exception, we will send it to the original destination for reprocessing
@@ -195,7 +196,7 @@ class JmsRetryProcessor(name : String, retryCfg : JmsRetryConfig)(
// case the envelope is marked with an exception after trying to forward the
// message

val transSplit = b.add(FlowProcessor.partition[FlowEnvelope]{ env => env.exception.isEmpty && router.validate(env).isFailure })
val transSplit = b.add(FlowProcessor.partition[FlowEnvelope] { env => env.exception.isEmpty && router.validate(env).isFailure })
val transMerge = b.add(Merge[FlowEnvelope](2))

merge.out ~> transSplit.in
@@ -237,8 +238,8 @@ class JmsRetryProcessor(name : String, retryCfg : JmsRetryConfig)(
}
}

def stop(): Unit = {
actor.synchronized{
def stop() : Unit = {
actor.synchronized {
actor.foreach(system.stop)
actor = None
}
@@ -4,16 +4,16 @@ case class MBeanSearchDef(
jmxDomain : String,
searchProperties : Map[String, String] = Map.empty
) {
def pattern: String = searchProperties match {
def pattern : String = searchProperties match {
case m if m.isEmpty => ""
case m => m.keys.map( k => s"$k=${m.get(k).get}" ).mkString("", ",", ",")
case m => m.keys.map(k => s"$k=${m.get(k).get}").mkString("", ",", ",")
}
}

case class OperationExecDef(
objectName : String,
objectName : String,
operationName : String,
parameters : List[String] = List.empty
parameters : List[String] = List.empty
) {
def pattern : String = s"$objectName/$operationName/" + parameters.mkString("/")
}
@@ -64,8 +64,7 @@ object CertificateHolder {
def create(cert : X509Certificate) : CertificateHolder = CertificateHolder(
publicKey = cert.getPublicKey(),
privateKey = None,
chain = List(cert),
changed = false
chain = List(cert)
)

def create(publicKey : PublicKey, chain : List[Certificate]) : Try[CertificateHolder] =
@@ -105,12 +104,11 @@ object CertificateHolder {
case None =>
throw new MissingRootCertificateException

case Some(root) => {
case Some(root) =>
// The root must have signed itself correctly
root.verify(root.getPublicKey())
// We kick off the sort with the root certificate as a starting point
sort(certs.filter(c => !c.equals(root)))(root :: Nil).get
}
}
}
}
@@ -120,7 +118,7 @@ object CertificateHolder {

// A test that yields true if and only if the certificate is not self signed AND was signed by
// the given principal
private def signedBy(issuer : Principal) : (X509Certificate => Boolean) = c =>
private def signedBy(issuer : Principal) : X509Certificate => Boolean = c =>
!c.getIssuerDN().equals(c.getSubjectDN()) && c.getIssuerDN().equals(issuer)

// Helper function to sort the certificates of a given chain so that any certificate in the chain is
@@ -17,12 +17,13 @@ import scala.util.Try
trait CertificateRequestBuilder {

private val log : Logger = Logger[CertificateRequestBuilder]
private val defaultValidDays : Int = 365

def hostCertificateRequest(
cnProvider : CommonNameProvider,
keyPair : KeyPair,
serial : BigInteger = new BigInteger("1"),
validDays : Int = 365,
validDays : Int = defaultValidDays,
issuedBy : Option[CertificateHolder] = None
) : Try[X509v3CertificateBuilder] = Try {

@@ -14,7 +14,7 @@ case class MemoryKeystore(certificates : Map[String, CertificateHolder]) {
private[this] val log : Logger = Logger[MemoryKeystore]
private[this] val millisPerDay : Long = 1.day.toMillis

val changedAliases : List[String] = certificates.filter { case (k, v) => v.changed }.keys.toList
val changedAliases : List[String] = certificates.filter { case (_, v) => v.changed }.keys.toList

// The in memory keystore is consistent if and only if all certificates have a private key defined
// or none of it does have a private key defined.
@@ -61,7 +61,7 @@ case class MemoryKeystore(certificates : Map[String, CertificateHolder]) {
this
case Some(p) =>
val newCert = p.refreshCertificate(oldCert, certCfg.cnProvider).get
log.info(s"Obtained certificate for alias [${certCfg.alias}] : [${newCert}]")
log.info(s"Obtained certificate for alias [${certCfg.alias}] : [$newCert]")
update(certCfg.alias, newCert).get
}
}
@@ -14,11 +14,13 @@ case class SelfSignedConfig(

object SelfSignedConfig {

private val defaultKeyStrength : Int = 2048

val sigAlgPath = "signatureAlgorithm"
val validDaysPath = "validDays"

def fromConfig(cfg : Config, idSvc : ContainerIdentifierService) : SelfSignedConfig = {
val keyStrength = cfg.getInt("keyStrength", 2048)
val keyStrength = cfg.getInt("keyStrength", defaultKeyStrength)
val signatureAlgorithm = cfg.getString("signatureAlgorithm", "SHA256withRSA")
val validDays = cfg.getInt("validDays", 1)

@@ -12,7 +12,7 @@ trait SslContextInfo {
getEnabledCypherSuites().filter { s => !getAllowedCypherSuites().contains(s) }
}

override def toString : String = s"SSLContextInfo(protocol=$getProtocol()," +
override def toString : String = s"SSLContextInfo(protocol=${getProtocol()}," +
s"enabledProtocols=${getEnabledProtocols().mkString(",")},\n" +
s"enabledCyphers=${getEnabledCypherSuites().mkString(",\n")}\n" +
s"invalidCyphers=${getInvalidCypherSuites().mkString(",\n")}\n)"
@@ -30,13 +30,6 @@ case class KeystoreConfig(

/**
* Configuration of [[CertificateManagerImpl]]
*
* @param keyStore The used keyStore.
* @param storePass The password used to open the key store.
* @param keyPass The key password.
* If the days until the end of the certificate validity fall below this threshold,
* the [[CertificateManagerImpl]] will try to re-new the certificate.
* @param skipInitialCheck If `true` no initial certifcate check will be issues.
*/
case class CertificateManagerConfig(
clientOnly : Boolean,
@@ -65,7 +65,7 @@ class CertificateManagerImpl(
registerSslContextProvider()
log.info("Successfully refreshed trusted certificate store")

case Success(Some(sks)) =>
case Success(Some(_)) =>
val jks = javaKeystore.get
//
// log.info(s"Successfully obtained [${sks.certificates.size}] Server Certificate(s) for SSLContext")
@@ -123,19 +123,19 @@ class CertificateManagerImpl(
// first refresh the server certificates if required
log.debug("Loading keystore...")
val ks = loadKeyStore().get
log.debug(s"Loaded keystore [${ks}]")
log.debug(s"Loaded keystore [$ks]")

ks.map { ms =>
log.debug(s"Refreshing certificates for keystore [${ms}]")
log.debug(s"Refreshing certificates for keystore [$ms]")
val changedKs = ms.refreshCertificates(cfg.certConfigs, providerMap).get

log.debug(s"Saving keystore...")
val jks = javaKeystore.get
jks.saveKeyStore(changedKs) match {
case f @ Failure(t) =>
case Failure(t) =>
log.warn(t)(s"Failed to save keystore to file [${jks.keystore.getAbsolutePath()}] : [${t.getMessage()}]")
throw t
case Success(ks) => ks
case Success(s) => s
}
}
}
@@ -111,7 +111,10 @@ class CertificateRefresher(
case Some(frameworkService) =>
// we want to restart the container, so no de- and re-registration of the ssl context
log.warn("Requesting framework restart")
frameworkService.restartContainer("The certificate required for the SSL context was refreshed. An restart is required to cleanly use the new certificate.", true)
frameworkService.restartContainer(
reason = "The certificate required for the SSL context was refreshed. An restart is required to cleanly use the new certificate.",
saveLogs = true
)

case None =>
log.error("Could not acquire a FrameworkService to restart the OSGi container. Skipping certificate refresh.")
@@ -64,7 +64,9 @@ class JavaKeystore(
}
} else {
log.info(s"Loading empty key store [${keystore.getAbsolutePath()}] ...")
// scalastyle:off null
ks.load(null, storepass)
// scalastyle:on null
}

ks
@@ -76,7 +78,7 @@ class JavaKeystore(
val certCount = ks.aliases().asScala.size
log.info(s"Storing [$certCount] certificates to [$keystore]")
ks.store(fos, storepass)
log.info(s"Successfully written key store to [${keystore}] with storePass [${new String(storepass)}]")
log.info(s"Successfully written key store to [$keystore] with storePass [${new String(storepass)}]")
} finally {
fos.close()
}
@@ -94,7 +96,7 @@ class JavaKeystore(
throw new Exception(s"Certificate for alias [$alias] not found.")
case Some(c) => List(c.asInstanceOf[X509Certificate])
}
case Some(chain) => chain.toList.map(_.asInstanceOf[X509Certificate])
case Some(c) => c.toList.map(_.asInstanceOf[X509Certificate])
}

val pubKey : PublicKey = chain.head.getPublicKey()
@@ -11,6 +11,7 @@ object SslContextProvider {
private[ssl] val propTrustStorePwd = "javax.net.ssl.trustStorePassword"
}

// scalastyle:off null
class SslContextProvider {

import SslContextProvider.{propTrustStore, propTrustStorePwd}
@@ -57,3 +58,4 @@ class SslContextProvider {
ctxt
}
}
// scalastyle:on null
@@ -57,6 +57,6 @@ class TrustStoreRefresher(ms : MemoryKeystore) {
}

private def updateRoots(trusted : MemoryKeystore, keystore : MemoryKeystore) : Try[MemoryKeystore] = Try {
keystore.certificates.foldLeft(trusted) { case (s, (alias, c)) => updateRoot(s, c).get }
keystore.certificates.foldLeft(trusted) { case (s, (_, c)) => updateRoot(s, c).get }
}
}
@@ -26,7 +26,7 @@ class CertificateHolderSpec extends LoggingFreeSpec
}
}

extendChain(createRootCertificate().get, length - 1)
extendChain(createRootCertificate(cn = "root").get, length - 1)
}

"The certificate holder should" - {
@@ -41,7 +41,7 @@ class CertificateHolderSpec extends LoggingFreeSpec

"Ensure the certificate chain does have a root certificate" in {

val root : CertificateHolder = createRootCertificate().get
val root : CertificateHolder = createRootCertificate(cn = "root").get
val host : CertificateHolder = createHostCertificate("host", root).get

intercept[MissingRootCertificateException] {
@@ -50,9 +50,9 @@ class CertificateHolderSpec extends LoggingFreeSpec
}

"Ensure the signature links are correct" in {
val root : CertificateHolder = createRootCertificate().get
val root : CertificateHolder = createRootCertificate(cn = "root").get
val host : CertificateHolder = createHostCertificate("host", root).get
val fakeRoot : CertificateHolder = createRootCertificate().get
val fakeRoot : CertificateHolder = createRootCertificate(cn = "root").get

intercept[SignatureException] {
CertificateHolder.create(host.publicKey, host.chain.head :: fakeRoot.chain.head :: Nil).get
@@ -32,7 +32,7 @@ trait SecurityTestSupport { this : CertificateRequestBuilder with CertificateSig
val selfSignedCfg : CommonNameProvider => SelfSignedConfig = cnProvider => SelfSignedConfig(
commonNameProvider = cnProvider,
sigAlg = "SHA256withRSA",
keyStrength = 2048,
keyStrength = keyStrength,
validDays = validDays
)

@@ -50,9 +50,9 @@ trait SecurityTestSupport { this : CertificateRequestBuilder with CertificateSig
f
}

def createRootCertificate(cn : String = "root", validDays : Int = validDays) : Try[CertificateHolder] = Try {
def createRootCertificate(cn : String, validDays : Int = validDays) : Try[CertificateHolder] = Try {

val cnProvider : CommonNameProvider = new HostnameCNProvider(cn)
val cnProvider : CommonNameProvider = HostnameCNProvider(cn)
new SelfSignedCertificateProvider(selfSignedCfg(cnProvider).copy(validDays = validDays)).refreshCertificate(None, cnProvider).get
}

@@ -34,8 +34,7 @@ class SelfSignedProviderSpec extends LoggingFreeSpec

"update a self signed certificate by maintaining the same key pair and increasing the serial number" in {

val cnProvider : CommonNameProvider =
new HostnameCNProvider("root")
val cnProvider : CommonNameProvider = HostnameCNProvider("root")

val provider : CertificateProvider =
new SelfSignedCertificateProvider(selfSignedCfg(cnProvider))
@@ -60,8 +59,7 @@ class SelfSignedProviderSpec extends LoggingFreeSpec

"requires a private key in in the old key to refresh" in {

val cnProvider : CommonNameProvider =
new HostnameCNProvider("root")
val cnProvider : CommonNameProvider = HostnameCNProvider("root")

val provider : CertificateProvider =
new SelfSignedCertificateProvider(selfSignedCfg(cnProvider))
@@ -52,7 +52,7 @@ class CertificateActivatorSpec extends SimplePojoContainerSpec
mandatoryService[SSLContext](registry)(Some("(type=server)"))

val invalid = sslInfo.getInvalidCypherSuites()
log.info(s"Invalid CypherSuites [${invalid.size}] : [\n${invalid.mkString("\n")}\n]")
log.info(s"Invalid CypherSuites [${invalid.length}] : [\n${invalid.mkString("\n")}\n]")

invalid should be(empty)
}

0 comments on commit 2e44436

Please sign in to comment.
You can’t perform that action at this time.