java.lang.reflect.Modifier Scala Examples

The following examples show how to use java.lang.reflect.Modifier. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: ScalaDefaultValuesInjector.scala    From scala-commons   with MIT License 5 votes vote down vote up
package com.avsystem.commons
package spring

import java.lang.reflect.{Constructor, Method, Modifier}

import org.springframework.beans.factory.config.ConstructorArgumentValues.ValueHolder
import org.springframework.beans.factory.config.{BeanDefinition, BeanDefinitionHolder, ConfigurableListableBeanFactory}
import org.springframework.beans.factory.support.{BeanDefinitionRegistry, BeanDefinitionRegistryPostProcessor, ManagedList, ManagedMap, ManagedSet}
import org.springframework.core.ParameterNameDiscoverer

import scala.beans.BeanProperty
import scala.reflect.{ScalaLongSignature, ScalaSignature}

class ScalaDefaultValuesInjector extends BeanDefinitionRegistryPostProcessor {
  @BeanProperty var paramNameDiscoverer: ParameterNameDiscoverer =
    new ScalaParameterNameDiscoverer

  def classLoader: ClassLoader =
    Thread.currentThread.getContextClassLoader.opt getOrElse getClass.getClassLoader

  def loadClass(name: String): Class[_] = Class.forName(name, false, classLoader)

  def postProcessBeanDefinitionRegistry(registry: BeanDefinitionRegistry): Unit = {
    def traverse(value: Any): Unit = value match {
      case bd: BeanDefinition =>
        bd.getConstructorArgumentValues.getGenericArgumentValues.asScala.foreach(traverse)
        bd.getConstructorArgumentValues.getIndexedArgumentValues.values.asScala.foreach(traverse)
        bd.getPropertyValues.getPropertyValueList.asScala.foreach(pv => traverse(pv.getValue))
        injectDefaultValues(bd)
      case bdw: BeanDefinitionHolder =>
        traverse(bdw.getBeanDefinition)
      case vh: ValueHolder =>
        traverse(vh.getValue)
      case ml: ManagedList[_] =>
        ml.asScala.foreach(traverse)
      case ms: ManagedSet[_] =>
        ms.asScala.foreach(traverse)
      case mm: ManagedMap[_, _] =>
        mm.asScala.foreach {
          case (k, v) =>
            traverse(k)
            traverse(v)
        }
      case _ =>
    }

    registry.getBeanDefinitionNames
      .foreach(n => traverse(registry.getBeanDefinition(n)))
  }

  private def isScalaClass(cls: Class[_]): Boolean = cls.getEnclosingClass match {
    case null => cls.getAnnotation(classOf[ScalaSignature]) != null ||
      cls.getAnnotation(classOf[ScalaLongSignature]) != null
    case encls => isScalaClass(encls)
  }

  private def injectDefaultValues(bd: BeanDefinition): Unit =
    bd.getBeanClassName.opt.map(loadClass)
      .recoverToOpt[ClassNotFoundException].flatten.filter(isScalaClass)
      .foreach { clazz =>
        val usingConstructor = bd.getFactoryMethodName == null
        val factoryExecs =
          if (usingConstructor) clazz.getConstructors.toVector
          else clazz.getMethods.iterator.filter(_.getName == bd.getFactoryMethodName).toVector
        val factorySymbolName =
          if (usingConstructor) "$lessinit$greater" else bd.getFactoryMethodName

        if (factoryExecs.size == 1) {
          val constrVals = bd.getConstructorArgumentValues
          val factoryExec = factoryExecs.head
          val paramNames = factoryExec match {
            case c: Constructor[_] => paramNameDiscoverer.getParameterNames(c)
            case m: Method => paramNameDiscoverer.getParameterNames(m)
          }
          (0 until factoryExec.getParameterCount).foreach { i =>
            def defaultValueMethod = clazz.getMethod(s"$factorySymbolName$$default$$${i + 1}")
              .recoverToOpt[NoSuchMethodException].filter(m => Modifier.isStatic(m.getModifiers))
            def specifiedNamed = paramNames != null &&
              constrVals.getGenericArgumentValues.asScala.exists(_.getName == paramNames(i))
            def specifiedIndexed =
              constrVals.getIndexedArgumentValues.get(i) != null
            if (!specifiedNamed && !specifiedIndexed) {
              defaultValueMethod.foreach { dvm =>
                constrVals.addIndexedArgumentValue(i, dvm.invoke(null))
              }
            }
          }
        }
      }

  def postProcessBeanFactory(beanFactory: ConfigurableListableBeanFactory): Unit = ()
} 
Example 2
Source File: invoke_scala.scala    From libisabelle   with Apache License 2.0 5 votes vote down vote up
package isabelle


import java.lang.reflect.{Method, Modifier, InvocationTargetException}

import scala.util.matching.Regex


object Invoke_Scala
{
  

class Invoke_Scala extends Session.Protocol_Handler
{
  private var session: Session = null
  private var futures = Map.empty[String, Future[Unit]]

  override def init(init_session: Session): Unit =
    synchronized { session = init_session }

  override def exit(): Unit = synchronized
  {
    for ((id, future) <- futures) cancel(id, future)
    futures = Map.empty
  }

  private def fulfill(id: String, tag: Invoke_Scala.Tag.Value, res: String): Unit =
    synchronized
    {
      if (futures.isDefinedAt(id)) {
        session.protocol_command("Invoke_Scala.fulfill", id, tag.id.toString, res)
        futures -= id
      }
    }

  private def cancel(id: String, future: Future[Unit])
  {
    future.cancel
    fulfill(id, Invoke_Scala.Tag.INTERRUPT, "")
  }

  private def invoke_scala(msg: Prover.Protocol_Output): Boolean = synchronized
  {
    msg.properties match {
      case Markup.Invoke_Scala(name, id) =>
        futures += (id ->
          Future.fork {
            val (tag, result) = Invoke_Scala.method(name, msg.text)
            fulfill(id, tag, result)
          })
        true
      case _ => false
    }
  }

  private def cancel_scala(msg: Prover.Protocol_Output): Boolean = synchronized
  {
    msg.properties match {
      case Markup.Cancel_Scala(id) =>
        futures.get(id) match {
          case Some(future) => cancel(id, future)
          case None =>
        }
        true
      case _ => false
    }
  }

  val functions =
    List(
      Markup.INVOKE_SCALA -> invoke_scala _,
      Markup.CANCEL_SCALA -> cancel_scala _)
} 
Example 3
Source File: invoke_scala.scala    From libisabelle   with Apache License 2.0 5 votes vote down vote up
package isabelle


import java.lang.reflect.{Method, Modifier, InvocationTargetException}

import scala.util.matching.Regex


object Invoke_Scala
{
  

class Invoke_Scala extends Session.Protocol_Handler
{
  private var session: Session = null
  private var futures = Map.empty[String, Future[Unit]]

  override def init(init_session: Session): Unit =
    synchronized { session = init_session }

  override def exit(): Unit = synchronized
  {
    for ((id, future) <- futures) cancel(id, future)
    futures = Map.empty
  }

  private def fulfill(id: String, tag: Invoke_Scala.Tag.Value, res: String): Unit =
    synchronized
    {
      if (futures.isDefinedAt(id)) {
        session.protocol_command("Invoke_Scala.fulfill", id, tag.id.toString, res)
        futures -= id
      }
    }

  private def cancel(id: String, future: Future[Unit])
  {
    future.cancel
    fulfill(id, Invoke_Scala.Tag.INTERRUPT, "")
  }

  private def invoke_scala(msg: Prover.Protocol_Output): Boolean = synchronized
  {
    msg.properties match {
      case Markup.Invoke_Scala(name, id) =>
        futures += (id ->
          Future.fork {
            val (tag, result) = Invoke_Scala.method(name, msg.text)
            fulfill(id, tag, result)
          })
        true
      case _ => false
    }
  }

  private def cancel_scala(msg: Prover.Protocol_Output): Boolean = synchronized
  {
    msg.properties match {
      case Markup.Cancel_Scala(id) =>
        futures.get(id) match {
          case Some(future) => cancel(id, future)
          case None =>
        }
        true
      case _ => false
    }
  }

  val functions =
    List(
      Markup.INVOKE_SCALA -> invoke_scala _,
      Markup.CANCEL_SCALA -> cancel_scala _)
} 
Example 4
Source File: invoke_scala.scala    From libisabelle   with Apache License 2.0 5 votes vote down vote up
package isabelle


import java.lang.reflect.{Method, Modifier, InvocationTargetException}

import scala.util.matching.Regex


object Invoke_Scala
{
  

class Invoke_Scala extends Session.Protocol_Handler
{
  private var session: Session = null
  private var futures = Map.empty[String, Future[Unit]]

  override def init(init_session: Session): Unit =
    synchronized { session = init_session }

  override def exit(): Unit = synchronized
  {
    for ((id, future) <- futures) cancel(id, future)
    futures = Map.empty
  }

  private def fulfill(id: String, tag: Invoke_Scala.Tag.Value, res: String): Unit =
    synchronized
    {
      if (futures.isDefinedAt(id)) {
        session.protocol_command("Invoke_Scala.fulfill", id, tag.id.toString, res)
        futures -= id
      }
    }

  private def cancel(id: String, future: Future[Unit])
  {
    future.cancel
    fulfill(id, Invoke_Scala.Tag.INTERRUPT, "")
  }

  private def invoke_scala(msg: Prover.Protocol_Output): Boolean = synchronized
  {
    msg.properties match {
      case Markup.Invoke_Scala(name, id) =>
        futures += (id ->
          Future.fork {
            val (tag, result) = Invoke_Scala.method(name, msg.text)
            fulfill(id, tag, result)
          })
        true
      case _ => false
    }
  }

  private def cancel_scala(msg: Prover.Protocol_Output): Boolean = synchronized
  {
    msg.properties match {
      case Markup.Cancel_Scala(id) =>
        futures.get(id) match {
          case Some(future) => cancel(id, future)
          case None =>
        }
        true
      case _ => false
    }
  }

  val functions =
    List(
      Markup.INVOKE_SCALA -> invoke_scala _,
      Markup.CANCEL_SCALA -> cancel_scala _)
} 
Example 5
Source File: ModelSerializabilityTestBase.scala    From aloha   with MIT License 5 votes vote down vote up
package com.eharmony.aloha

import scala.language.existentials
import com.eharmony.aloha
import com.eharmony.aloha.models.{Model, SubmodelBase}
import org.junit.Assert._
import org.junit.Test
import org.reflections.Reflections

import scala.collection.JavaConversions.asScalaSet
import scala.util.Try
import java.lang.reflect.{Method, Modifier}

import com.eharmony.aloha.util.Logging


abstract class ModelSerializabilityTestBase(pkgs: Seq[String], outFilters: Seq[String])
extends Logging {

  def this() = this(pkgs = Seq(aloha.pkgName), Seq.empty)

  @Test def testSerialization(): Unit = {
    val ref = new Reflections(pkgs:_*)
    val submodels = ref.getSubTypesOf(classOf[SubmodelBase[_, _, _, _]]).toSeq
    val models = ref.getSubTypesOf(classOf[Model[_, _]]).toSeq

    val modelClasses =
      (models ++ submodels).
        filterNot { _.isInterface }.
        filterNot { c =>
          val name = c.getName
          outFilters.exists(name.matches)
        }

    if (modelClasses.isEmpty) {
      fail(s"No models found to test for Serializability in packages: ${pkgs.mkString(",")}")
    }
    else {
      debug {
        modelClasses
          .map(_.getCanonicalName)
          .mkString("Models tested for Serializability:\n\t", "\n\t", "")
      }
    }

    modelClasses.foreach { c =>
      val m = for {
        testClass  <- getTestClass(c.getCanonicalName)
        testMethod <- getTestMethod(testClass)
        method     <- ensureTestMethodIsTest(testMethod)
      } yield method

      m.left foreach fail
    }
  }

  private[this] implicit class RightMonad[L, R](e: Either[L, R]) {
    def flatMap[R1](f: R => Either[L, R1]) = e.right.flatMap(f)
    def map[R1](f: R => R1) = e.right.map(f)
  }

  private[this] def getTestClass(modelClassName: String) = {
    val testName = modelClassName + "Test"
    Try {
      Class.forName(testName)
    } map {
      Right(_)
    } getOrElse Left("No test class exists for " + modelClassName)
  }

  private[this] def getTestMethod(testClass: Class[_]) = {
    val testMethodName = "testSerialization"
    lazy val msg = s"$testMethodName doesn't exist in ${testClass.getCanonicalName}."
    Try {
      Option(testClass.getMethod(testMethodName))
    } map {
      case Some(m) => Right(m)
      case None => Left(msg)
    } getOrElse Left(msg)
  }

  private[this] def ensureTestMethodIsTest(method: Method) = {
    if (!Modifier.isPublic(method.getModifiers))
      Left(s"testSerialization in ${method.getDeclaringClass.getCanonicalName} is not public")
    if (!method.getDeclaredAnnotations.exists(_.annotationType() == classOf[Test]))
      Left(s"testSerialization in ${method.getDeclaringClass.getCanonicalName} does not have a @org.junit.Test annotation.")
    else if (method.getReturnType != classOf[Void] && method.getReturnType != classOf[Unit])
      Left(s"testSerialization in ${method.getDeclaringClass.getCanonicalName} is not a void function. It returns: ${method.getReturnType}")
    else Right(method)
  }
} 
Example 6
Source File: RowCreatorProducerTest.scala    From aloha   with MIT License 5 votes vote down vote up
package com.eharmony.aloha.dataset

import java.lang.reflect.Modifier

import com.eharmony.aloha
import com.eharmony.aloha.dataset.vw.multilabel.VwMultilabelRowCreator
import org.junit.Assert._
import org.junit.{Ignore, Test}
import org.junit.runner.RunWith
import org.junit.runners.BlockJUnit4ClassRunner

import scala.collection.JavaConversions.asScalaSet
import org.reflections.Reflections

@RunWith(classOf[BlockJUnit4ClassRunner])
class RowCreatorProducerTest {
    import RowCreatorProducerTest._

    private[this] def scanPkg = aloha.pkgName + ".dataset"

    @Test def testAllRowCreatorProducersHaveOnlyZeroArgConstructors() {
        val reflections = new Reflections(scanPkg)
        val specProdClasses = reflections.getSubTypesOf(classOf[RowCreatorProducer[_, _, _]]).toSet
        specProdClasses.foreach { clazz =>
            val cons = clazz.getConstructors
            assertTrue(s"There should only be one constructor for ${clazz.getCanonicalName}.  Found ${cons.length} constructors.", cons.length <= 1)
            cons.headOption.foreach { c =>
                if (!(WhitelistedRowCreatorProducers contains clazz)) {
                    val nParams = c.getParameterTypes.length
                    assertEquals(s"The constructor for ${clazz.getCanonicalName} should take 0 arguments.  It takes $nParams.", 0, nParams)
                }
            }
        }
    }

    
    // TODO: Report the above bug!
    @Ignore @Test def testAllRowCreatorProducersAreFinalClasses() {
        val reflections = new Reflections(scanPkg)
        val specProdClasses = reflections.getSubTypesOf(classOf[RowCreatorProducer[_, _, _]]).toSet
        specProdClasses.foreach { clazz =>
            assertTrue(s"${clazz.getCanonicalName} needs to be declared final.", Modifier.isFinal(clazz.getModifiers))
        }
    }
}

object RowCreatorProducerTest {
    private val WhitelistedRowCreatorProducers = Set[Class[_]](
        classOf[VwMultilabelRowCreator.Producer[_, _]]
    )
} 
Example 7
Source File: Cli.scala    From aloha   with MIT License 5 votes vote down vote up
package com.eharmony.aloha.cli

import java.lang.reflect.Modifier

import com.eharmony.aloha.annotate.CLI
import org.reflections.Reflections

import scala.collection.JavaConversions.asScalaSet
import com.eharmony.aloha.pkgName


object Cli {
    def main(args: Array[String]): Unit = {

        if (args.isEmpty) {
            Console.err.println("No arguments supplied. Supply one of: " + flagClassMap.keys.toVector.sorted.map("'" + _ + "'").mkString(", ") + ".")
        }
        else {
            val flag = args(0)
            if (!flagClassMap.contains(flag)) {
                Console.err.println(s"'$flag' supplied. Supply one of: " + flagClassMap.keys.toVector.sorted.map("'" + _ + "'").mkString(", ") + ".")
            }
            else {
                flagClassMap(flag).
                    getMethod("main", classOf[Array[String]]).
                    invoke(null, args.tail)
            }
        }
    }

    private[cli] lazy val cliClasses = {
        val reflections = new Reflections(pkgName)

        // We want to classes with the static forwarders, not the singleton (module) classes.
        reflections.getTypesAnnotatedWith(classOf[CLI]).toSet.asInstanceOf[Set[Class[Any]]].collect { case c if hasStaticMain(c) =>  c }
    }

    private[this] def hasStaticMain(c: Class[Any]): Boolean =
        !c.getName.endsWith("$") && Option(c.getMethod("main", classOf[Array[String]])).exists(m => Modifier.isStatic(m.getModifiers))


    private[this] lazy val flagClassMap = cliClasses.map{ case c => c.getAnnotation(classOf[CLI]).flag() -> c }.toMap
} 
Example 8
Source File: JniMethodRefs.scala    From jvm-toxcore-c   with GNU General Public License v3.0 5 votes vote down vote up
package im.tox.tox4j.impl.jni.codegen

import java.lang.reflect.Modifier

import im.tox.tox4j.impl.jni.codegen.NameConversions.cxxVarName
import im.tox.tox4j.impl.jni.codegen.cxx.Ast._
import im.tox.tox4j.impl.jni.{ ToxAvJni, ToxCoreJni, ToxCryptoJni }

object JniMethodRefs extends CodeGenerator {

  def generateNativeDecls(clazz: Class[_]): TranslationUnit = {
    clazz.getDeclaredMethods
      .filter { method =>
        Modifier.isNative(method.getModifiers) &&
          !Seq("invoke", "tox4j").exists(method.getName.startsWith)
      }
      .sortBy(method => method.getName)
      .flatMap { method =>
        Seq(
          MacroCall(FunCall(Identifier("JAVA_METHOD_REF"), Seq(Identifier(method.getName)))),
          MacroCall(FunCall(Identifier("CXX_FUNCTION_REF"), Seq(Identifier(cxxVarName(method.getName)))))
        )
      }
  }

  writeCode("ToxAv/generated/natives.h", "\n") {
    Comment(classOf[ToxAvJni].getName) +:
      generateNativeDecls(classOf[ToxAvJni])
  }

  writeCode("ToxCore/generated/natives.h", "\n") {
    Comment(classOf[ToxCoreJni].getName) +:
      generateNativeDecls(classOf[ToxCoreJni])
  }

  writeCode("ToxCrypto/generated/natives.h", "\n") {
    Comment(classOf[ToxCryptoJni].getName) +:
      generateNativeDecls(classOf[ToxCryptoJni])
  }

} 
Example 9
Source File: MethodMap.scala    From jvm-toxcore-c   with GNU General Public License v3.0 5 votes vote down vote up
package im.tox.tox4j.impl.jni

import java.lang.reflect.{ Method, Modifier }

import im.tox.tox4j.OptimisedIdOps._
import im.tox.tox4j.impl.jni.codegen.NameConversions

object MethodMap {

  private val actions = Seq("get", "set", "add", "delete")

  private def removeSelf(name: Seq[String]): Seq[String] = {
    name.headOption match {
      case Some("self") => name.drop(1)
      case _            => name
    }
  }

  private def moveActionToFront(name: Seq[String]): Seq[String] = {
    name.indexWhere(actions.contains) match {
      case -1 =>
        name
      case actionIndex =>
        name(actionIndex) +: (name.slice(0, actionIndex) ++ name.slice(actionIndex + 1, name.length))
    }
  }

  def apply(jniClass: Class[_]): Map[String, Method] = {
    jniClass
      .getDeclaredMethods.toSeq
      .filter { method =>
        Modifier.isNative(method.getModifiers) &&
          method.getName.startsWith("tox")
      }
      .map { method =>
        val expectedName = (method.getName
          |> NameConversions.cxxVarName
          |> (_.split("_").toSeq.drop(1))
          |> removeSelf
          |> moveActionToFront
          |> (_.mkString("_"))
          |> NameConversions.javaVarName)
        (expectedName, method)
      } |> { pairs => Map(pairs: _*) }
  }

} 
Example 10
Source File: UnsafeSerializer.scala    From hazelcast-scala   with Apache License 2.0 5 votes vote down vote up
package com.hazelcast.Scala.serialization

import java.lang.reflect.{ Field, Modifier }

import scala.util.{ Failure, Success, Try }

import com.hazelcast.nio.{ ObjectDataInput, ObjectDataOutput, UnsafeHelper }

import sun.misc.Unsafe

private[serialization] object UnsafeSerializer {

  private[this] val UNSAFE = Try(Unsafe.getUnsafe) match {
    case Failure(_: SecurityException) | Success(null) => UnsafeHelper.UNSAFE.ensuring(_ != null, "Unable to obtain sun.misc.Unsafe")
    case Failure(e) => throw e
    case Success(unsafe) => unsafe
  }

  private def shouldSerialize(f: Field): Boolean =
    !Modifier.isStatic(f.getModifiers) &&
      !Modifier.isTransient(f.getModifiers)

  private def collectFields(cls: Class[_]): List[Field] = {
    if (cls != null) {
      val superFields = collectFields(cls.getSuperclass)
      val thisFields = cls.getDeclaredFields.filter(shouldSerialize).sortBy(_.getName)
      thisFields.foreach(_.setAccessible(true))
      thisFields ++: superFields
    } else Nil
  }

  private[this] val fields = new ClassValue[List[Field]] {
    def computeValue(cls: Class[_]): List[Field] = collectFields(cls)
  }

  def write(out: ObjectDataOutput, any: Any): Unit = {
    fields.get(any.getClass).foreach { field =>
      out.writeObject(field.get(any))
    }
  }
  private def collectInterfaceNames(cls: Class[_]): List[String] = {
    if (cls != null) {
      cls.getInterfaces.map(_.getName) ++: collectInterfaceNames(cls.getSuperclass)
    } else Nil
  }
  def read(inp: ObjectDataInput, cls: Class[_]): Any = {
    val instance = UNSAFE.allocateInstance(cls)
    fields.get(cls).foreach { field =>
      field.set(instance, inp.readObject[Any])
    }
    instance
  }
} 
Example 11
Source File: JacksonNestedTest.scala    From guardrail   with MIT License 5 votes vote down vote up
package core.Jackson

import java.lang.reflect.Modifier
import org.scalatest.freespec.AnyFreeSpec
import org.scalatest.matchers.must.Matchers
import polymorphismNested.client.dropwizard.definitions.{ A, B, C, TestResponse }

class JacksonNestedTest extends AnyFreeSpec with Matchers {
  "Jackson nested schemas" - {
    "Should have the nested objects in the right place" in {
      new TestResponse.Builder()
        .withEnum1(A.Enum1.B)
        .withEnum2(B.Enum2.D)
        .withObj(new C.Obj.Builder().withValue("foo").build())
        .build()
    }

    "Should have nested classes as public static members" in {
      classOf[C.Obj].getModifiers & Modifier.PUBLIC mustBe Modifier.PUBLIC
      classOf[C.Obj].getModifiers & Modifier.STATIC mustBe Modifier.STATIC
    }

    "Should have nested enums as public non-static members that nonetheless reflect as static" in {
      classOf[A.Enum1].getModifiers & Modifier.PUBLIC mustBe Modifier.PUBLIC
      classOf[A.Enum1].getModifiers & Modifier.STATIC mustBe Modifier.STATIC
    }
  }
} 
Example 12
Source File: TestUtilsSuite.scala    From hail   with MIT License 5 votes vote down vote up
package is.hail

import java.io.File
import java.lang.reflect.Modifier
import java.net.URI

import breeze.linalg.{DenseMatrix, DenseVector}
import is.hail.utils.ArrayBuilder
import org.testng.annotations.{DataProvider, Test}

class TestUtilsSuite extends HailSuite {

  @Test def matrixEqualityTest() {
    val M = DenseMatrix((1d, 0d), (0d, 1d))
    val M1 = DenseMatrix((1d, 0d), (0d, 1.0001d))
    val V = DenseVector(0d, 1d)
    val V1 = DenseVector(0d, 0.5d)

    TestUtils.assertMatrixEqualityDouble(M, DenseMatrix.eye(2))
    TestUtils.assertMatrixEqualityDouble(M, M1, 0.001)
    TestUtils.assertVectorEqualityDouble(V, 2d * V1)

    intercept[Exception](TestUtils.assertVectorEqualityDouble(V, V1))
    intercept[Exception](TestUtils.assertMatrixEqualityDouble(M, M1))
  }

  @Test def constantVectorTest() {
    assert(TestUtils.isConstant(DenseVector()))
    assert(TestUtils.isConstant(DenseVector(0)))
    assert(TestUtils.isConstant(DenseVector(0, 0)))
    assert(TestUtils.isConstant(DenseVector(0, 0, 0)))
    assert(!TestUtils.isConstant(DenseVector(0, 1)))
    assert(!TestUtils.isConstant(DenseVector(0, 0, 1)))
  }

  @Test def removeConstantColsTest(): Unit = {
    val M = DenseMatrix((0, 0, 1, 1, 0),
                        (0, 1, 0, 1, 1))

    val M1 = DenseMatrix((0, 1, 0),
                         (1, 0, 1))

    assert(TestUtils.removeConstantCols(M) == M1)
  }
} 
Example 13
Source File: ScalaParameterNameDiscoverer.scala    From scala-commons   with MIT License 5 votes vote down vote up
package com.avsystem.commons
package spring

import java.lang.reflect.{Constructor, Executable, Method, Modifier}

import com.github.ghik.silencer.silent
import org.springframework.core.{JdkVersion, ParameterNameDiscoverer}

import scala.annotation.tailrec
import scala.ref.WeakReference
import scala.reflect.api.JavaUniverse
import scala.reflect.{ScalaLongSignature, ScalaSignature}

object ScalaParameterNameDiscoverer {
  final val ScalaSignatureClasses =
    List(classOf[ScalaSignature], classOf[ScalaLongSignature])

  @silent("deprecated")
  final val JdkAtLeast8 =
    JdkVersion.getMajorJavaVersion >= JdkVersion.JAVA_18

  // we don't want to keep the universe in memory forever, so we don't use scala.reflect.runtime.universe
  private var universeRef: WeakReference[JavaUniverse] = _

  private def universe: JavaUniverse = {
    universeRef.option.flatMap(_.get) match {
      case Some(result) => result
      case None =>
        val result = new scala.reflect.runtime.JavaUniverse
        universeRef = new WeakReference[JavaUniverse](result)
        result
    }
  }
}

class ScalaParameterNameDiscoverer extends ParameterNameDiscoverer {

  import ScalaParameterNameDiscoverer._

  @tailrec private def isScala(cls: Class[_]): Boolean = cls.getEnclosingClass match {
    case null => ScalaSignatureClasses.exists(ac => cls.getAnnotation(ac) != null)
    case encls => isScala(encls)
  }

  private def discoverNames(u: JavaUniverse)(executable: Executable, symbolPredicate: u.Symbol => Boolean): Array[String] = {
    import u._

    val declaringClass = executable.getDeclaringClass
    val mirror = runtimeMirror(declaringClass.getClassLoader)
    val ownerSymbol =
      if (Modifier.isStatic(executable.getModifiers)) mirror.moduleSymbol(declaringClass).moduleClass.asType
      else mirror.classSymbol(declaringClass)

    def argErasuresMatch(ms: MethodSymbol) =
      ms.paramLists.flatten.map(s => mirror.runtimeClass(s.typeSignature)) == executable.getParameterTypes.toList

    def paramNames(ms: MethodSymbol) =
      ms.paramLists.flatten.map(_.name.toString).toArray

    ownerSymbol.toType.members
      .find(s => symbolPredicate(s) && argErasuresMatch(s.asMethod))
      .map(s => paramNames(s.asMethod))
      .orNull
  }

  def getParameterNames(ctor: Constructor[_]): Array[String] =
    if (JdkAtLeast8 && ctor.getParameters.forall(_.isNamePresent))
      ctor.getParameters.map(_.getName)
    else if (isScala(ctor.getDeclaringClass))
      discoverNames(universe)(ctor, s => s.isConstructor)
    else null

  def getParameterNames(method: Method): Array[String] = {
    val declaringCls = method.getDeclaringClass
    if (JdkAtLeast8 && method.getParameters.forall(_.isNamePresent))
      method.getParameters.map(_.getName)
    else if (isScala(declaringCls)) {
      // https://github.com/scala/bug/issues/10650
      val forStaticForwarder =
        if (Modifier.isStatic(method.getModifiers))
          Class.forName(declaringCls.getName + "$", false, declaringCls.getClassLoader)
            .recoverToOpt[ClassNotFoundException]
            .flatMap(_.getMethod(method.getName, method.getParameterTypes: _*).recoverToOpt[NoSuchMethodException])
            .map(getParameterNames)
        else
          Opt.Empty
      forStaticForwarder.getOrElse(
        discoverNames(universe)(method, s => s.isMethod && s.name.toString == method.getName))
    }
    else null
  }
} 
Example 14
Source File: ClassUtils.scala    From ohara   with Apache License 2.0 5 votes vote down vote up
package oharastream.ohara.it.code

import java.io.FileInputStream
import java.lang.reflect.Modifier
import java.util.jar.JarInputStream
import java.util.regex.Pattern

import org.junit.Test

import scala.jdk.CollectionConverters._

private[code] object ClassUtils {
  
  def classesInProductionScope(): Seq[Class[_]] = allClasses(n => !n.contains("tests.jar"))

  def allClasses(fileNameFilter: String => Boolean): Seq[Class[_]] = {
    val classLoader = ClassLoader.getSystemClassLoader
    val path        = "oharastream/ohara"
    val pattern     = Pattern.compile("^file:(.+\\.jar)!/" + path + "$")
    val urls        = classLoader.getResources(path)
    urls.asScala
      .map(url => pattern.matcher(url.getFile))
      .filter(_.find())
      .map(_.group(1))
      .filter(fileNameFilter)
      .flatMap { f =>
        val jarInput = new JarInputStream(new FileInputStream(f))
        try Iterator
          .continually(jarInput.getNextJarEntry)
          .takeWhile(_ != null)
          .map(_.getName)
          .toArray
          .filter(_.endsWith(".class"))
          .map(_.replace('/', '.'))
          .map(className => className.substring(0, className.length - ".class".length))
          .map(Class.forName)
        finally jarInput.close()
      }
      .toSeq
  }
} 
Example 15
Source File: ActorSystemSpec.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.persistence

import java.lang.reflect.Modifier

import akka.actor.ActorSystem
import akka.actor.CoordinatedShutdown
import akka.actor.setup.ActorSystemSetup
import akka.event.Logging
import akka.event.LoggingAdapter
import akka.testkit.ImplicitSender
import akka.testkit.TestKit
import com.typesafe.config.Config
import com.typesafe.config.ConfigFactory
import org.scalactic.CanEqual
import org.scalactic.TypeCheckedTripleEquals
import org.scalatest.BeforeAndAfterAll
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike

object ActorSystemSpec {
  // taken from akka-testkit's AkkaSpec
  private def testNameFromCallStack(classToStartFrom: Class[_]): String = {

    def isAbstractClass(className: String): Boolean = {
      try {
        Modifier.isAbstract(Class.forName(className).getModifiers)
      } catch {
        case _: Throwable => false // yes catch everything, best effort check
      }
    }

    val startFrom = classToStartFrom.getName
    val filteredStack = Thread.currentThread.getStackTrace.iterator
      .map(_.getClassName)
      // drop until we find the first occurrence of classToStartFrom
      .dropWhile(!_.startsWith(startFrom))
      // then continue to the next entry after classToStartFrom that makes sense
      .dropWhile {
        case `startFrom`                            => true
        case str if str.startsWith(startFrom + "$") => true // lambdas inside startFrom etc
        case str if isAbstractClass(str)            => true
        case _                                      => false
      }

    if (filteredStack.isEmpty)
      throw new IllegalArgumentException(s"Couldn't find [${classToStartFrom.getName}] in call stack")

    // sanitize for actor system name
    scrubActorSystemName(filteredStack.next())
  }

  // taken from akka-testkit's AkkaSpec
  
  private def scrubActorSystemName(name: String): String = {
    name
      .replaceFirst("""^.*\.""", "")  // drop package name
      .replaceAll("""\$\$?\w+""", "") // drop scala anonymous functions/classes
      .replaceAll("[^a-zA-Z_0-9]", "_")
  }
}

abstract class ActorSystemSpec(actorSystemFactory: () => ActorSystem)
    extends TestKit(actorSystemFactory())
    with AnyWordSpecLike
    with Matchers
    with BeforeAndAfterAll
    with TypeCheckedTripleEquals
    with ImplicitSender {

  def this(testName: String, config: Config) =
    this(() => ActorSystem(testName, config))

  def this(config: Config) = this(ActorSystemSpec.testNameFromCallStack(classOf[ActorSystemSpec]), config)

  def this(setup: ActorSystemSetup) =
    this(() => ActorSystem(ActorSystemSpec.testNameFromCallStack(classOf[ActorSystemSpec]), setup))

  def this() = this(ConfigFactory.empty())

  override def afterAll(): Unit = {
    shutdown()
    super.afterAll()
  }

  val log: LoggingAdapter                      = Logging(system, this.getClass)
  val coordinatedShutdown: CoordinatedShutdown = CoordinatedShutdown(system)

  // for ScalaTest === compare of Class objects
  implicit def classEqualityConstraint[A, B]: CanEqual[Class[A], Class[B]] =
    new CanEqual[Class[A], Class[B]] {
      def areEqual(a: Class[A], b: Class[B]) = a == b
    }
} 
Example 16
Source File: PersistenceSpec.scala    From lagom   with Apache License 2.0 5 votes vote down vote up
package com.lightbend.lagom.persistence

import java.lang.reflect.Modifier

object PersistenceSpec {
  // taken from akka-testkit's AkkaSpec
  private[lagom] def testNameFromCallStack(classToStartFrom: Class[_]): String = {

    def isAbstractClass(className: String): Boolean = {
      try {
        Modifier.isAbstract(Class.forName(className).getModifiers)
      } catch {
        case _: Throwable => false // yes catch everything, best effort check
      }
    }

    val startFrom = classToStartFrom.getName
    val filteredStack = Thread.currentThread.getStackTrace.iterator
      .map(_.getClassName)
      // drop until we find the first occurrence of classToStartFrom
      .dropWhile(!_.startsWith(startFrom))
      // then continue to the next entry after classToStartFrom that makes sense
      .dropWhile {
        case `startFrom`                            => true
        case str if str.startsWith(startFrom + "$") => true // lambdas inside startFrom etc
        case str if isAbstractClass(str)            => true
        case _                                      => false
      }

    if (filteredStack.isEmpty)
      throw new IllegalArgumentException(s"Couldn't find [${classToStartFrom.getName}] in call stack")

    // sanitize for actor system name
    scrubActorSystemName(filteredStack.next())
  }

  // taken from akka-testkit's AkkaSpec
  
  private def scrubActorSystemName(name: String): String = {
    name
      .replaceFirst("""^.*\.""", "")  // drop package name
      .replaceAll("""\$\$?\w+""", "") // drop scala anonymous functions/classes
      .replaceAll("[^a-zA-Z_0-9]", "_")
  }
} 
Example 17
Source File: Module.scala    From Cortex   with GNU Affero General Public License v3.0 5 votes vote down vote up
package org.thp.cortex

import java.lang.reflect.Modifier

import com.google.inject.AbstractModule
import net.codingwell.scalaguice.{ScalaModule, ScalaMultibinder}
import play.api.libs.concurrent.AkkaGuiceSupport
import play.api.{Configuration, Environment, Logger, Mode}
import scala.collection.JavaConverters._

import com.google.inject.name.Names
import org.reflections.Reflections
import org.reflections.scanners.SubTypesScanner
import org.reflections.util.ConfigurationBuilder
import org.thp.cortex.models.{AuditedModel, Migration}
import org.thp.cortex.services._

import org.elastic4play.models.BaseModelDef
import org.elastic4play.services.auth.MultiAuthSrv
import org.elastic4play.services.{UserSrv ⇒ EUserSrv, AuthSrv, MigrationOperations}
import org.thp.cortex.controllers.{AssetCtrl, AssetCtrlDev, AssetCtrlProd}
import services.mappers.{MultiUserMapperSrv, UserMapper}

class Module(environment: Environment, configuration: Configuration) extends AbstractModule with ScalaModule with AkkaGuiceSupport {

  private lazy val logger = Logger(s"module")

  override def configure(): Unit = {
    val modelBindings        = ScalaMultibinder.newSetBinder[BaseModelDef](binder)
    val auditedModelBindings = ScalaMultibinder.newSetBinder[AuditedModel](binder)
    val reflectionClasses = new Reflections(
      new ConfigurationBuilder()
        .forPackages("org.elastic4play")
        .addClassLoader(getClass.getClassLoader)
        .addClassLoader(environment.getClass.getClassLoader)
        .forPackages("org.thp.cortex")
        .setExpandSuperTypes(false)
        .setScanners(new SubTypesScanner(false))
    )

    reflectionClasses
      .getSubTypesOf(classOf[BaseModelDef])
      .asScala
      .filterNot(c ⇒ Modifier.isAbstract(c.getModifiers))
      .foreach { modelClass ⇒
        logger.info(s"Loading model $modelClass")
        modelBindings.addBinding.to(modelClass)
        if (classOf[AuditedModel].isAssignableFrom(modelClass)) {
          auditedModelBindings.addBinding.to(modelClass.asInstanceOf[Class[AuditedModel]])
        }
      }

    val authBindings = ScalaMultibinder.newSetBinder[AuthSrv](binder)
    reflectionClasses
      .getSubTypesOf(classOf[AuthSrv])
      .asScala
      .filterNot(c ⇒ Modifier.isAbstract(c.getModifiers) || c.isMemberClass)
      .filterNot(c ⇒ c == classOf[MultiAuthSrv] || c == classOf[CortexAuthSrv])
      .foreach { authSrvClass ⇒
        logger.info(s"Loading authentication module $authSrvClass")
        authBindings.addBinding.to(authSrvClass)
      }

    val ssoMapperBindings = ScalaMultibinder.newSetBinder[UserMapper](binder)
    reflectionClasses
      .getSubTypesOf(classOf[UserMapper])
      .asScala
      .filterNot(c ⇒ Modifier.isAbstract(c.getModifiers) || c.isMemberClass)
      .filterNot(c ⇒ c == classOf[MultiUserMapperSrv])
      .foreach(mapperCls ⇒ ssoMapperBindings.addBinding.to(mapperCls))

    if (environment.mode == Mode.Prod)
      bind[AssetCtrl].to[AssetCtrlProd]
    else
      bind[AssetCtrl].to[AssetCtrlDev]

    bind[EUserSrv].to[UserSrv]
    bind[Int].annotatedWith(Names.named("databaseVersion")).toInstance(models.modelVersion)
    bind[UserMapper].to[MultiUserMapperSrv]

    bind[AuthSrv].to[CortexAuthSrv]
    bind[MigrationOperations].to[Migration]
    bindActor[AuditActor]("audit")
  }
} 
Example 18
Source File: LazyApplicationSuite.scala    From darwin   with Apache License 2.0 5 votes vote down vote up
package it.agilelab.darwin.app.mock

import java.lang.reflect.Modifier
import java.nio.ByteOrder

import com.typesafe.config.{Config, ConfigFactory}
import it.agilelab.darwin.annotations.AvroSerde
import it.agilelab.darwin.app.mock.classes.{MyClass, MyNestedClass, NewClass, OneField}
import it.agilelab.darwin.common.{Connector, ConnectorFactory}
import it.agilelab.darwin.manager.{AvroSchemaManager, LazyAvroSchemaManager}
import org.apache.avro.{Schema, SchemaNormalization}
import org.apache.avro.reflect.ReflectData
import org.reflections.Reflections

import it.agilelab.darwin.common.compat._
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

class BigEndianLazyApplicationSuite extends LazyApplicationSuite(ByteOrder.BIG_ENDIAN)

class LittleEndianLazyApplicationSuite extends LazyApplicationSuite(ByteOrder.LITTLE_ENDIAN)

abstract class LazyApplicationSuite(endianness: ByteOrder) extends AnyFlatSpec with Matchers {

  val config: Config = ConfigFactory.load()
  val connector: Connector = ConnectorFactory.connector(config)
  val manager: AvroSchemaManager = new LazyAvroSchemaManager(connector, endianness)

  "LazyAvroSchemaManager" should "not fail after the initialization" in {
    val schemas: Seq[Schema] = Seq(SchemaReader.readFromResources("MyNestedClass.avsc"))
    assert(manager.registerAll(schemas).size == 1)
  }

  it should "load all existing schemas and register a new one" in {
    val schemas: Seq[Schema] = Seq(SchemaReader.readFromResources("MyNestedClass.avsc"))
    manager.getSchema(0L)

    manager.registerAll(schemas)

    val id = manager.getId(schemas.head)
    assert(manager.getSchema(id).isDefined)
    assert(schemas.head == manager.getSchema(id).get)
  }

  it should "get all previously registered schemas" in {
    val schema: Schema = SchemaReader.readFromResources("MyNestedClass.avsc")
    val schema0 = manager.getSchema(0L)
    val schema1 = manager.getSchema(1L)
    assert(schema0.isDefined)
    assert(schema1.isDefined)
    assert(schema0.get != schema1.get)
    assert(schema != schema0.get)
    assert(schema != schema1.get)
  }

  it should "generate all schemas for all the annotated classes with @AvroSerde" in {
    val reflections = new Reflections("it.agilelab.darwin.app.mock.classes")

    val oneFieldSchema = ReflectData.get().getSchema(classOf[OneField]).toString
    val myNestedSchema = ReflectData.get().getSchema(classOf[MyNestedClass]).toString
    val myClassSchema = ReflectData.get().getSchema(classOf[MyClass]).toString

    val annotationClass: Class[AvroSerde] = classOf[AvroSerde]
    val classes = reflections.getTypesAnnotatedWith(annotationClass).toScala.toSeq
      .filter(c => !c.isInterface && !Modifier.isAbstract(c.getModifiers))
    val schemas = classes.map(c => ReflectData.get().getSchema(Class.forName(c.getName)).toString)
    Seq(oneFieldSchema, myClassSchema, myNestedSchema) should contain theSameElementsAs schemas
  }

  it should "reload all schemas from the connector" in {
    val newSchema = ReflectData.get().getSchema(classOf[NewClass])
    val newId = SchemaNormalization.parsingFingerprint64(newSchema)
    assert(manager.getSchema(newId).isEmpty)

    connector.insert(Seq(newId -> newSchema))
    assert(manager.getSchema(newId).isDefined)
    assert(manager.getSchema(newId).get == newSchema)
  }
} 
Example 19
Source File: CachedLazyApplicationSuite.scala    From darwin   with Apache License 2.0 5 votes vote down vote up
package it.agilelab.darwin.app.mock

import java.lang.reflect.Modifier
import java.nio.ByteOrder

import com.typesafe.config.{Config, ConfigFactory}
import it.agilelab.darwin.annotations.AvroSerde
import it.agilelab.darwin.app.mock.classes.{MyClass, MyNestedClass, NewClass, OneField}
import it.agilelab.darwin.common.{Connector, ConnectorFactory}
import it.agilelab.darwin.manager.{AvroSchemaManager, CachedLazyAvroSchemaManager}
import org.apache.avro.{Schema, SchemaNormalization}
import org.apache.avro.reflect.ReflectData
import org.reflections.Reflections

import it.agilelab.darwin.common.compat._
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

class BigEndianCachedLazyApplicationSuite extends CachedLazyApplicationSuite(ByteOrder.BIG_ENDIAN)

class LittleEndianCachedLazyApplicationSuite extends CachedLazyApplicationSuite(ByteOrder.LITTLE_ENDIAN)

abstract class CachedLazyApplicationSuite(val endianness: ByteOrder) extends AnyFlatSpec with Matchers {

  val config: Config = ConfigFactory.load()
  val connector: Connector = ConnectorFactory.connector(config)
  val manager: AvroSchemaManager = new CachedLazyAvroSchemaManager(connector, endianness)

  "CachedLazyAvroSchemaManager" should "not fail after the initialization" in {
    val schemas: Seq[Schema] = Seq(SchemaReader.readFromResources("MyNestedClass.avsc"))
    assert(manager.registerAll(schemas).size == 1)
  }

  it should "load all existing schemas and register a new one" in {
    val schemas: Seq[Schema] = Seq(SchemaReader.readFromResources("MyNestedClass.avsc"))
    manager.getSchema(0L)

    manager.registerAll(schemas)

    val id = manager.getId(schemas.head)
    assert(manager.getSchema(id).isDefined)
    assert(schemas.head == manager.getSchema(id).get)
  }

  it should "get all previously registered schemas" in {
    val schema: Schema = SchemaReader.readFromResources("MyNestedClass.avsc")
    val schema0 = manager.getSchema(0L)
    val schema1 = manager.getSchema(1L)
    assert(schema0.isDefined)
    assert(schema1.isDefined)
    assert(schema0.get != schema1.get)
    assert(schema != schema0.get)
    assert(schema != schema1.get)
  }

  it should "generate all schemas for all the annotated classes with @AvroSerde" in {
    val reflections = new Reflections("it.agilelab.darwin.app.mock.classes")

    val oneFieldSchema = ReflectData.get().getSchema(classOf[OneField]).toString
    val myNestedSchema = ReflectData.get().getSchema(classOf[MyNestedClass]).toString
    val myClassSchema = ReflectData.get().getSchema(classOf[MyClass]).toString

    val annotationClass: Class[AvroSerde] = classOf[AvroSerde]
    val classes = reflections.getTypesAnnotatedWith(annotationClass).toScala.toSeq
      .filter(c => !c.isInterface && !Modifier.isAbstract(c.getModifiers))
    val schemas = classes.map(c => ReflectData.get().getSchema(Class.forName(c.getName)).toString)
    Seq(oneFieldSchema, myClassSchema, myNestedSchema) should contain theSameElementsAs schemas
  }

  it should "reload all schemas from the connector" in {
    val newSchema = ReflectData.get().getSchema(classOf[NewClass])
    val newId = SchemaNormalization.parsingFingerprint64(newSchema)
    assert(manager.getSchema(newId).isEmpty)

    connector.insert(Seq(newId -> newSchema))
    assert(manager.getSchema(newId).isDefined)
    assert(manager.getSchema(newId).get == newSchema)
  }
} 
Example 20
Source File: CachedEagerApplicationSuite.scala    From darwin   with Apache License 2.0 5 votes vote down vote up
package it.agilelab.darwin.app.mock

import java.lang.reflect.Modifier
import java.nio.ByteOrder

import com.typesafe.config.{Config, ConfigFactory}
import it.agilelab.darwin.annotations.AvroSerde
import it.agilelab.darwin.app.mock.classes.{MyClass, MyNestedClass, NewClass, OneField}
import it.agilelab.darwin.common.{Connector, ConnectorFactory}
import it.agilelab.darwin.manager.{AvroSchemaManager, CachedEagerAvroSchemaManager}
import org.apache.avro.{Schema, SchemaNormalization}
import org.apache.avro.reflect.ReflectData
import org.reflections.Reflections

import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import it.agilelab.darwin.common.compat._

class BigEndianCachedEagerApplicationSuite extends CachedEagerApplicationSuite(ByteOrder.BIG_ENDIAN)

class LittleEndianCachedEagerApplicationSuite extends CachedEagerApplicationSuite(ByteOrder.LITTLE_ENDIAN)

abstract class CachedEagerApplicationSuite(val endianness: ByteOrder) extends AnyFlatSpec with Matchers {

  val config: Config = ConfigFactory.load()
  val connector: Connector = ConnectorFactory.connector(config)
  val manager: AvroSchemaManager = new CachedEagerAvroSchemaManager(connector, endianness)

  "CachedEagerAvroSchemaManager" should "not fail after the initialization" in {
    val schemas: Seq[Schema] = Seq(SchemaReader.readFromResources("MyNestedClass.avsc"))
    assert(manager.registerAll(schemas).size == 1)
  }

  it should "load all existing schemas and register a new one" in {
    val schemas: Seq[Schema] = Seq(SchemaReader.readFromResources("MyNestedClass.avsc"))
    manager.getSchema(0L)

    manager.registerAll(schemas)

    val id = manager.getId(schemas.head)
    assert(manager.getSchema(id).isDefined)
    assert(schemas.head == manager.getSchema(id).get)
  }

  it should "get all previously registered schemas" in {
    val schema: Schema = SchemaReader.readFromResources("MyNestedClass.avsc")
    val schema0 = manager.getSchema(0L)
    val schema1 = manager.getSchema(1L)
    assert(schema0.isDefined)
    assert(schema1.isDefined)
    assert(schema0.get != schema1.get)
    assert(schema != schema0.get)
    assert(schema != schema1.get)
  }

  it should "generate all schemas for all the annotated classes with @AvroSerde" in {
    val reflections = new Reflections("it.agilelab.darwin.app.mock.classes")

    val oneFieldSchema = ReflectData.get().getSchema(classOf[OneField]).toString
    val myNestedSchema = ReflectData.get().getSchema(classOf[MyNestedClass]).toString
    val myClassSchema = ReflectData.get().getSchema(classOf[MyClass]).toString

    val annotationClass: Class[AvroSerde] = classOf[AvroSerde]
    val classes = reflections.getTypesAnnotatedWith(annotationClass).toScala.toSeq
      .filter(c => !c.isInterface && !Modifier.isAbstract(c.getModifiers))
    val schemas = classes.map(c => ReflectData.get().getSchema(Class.forName(c.getName)).toString)
    Seq(oneFieldSchema, myClassSchema, myNestedSchema) should contain theSameElementsAs schemas
  }

  it should "reload all schemas from the connector" in {
    val newSchema = ReflectData.get().getSchema(classOf[NewClass])
    val newId = SchemaNormalization.parsingFingerprint64(newSchema)
    assert(manager.getSchema(newId).isEmpty)

    connector.insert(Seq(newId -> newSchema))
    assert(manager.getSchema(newId).isEmpty)

    manager.reload()
    assert(manager.getSchema(newId).isDefined)
    assert(manager.getSchema(newId).get == newSchema)
  }

} 
Example 21
Source File: HydraComponentLoader.scala    From hydra   with Apache License 2.0 5 votes vote down vote up
package hydra.ingest.bootstrap

import java.lang.reflect.Modifier

import com.pluralsight.hydra.reflect.DoNotScan
import hydra.common.config.ConfigSupport
import hydra.common.logging.LoggingAdapter
import hydra.core.ingest.Ingestor
import hydra.core.transport.Transport

import scala.collection.JavaConverters._


trait HydraComponentLoader {

  def ingestors: Seq[Class[_ <: Ingestor]]

  def transports: Seq[Class[_ <: Transport]]
}

object ClasspathHydraComponentLoader
    extends HydraComponentLoader
    with ConfigSupport
    with LoggingAdapter {

  import hydra.core.bootstrap.ReflectionsWrapper._

  override lazy val ingestors = reflections
    .getSubTypesOf(classOf[Ingestor])
    .asScala
    .filterNot(c => Modifier.isAbstract(c.getModifiers))
    .filterNot(c => c.isAnnotationPresent(classOf[DoNotScan]))
    .toSeq

  override lazy val transports = reflections
    .getSubTypesOf(classOf[Transport])
    .asScala
    .filterNot(c => Modifier.isAbstract(c.getModifiers))
    .filterNot(c => c.isAnnotationPresent(classOf[DoNotScan]))
    .toSeq

} 
Example 22
Source File: ActorFactory.scala    From hydra   with Apache License 2.0 5 votes vote down vote up
package hydra.ingest.bootstrap

import java.lang.reflect.Modifier

import akka.actor.Props
import com.pluralsight.hydra.reflect.DoNotScan
import hydra.common.config.ConfigSupport
import hydra.common.reflect.ReflectionUtils
import hydra.core.bootstrap.{ReflectionsWrapper, ServiceProvider}

import scala.util.Try

object ActorFactory extends ConfigSupport {

  import ReflectionsWrapper._

  import scala.collection.JavaConverters._

  def getActors(): Seq[(String, Props)] = {
    val serviceProviders = scanFor(classOf[ServiceProvider])
    serviceProviders.flatMap { clz =>
      Try(ReflectionUtils.getObjectInstance(clz))
        .map(_.services)
        .getOrElse(clz.newInstance().services)
    }
  }

  private def scanFor[T](clazz: Class[T]): Seq[Class[_ <: T]] =
    reflections
      .getSubTypesOf(clazz)
      .asScala
      .filterNot(c => Modifier.isAbstract(c.getModifiers))
      .filterNot(c => c.isAnnotationPresent(classOf[DoNotScan]))
      .toSeq
} 
Example 23
Source File: SerializerSpecHelper.scala    From BigDL   with Apache License 2.0 5 votes vote down vote up
package com.intel.analytics.bigdl.utils.serializer

import java.io.{File}
import java.lang.reflect.Modifier

import com.intel.analytics.bigdl.nn.abstractnn.{AbstractModule, Activity}
import com.intel.analytics.bigdl.nn.ops.{Exp => ExpOps, Pow => PowOps, Select => SelectOps, Sum => SumOps, Tile => TileOps}
import com.intel.analytics.bigdl.nn.tf.{DecodeGif => DecodeGifOps, DecodeJpeg => DecodeJpegOps, DecodePng => DecodePngOps, DecodeRaw => DecodeRawOps}
import com.intel.analytics.bigdl.utils.RandomGenerator.RNG
import com.intel.analytics.bigdl.utils.tf.loaders.{Pack => _}
import com.intel.analytics.bigdl.utils.{Shape => KShape}
import org.reflections.Reflections
import org.reflections.scanners.SubTypesScanner
import org.reflections.util.{ClasspathHelper, ConfigurationBuilder, FilterBuilder}
import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}

import scala.collection.JavaConverters._
import scala.collection.mutable


abstract class SerializerSpecHelper extends FlatSpec with Matchers with BeforeAndAfterAll{

  val postFix = "bigdl"
  val excludedClass = new mutable.HashSet[String]()
  val excludedPackage = new mutable.HashSet[String]()

  private val expected = new mutable.HashSet[String]()
  val tested = new mutable.HashSet[String]()

  private var executedCount = 0

  protected def getPackage(): String = ""

  protected def addExcludedClass(): Unit = {}

  protected def addExcludedPackage(): Unit = {}

  protected def getExpected(): mutable.Set[String] = expected

  override protected def beforeAll() = {
    addExcludedClass
    addExcludedPackage
    val filterBuilder = new FilterBuilder()
    excludedPackage.foreach(filterBuilder.excludePackage(_))
    val reflections = new Reflections(new ConfigurationBuilder()
      .filterInputsBy(filterBuilder)
      .setUrls(ClasspathHelper.forPackage(getPackage()))
      .setScanners(new SubTypesScanner()))
    val subTypes = reflections.getSubTypesOf(classOf[AbstractModule[_, _, _]])
      .asScala.filter(sub => !Modifier.isAbstract(sub.getModifiers)).
      filter(sub => !excludedClass.contains(sub.getName))
    subTypes.foreach(sub => expected.add(sub.getName))
  }

  protected def runSerializationTest(module : AbstractModule[_, _, Float],
                                   input : Activity, cls: Class[_] = null) : Unit = {
    runSerializationTestWithMultiClass(module, input,
      if (cls == null) Array(module.getClass) else Array(cls))
  }

  protected def runSerializationTestWithMultiClass(module : AbstractModule[_, _, Float],
      input : Activity, classes: Array[Class[_]]) : Unit = {
    val name = module.getName
    val serFile = File.createTempFile(name, postFix)
    val originForward = module.evaluate().forward(input)

    ModulePersister.saveToFile[Float](serFile.getAbsolutePath, null, module.evaluate(), true)
    RNG.setSeed(1000)
    val loadedModule = ModuleLoader.loadFromFile[Float](serFile.getAbsolutePath)

    val afterLoadForward = loadedModule.forward(input)

    if (serFile.exists) {
      serFile.delete
    }

    afterLoadForward should be (originForward)
    classes.foreach(cls => {
      if (getExpected.contains(cls.getName)) {
        tested.add(cls.getName)
      }
    })
  }


  override protected def afterAll() = {
    println(s"total ${getExpected.size}, remaining ${getExpected.size - tested.size}")
    tested.filter(!getExpected.contains(_)).foreach(t => {
      println(s"$t do not need to be tested")
    })
    getExpected.foreach(exp => {
      require(tested.contains(exp), s" $exp not included in the test!")
    })
  }
} 
Example 24
Source File: Reflect.scala    From nanotest-strawman   with Apache License 2.0 5 votes vote down vote up
package verify.internal

import java.lang.reflect.Modifier

object Reflect {
  def loadModule(name: String, loader: ClassLoader): Any = {
    load(name + "$", loader).filter(isModuleClass) match {
      case Some(runtimeClass) =>
        try {
          runtimeClass.getField("MODULE$").get(null)
        } catch {
          case e: java.lang.ExceptionInInitializerError =>
            val cause = e.getCause
            if (cause == null) throw e
            else throw cause
        }
      case _ => throw new ClassNotFoundException(name)
    }
  }

  private def isModuleClass(clazz: Class[_]): Boolean = {
    try {
      val fld = clazz.getField("MODULE$")
      clazz.getName.endsWith("$") && (fld.getModifiers & Modifier.STATIC) != 0
    } catch {
      case _: NoSuchFieldException => false
    }
  }

  private def load(fqcn: String, loader: ClassLoader): Option[Class[_]] = {
    try {
      
      val clazz = Class.forName(fqcn, false, loader)
      Some(clazz)
    } catch {
      case _: ClassNotFoundException => None
    }
  }
} 
Example 25
Source File: ReflectionUtils.scala    From ohara   with Apache License 2.0 5 votes vote down vote up
package oharastream.ohara.configurator

import java.lang.reflect.Modifier
import com.typesafe.scalalogging.Logger
import oharastream.ohara.client.configurator.FileInfoApi.ClassInfo
import oharastream.ohara.common.setting.WithDefinitions
import oharastream.ohara.kafka.connector.{RowSinkConnector, RowSourceConnector}
import org.reflections.Reflections
import org.reflections.util.{ClasspathHelper, ConfigurationBuilder}

import scala.jdk.CollectionConverters._
object ReflectionUtils {
  private[this] val LOG = Logger(ReflectionUtils.getClass)

  
  lazy val localConnectorDefinitions: Seq[ClassInfo] =
    new Reflections(
      new ConfigurationBuilder()
      // we ought to define urls manually since Reflections does not work on java 11
      // It can't find correct urls without pre-defined urls.
        .setUrls(ClasspathHelper.forJavaClassPath)
    ).getSubTypesOf(classOf[WithDefinitions])
      .asScala
      .toSeq
      .filter(
        clz => classOf[RowSourceConnector].isAssignableFrom(clz) || classOf[RowSinkConnector].isAssignableFrom(clz)
      )
      // the abstract class is not instantiable.
      .filterNot(clz => Modifier.isAbstract(clz.getModifiers))
      .flatMap { clz =>
        try Some((clz.getName, clz.getDeclaredConstructor().newInstance().settingDefinitions().values().asScala.toSeq))
        catch {
          case e: Throwable =>
            LOG.error(s"failed to instantiate ${clz.getName}", e)
            None
        }
      }
      .map {
        case (className, definitions) =>
          ClassInfo(
            className = className,
            settingDefinitions = definitions
          )
      }
}