java.lang.reflect.Method Scala Examples

The following examples show how to use java.lang.reflect.Method. 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: 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 2
Source File: AttachingHostProxy.scala    From ncdbg   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package com.programmaticallyspeaking.ncd.nashorn

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

import com.programmaticallyspeaking.ncd.boot.{Broker, BrokerConnection}
import org.slf4s.Logging

import scala.concurrent.Await
import scala.concurrent.duration.FiniteDuration

class AttachingHostProxy(broker: Broker, connectionTimeout: FiniteDuration) {

  def createHost(): NashornScriptHost = {
    val clazz = classOf[NashornScriptHost]
    java.lang.reflect.Proxy.newProxyInstance(clazz.getClassLoader, Array(clazz), new Handler).asInstanceOf[NashornScriptHost]
  }

  class Handler extends InvocationHandler with Logging {

    private var brokerConnection: Option[BrokerConnection] = None
    private object connectLock

    override def invoke(proxy: scala.Any, method: Method, args: Array[AnyRef]): AnyRef = {

      brokerConnection match {
        case Some(connection) =>
          val targetHost = connection.host
          val result = method.invoke(targetHost, args: _*)

          if (method.getName == "reset") {
            log.info("Detaching from target debugger")
            connection.disconnect()
            brokerConnection = None
          }

          result

        case None =>
          if (method.getName == "reset") {
            log.warn("Ignoring reset call when there is no connection!")
            return null
          }

          connectFirstThen { connection =>
            val targetHost = connection.host
            method.invoke(targetHost, args: _*)
          }
      }

    }

    private def connectFirstThen(f: BrokerConnection => AnyRef): AnyRef = {
      if (brokerConnection.isEmpty) {
        connectLock.synchronized {
          if (brokerConnection.isEmpty) {
            log.info("Attaching to debug target...")
            val futureConnection = broker.connect({
              _ =>
                // Do we need different handling depending on error or not?
                brokerConnection.foreach(_.disconnect())
                brokerConnection = None
            })
            val connection = Await.result(futureConnection, connectionTimeout)
            brokerConnection = Some(connection)
          }
        }
      }
      f(brokerConnection.get)
    }
  }
} 
Example 3
Source File: LAPACK.scala    From hail   with MIT License 5 votes vote down vote up
package is.hail.linalg

import java.lang.reflect.Method

import com.sun.jna.{FunctionMapper, Library, Native, NativeLibrary, Pointer}
import com.sun.jna.ptr.{DoubleByReference, IntByReference}

import scala.util.{Failure, Success, Try}
import is.hail.utils._

class UnderscoreFunctionMapper extends FunctionMapper {
  override def getFunctionName(library: NativeLibrary, method: Method): String = {
    method.getName() + "_"
  }
}

object LAPACK {
  lazy val libraryInstance = {
    val standard = Native.loadLibrary("lapack", classOf[LAPACKLibrary]).asInstanceOf[LAPACKLibrary]

    versionTest(standard) match {
      case Success(version) =>
        log.info(s"Imported LAPACK version ${version} with standard names")
        standard
      case Failure(exception) =>
        val underscoreAfterMap = new java.util.HashMap[String, FunctionMapper]()
        underscoreAfterMap.put(Library.OPTION_FUNCTION_MAPPER, new UnderscoreFunctionMapper)
        val underscoreAfter = Native.loadLibrary("lapack", classOf[LAPACKLibrary], underscoreAfterMap).asInstanceOf[LAPACKLibrary]
        versionTest(underscoreAfter) match {
          case Success(version) =>
            log.info(s"Imported LAPACK version ${version} with underscore names")
            underscoreAfter
          case Failure(exception) =>
            throw exception
        }
    }
  }

  def dgeqrf(M: Int, N: Int, A: Long, LDA: Int, TAU: Long, WORK: Long, LWORK: Int): Int = {
    val mInt = new IntByReference(M)
    val nInt = new IntByReference(N)
    val LDAInt = new IntByReference(LDA)
    val LWORKInt = new IntByReference(LWORK)
    val infoInt = new IntByReference(1)
    libraryInstance.dgeqrf(mInt, nInt, A, LDAInt, TAU, WORK, LWORKInt, infoInt)
    infoInt.getValue()
  }

  def dorgqr(M: Int, N: Int, K: Int, A: Long, LDA: Int, TAU: Long, WORK: Long, LWORK: Int): Int = {
    val mInt = new IntByReference(M)
    val nInt = new IntByReference(N)
    val kInt = new IntByReference(K)
    val LDAInt = new IntByReference(LDA)
    val LWORKInt = new IntByReference(LWORK)
    val infoInt = new IntByReference(1)
    libraryInstance.dorgqr(mInt, nInt, kInt, A, LDAInt, TAU, WORK, LWORKInt, infoInt)
    infoInt.getValue()
  }

  private def versionTest(libInstance: LAPACKLibrary): Try[String] = {
    val major = new IntByReference()
    val minor = new IntByReference()
    val patch = new IntByReference()

    TryAll {
      libInstance.ilaver(major, minor, patch)
      s"${major.getValue}.${minor.getValue}.${patch.getValue}"
    }
  }
}

trait LAPACKLibrary extends Library {
  def dgeqrf(M: IntByReference, N: IntByReference, A: Long, LDA: IntByReference, TAU: Long, WORK: Long, LWORK: IntByReference, INFO: IntByReference)
  def dorgqr(M: IntByReference, N: IntByReference, K: IntByReference, A: Long, LDA: IntByReference, TAU: Long, WORK: Long, LWORK: IntByReference, Info: IntByReference)
  def ilaver(MAJOR: IntByReference, MINOR: IntByReference, PATCH: IntByReference)
} 
Example 4
Source File: ClusterBuilder.scala    From quill   with Apache License 2.0 5 votes vote down vote up
package io.getquill.context.cassandra.cluster

import io.getquill.util.Messages._
import scala.util.Try
import com.typesafe.config.Config
import com.typesafe.config.ConfigValueType
import java.lang.reflect.Method
import scala.jdk.CollectionConverters._
import com.datastax.driver.core.Cluster

object ClusterBuilder {

  def apply(cfg: Config) =
    set(Cluster.builder, cfg)

  private def set[T](instance: T, cfg: Config): T = {
    for (key <- cfg.entrySet.asScala.map(_.getKey.split('.').head)) {

      def tryMethod(m: Method) =
        m.getParameterTypes.toList match {
          case Nil =>
            Try(cfg.getBoolean(key)).map {
              case true  => m.invoke(instance)
              case false =>
            }
          case tpe :: Nil =>
            param(key, tpe, cfg)
              .map(p => m.invoke(instance, p.asInstanceOf[AnyRef]))
          case tpe :: tail =>
            val c = cfg.getConfig(key)
            tail.foldLeft(param("0", tpe, c).map(List(_))) {
              case (list, tpe) =>
                list.flatMap { l =>
                  val key = s"${l.size}"
                  param(key, tpe, c).map(l :+ _)
                }
            }.map { params =>
              m.invoke(instance, params.asInstanceOf[List[Object]]: _*)
            }
        }

      def tryMethods(m: List[Method]): Any =
        m match {
          case Nil       => fail(s"Invalid config key '$key'")
          case m :: tail => tryMethod(m).getOrElse(tryMethods(tail))
        }

      tryMethods {
        instance.getClass.getMethods.toList.filter { m =>
          m.getName == key ||
            m.getName == s"with${key.capitalize}" ||
            m.getName == s"add${key.capitalize}" ||
            m.getName == s"set${key.capitalize}"
        }
      }
    }

    instance
  }

  val stringArrayClass = java.lang.reflect.Array.newInstance(classOf[String], 0).getClass()

  private def param(key: String, tpe: Class[_], cfg: Config) =
    Try {
      if (tpe == classOf[String])
        cfg.getString(key)
      else if (tpe == stringArrayClass)
        cfg.getStringList(key).asScala.toArray
      else if (tpe == classOf[Int] || tpe == classOf[Integer])
        cfg.getInt(key)
      else if (tpe.isEnum)
        tpe.getMethod("valueOf", classOf[String]).invoke(tpe, cfg.getString(key))
      else if (cfg.getValue(key).valueType == ConfigValueType.STRING)
        getClass.getClassLoader.loadClass(cfg.getString(key)).getConstructor().newInstance()
      else
        set(tpe.getConstructor().newInstance(), cfg.getConfig(key))
    }
} 
Example 5
Source File: package.scala    From hazelcast-scala   with Apache License 2.0 5 votes vote down vote up
package com.hazelcast.Scala

import com.hazelcast.cache.ICache
import com.hazelcast.core.HazelcastInstance
import javax.cache.spi.CachingProvider
import language.implicitConversions
import java.lang.reflect.Method
import scala.util.Try

package object jcache {

  private[this] val HazelcastClientCachingProvider_createCachingProvider: Try[Method] = Try {
    Class.forName("com.hazelcast.client.cache.impl.HazelcastClientCachingProvider")
      .getDeclaredMethod("createCachingProvider", classOf[HazelcastInstance])
  }

  private[Scala] def createClientCachingProvider(hz: HazelcastInstance): Try[CachingProvider] =
    HazelcastClientCachingProvider_createCachingProvider.map(_.invoke(null, hz).asInstanceOf[CachingProvider])

  implicit def asJCacheInstance(hz: HazelcastInstance): JCacheHazelcastInstance = new JCacheHazelcastInstance(hz)
  implicit def asHzCache[K, V](icache: ICache[K, V]) = new HzCache[K, V](icache)
} 
Example 6
Source File: FileUtils.scala    From mimir   with Apache License 2.0 5 votes vote down vote up
package mimir.util

import java.lang.reflect.Method
import java.net.URL
import java.io.{File, FileOutputStream, BufferedOutputStream, InputStream}
import org.apache.commons.compress.archivers.tar.{TarArchiveEntry, TarArchiveInputStream}
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream
import java.io.BufferedInputStream
import java.nio.file.Files

object FileUtils {
  def getListOfFiles(dir: String):List[File] = {
    val d = new File(dir)
    if (d.exists && d.isDirectory) {
        d.listFiles.filter(_.isFile).toList
    } else {
        List[File]()
    }
  }
  def addJarToClasspath(jar: File): Unit = {
// Get the ClassLoader class
    val cl: ClassLoader = ClassLoader.getSystemClassLoader
    val clazz: Class[_] = cl.getClass
// Get the protected addURL method from the parent URLClassLoader class
    val method: Method =
      clazz.getSuperclass.getDeclaredMethod("addURL", Seq(classOf[URL]):_*)
// Run projected addURL method to add JAR to classpath
    method.setAccessible(true)
    method.invoke(cl, Seq(jar.toURI().toURL()):_*)
  }
  
  def untar(in:InputStream, destinationDir: String): File = {

    val dest = new File(destinationDir)
    dest.mkdir()

    var tarIn: TarArchiveInputStream = null

    try {
      tarIn = new TarArchiveInputStream(
        new GzipCompressorInputStream(
          new BufferedInputStream(in)))
      var tarEntry = tarIn.getNextTarEntry
      while (tarEntry != null) {

        // create a file with the same name as the tarEntry
        val destPath = new File(dest, tarEntry.getName)
        if (tarEntry.isDirectory) {
          destPath.mkdirs()
        } else {
          // Create any necessary parent dirs
          val parent = destPath.getParentFile
          if (!Files.exists(parent.toPath)) {
            parent.mkdirs()
          }

          destPath.createNewFile()

          val btoRead = new Array[Byte](1024)
          var bout: BufferedOutputStream = null

          try {
            bout = new BufferedOutputStream(new FileOutputStream(destPath))

            var len = 0
            while (len != -1) {
              len = tarIn.read(btoRead)
              if (len != -1) {
                bout.write(btoRead, 0, len)
              }
            }
          } finally {
            if (bout != null) {
              bout.close()
            }
          }
        }
        tarEntry = tarIn.getNextTarEntry
      }
    } finally {
      if (tarIn != null) {
        tarIn.close()
      }
    }
    dest
  }
  
} 
Example 7
Source File: Scalaprops.scala    From scalaprops   with MIT License 5 votes vote down vote up
package scalaprops

import java.lang.reflect.Method
import sbt.testing.Logger
import scala.scalajs.reflect.annotation.EnableReflectiveInstantiation
import scalaprops.internal._

@EnableReflectiveInstantiation
trait Scalaprops {
  def param: Param = Param.withCurrentTimeSeed()

  def listener: ScalapropsListener =
    ScalapropsListener.default

  def transformProperties[A](properties: List[Properties[A]]): List[Properties[A]] =
    properties.map(Scalaprops.filterUnitEmpty).sortBy(_.id.toString)
}

object Scalaprops {
  def filterUnitEmpty[A](p: Properties[A]): Properties[A] = {
    def loop(tree: Tree[(A, Option[Check])]): Tree[(A, Option[Check])] =
      tree match {
        case Tree.Node(root, Stream(Tree.Node((Or.L(()), None), sub))) =>
          Tree.Node(root, sub.map(loop))
        case Tree.Node((root, None), Stream(Tree.Node(((), sub1), sub2))) =>
          Tree.Node(root -> sub1, sub2.map(loop))
        case _ =>
          Tree.Node(tree.rootLabel, tree.subForest.map(loop))
      }
    Properties.noSort(loop(p.props))
  }

  private[scalaprops] def testFieldNames(clazz: Class[_]): Array[String] =
    Array(
      findTestFields(clazz, classOf[Property]),
      findTestFields(clazz, classOf[Properties[_]])
    ).flatten.map(_.getName)

  private[scalaprops] def findTestFields(clazz: Class[_], fieldType: Class[_]): Array[Method] =
    clazz.getMethods.filter(method => method.getParameterTypes.length == 0 && method.getReturnType == fieldType)

  private[scalaprops] def logger(loggers: Array[Logger]): Logger =
    new Logger {
      override def warn(msg: String): Unit =
        loggers.foreach(_.warn(msg))
      override def error(msg: String): Unit =
        loggers.foreach(_.error(msg))
      override def ansiCodesSupported(): Boolean =
        loggers.forall(_.ansiCodesSupported())
      override def debug(msg: String): Unit =
        loggers.foreach(_.debug(msg))
      override def trace(t: Throwable): Unit =
        loggers.foreach(_.trace(t))
      override def info(msg: String): Unit =
        loggers.foreach(_.info(msg))
    }
} 
Example 8
Source File: ReflectionUtil.scala    From sigmastate-interpreter   with MIT License 5 votes vote down vote up
package scalan.util

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

import scala.reflect.{classTag, ClassTag}
import scalan.OverloadId

object ReflectionUtil {
  def jAnnotation[A <: java.lang.annotation.Annotation : ClassTag](element: AnnotatedElement) =
    Option(element.getAnnotation(classTag[A].runtimeClass.asInstanceOf[Class[A]]))

  def overloadId(method: Method) = jAnnotation[OverloadId](method).map(_.value)

  
  def namedSuperclass(clazz: Class[_]) = {
    if (clazz.getSimpleName.contains("$anon$")) {
      val superclass = clazz.getSuperclass
      if (superclass == classOf[Object]) {
        // clazz is composed of traits only, return the first one
        clazz.getInterfaces.head
      } else
        superclass
    } else
      clazz
  }

  implicit class ClassOps(val cl: Class[_]) extends AnyVal {
    private def isSpecialChar(c: Char): Boolean = {
      ('0' <= c && c <= '9') || c == '$'
    }
    def safeSimpleName: String = {
      if (cl.getEnclosingClass == null) return cl.getSimpleName
      val simpleName = cl.getName.substring(cl.getEnclosingClass.getName.length)
      val length = simpleName.length
      var index = 0
      while (index < length && isSpecialChar(simpleName.charAt(index))) { index += 1 }
      // Eventually, this is the empty string iff this is an anonymous class
      simpleName.substring(index)
    }
  }
} 
Example 9
Source File: TestContexts.scala    From sigmastate-interpreter   with MIT License 5 votes vote down vote up
package scalan

import java.lang.reflect.Method

import scalan.compilation.GraphVizConfig
import scalan.util.FileUtil

trait TestContexts extends TestUtils {
  protected[this] def stage(scalan: Scalan)(testName: String, name: String, sfs: Seq[() => scalan.Sym]): Unit = {
    val directory = FileUtil.file(prefix, testName)
    implicit val graphVizConfig = scalan.defaultGraphVizConfig
    try {
      val ss = sfs.map(_.apply())
      scalan.emitDepGraph(ss, directory, name)
    } catch {
      case e: Exception =>
        val graphMsg = scalan.emitExceptionGraph(e, directory, name) match {
          case Some(graphFile) =>
            s"See ${graphFile.file.getAbsolutePath} for exception graph."
          case None =>
            s"No exception graph produced."
        }
        fail(s"Staging $name failed. $graphMsg", e)
    }
  }

  trait TestContextApi { scalan: Scalan =>
    def invokeAll: Boolean
    def isInvokeEnabled(d: Def[_], m: Method): Boolean
    def shouldUnpack(e: Elem[_]): Boolean
    def testName: String
    def emitF(name: String, sfs: (() => Sym)*): Unit
    //    def emit(name: String, s1: => Sym): Unit = emitF(name, () => s1)
    def emit(name: String, ss: Sym*): Unit = {
      emitF(name, ss.map((s: Ref[_]) => () => s): _*)
    }
    def emit(s1: => Sym): Unit = emitF(testName, () => s1)
    def emit(s1: => Sym, s2: Sym*): Unit = {
      emitF(testName, Seq(() => s1) ++ s2.map((s: Ref[_]) => () => s): _*)
    }
  }
  abstract class TestContext(val testName: String) extends Scalan with TestContextApi {
    def this() = this(currentTestNameAsFileName)

    override val invokeAll = true
    override def isInvokeEnabled(d: Def[_], m: Method) = invokeAll
    override def shouldUnpack(e: Elem[_]) = true

    // workaround for non-existence of by-name repeated parameters
    def emitF(name: String, sfs: (() => Sym)*): Unit = stage(this)(testName, name, sfs)
  }


}

abstract class BaseCtxTests extends BaseTests with TestContexts

abstract class BaseNestedCtxTests extends BaseNestedTests with TestContexts

abstract class BaseShouldCtxTests extends BaseShouldTests with TestContexts 
Example 10
Source File: ExecutorProxy.scala    From ncdbg   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package com.programmaticallyspeaking.ncd.infra

import java.lang.reflect.{InvocationHandler, InvocationTargetException, Method}
import java.util.concurrent.Executor
import java.util.concurrent.atomic.AtomicInteger

import org.slf4s.Logging

import scala.concurrent.duration._
import scala.concurrent.{Await, Future, Promise, TimeoutException}
import scala.reflect.ClassTag
import scala.util.{Failure, Success, Try}

class ExecutorProxy(executor: Executor) {
  import scala.collection.JavaConverters._

  def createFor[A <: AnyRef : ClassTag](instance: A): A = {
    val clazz = implicitly[ClassTag[A]].runtimeClass
    java.lang.reflect.Proxy.newProxyInstance(clazz.getClassLoader, Array(clazz), new Handler(instance)).asInstanceOf[A]
  }

  class Handler(instance: AnyRef) extends InvocationHandler with Logging {
    import scala.concurrent.ExecutionContext.Implicits._
    private val className = instance.getClass.getName

    private val idGen = new AtomicInteger(0)
    private var awaitingCalls = Map[Int, String]()

    override def invoke(proxy: scala.Any, method: Method, args: Array[AnyRef]): AnyRef = {
      val resultPromise = Promise[AnyRef]()

      val before = System.nanoTime()

      val id = idGen.getAndIncrement()
      val argss = Option(args).getOrElse(Array.empty)
      val desc = s"$method(${argss.mkString(", ")})[$id]"
      log.trace(s"Waiting to execute: $desc")

      // Snapshot of waiting calls prior to submitting to the executor
      val waitingCallsAtEntry = awaitingCalls

      executor.execute(() => {
        log.trace(s"Execute: $id")
        Try(method.invoke(instance, args: _*)) match {
          case Success(f: Future[_]) => resultPromise.completeWith(f.asInstanceOf[Future[AnyRef]])
          case Success(result) => resultPromise.success(result)
          case Failure(t: InvocationTargetException) => resultPromise.failure(t.getCause)
          case Failure(t) => resultPromise.failure(t)
        }
      })

      resultPromise.future.onComplete { _ =>
        val methodName = method.getName
        val millis = (System.nanoTime() - before).nanos.toMillis
        log.trace(s"Elapsed time for $className.$methodName = $millis ms")
      }

      if (classOf[Future[_]].isAssignableFrom(method.getReturnType)) resultPromise.future
      else {
        // Update with this call
        awaitingCalls += (id -> desc)
        //TODO: Configurable timeout
        try Await.result(resultPromise.future, 30.seconds) catch {
          case _: TimeoutException =>
            val other = waitingCallsAtEntry.values
            val sb = new StringBuilder(s"Timed out waiting for '$desc' to complete. Calls at entry: ${other.mkString("'", "', '", "'")}. Stack:\n")
            appendStackTraces(sb)
            log.debug(sb.toString())
            throw new TimeoutException(s"Timed out waiting for '$desc' to complete.")
        } finally {
          // Done with this call
          awaitingCalls -= id
          log.trace(s"Done: $id")
        }
      }
    }

    private def appendStackTraces(sb: StringBuilder): Unit = {
      Thread.getAllStackTraces.asScala.foreach { tup =>
        sb.append("\n> THREAD ").append(tup._1.getName).append("\n")
        tup._2.foreach(ste => sb.append("  ").append(ste).append("\n"))
      }
    }
  }
} 
Example 11
Source File: MockDynamoDB.scala    From iep-apps   with Apache License 2.0 5 votes vote down vote up
package com.netflix.iep.archaius

import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.lang.reflect.Proxy

import com.amazonaws.services.dynamodbv2.AmazonDynamoDB
import com.amazonaws.services.dynamodbv2.model.ScanResult

class MockDynamoDB extends InvocationHandler {

  var scanResult: ScanResult = _

  override def invoke(proxy: Any, method: Method, args: Array[AnyRef]): AnyRef = {
    method.getName match {
      case "scan" => scanResult
      case _      => throw new UnsupportedOperationException(method.toString)
    }
  }

  def client: AmazonDynamoDB = {
    val clsLoader = Thread.currentThread().getContextClassLoader
    val proxy = Proxy.newProxyInstance(clsLoader, Array(classOf[AmazonDynamoDB]), this)
    proxy.asInstanceOf[AmazonDynamoDB]
  }
} 
Example 12
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 13
Source File: untyped.scala    From libisabelle   with Apache License 2.0 5 votes vote down vote up
package isabelle


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


object Untyped
{
  def method(c: Class[_], name: String, arg_types: Class[_]*): Method =
  {
    val m = c.getDeclaredMethod(name, arg_types: _*)
    m.setAccessible(true)
    m
  }

  def classes(obj: AnyRef): Iterator[Class[_ <: AnyRef]] = new Iterator[Class[_ <: AnyRef]] {
    private var next_elem: Class[_ <: AnyRef] = obj.getClass
    def hasNext(): Boolean = next_elem != null
    def next(): Class[_ <: AnyRef] = {
      val c = next_elem
      next_elem = c.getSuperclass.asInstanceOf[Class[_ <: AnyRef]]
      c
    }
  }

  def field(obj: AnyRef, x: String): Field =
  {
    val iterator =
      for {
        c <- classes(obj)
        field <- c.getDeclaredFields.iterator
        if field.getName == x
      } yield {
        field.setAccessible(true)
        field
      }
    if (iterator.hasNext) iterator.next
    else error("No field " + quote(x) + " for " + obj)
  }

  def get[A](obj: AnyRef, x: String): A =
    if (obj == null) null.asInstanceOf[A]
    else field(obj, x).get(obj).asInstanceOf[A]

  def set[A](obj: AnyRef, x: String, y: A): Unit =
    field(obj, x).set(obj, y)
} 
Example 14
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 15
Source File: untyped.scala    From libisabelle   with Apache License 2.0 5 votes vote down vote up
package isabelle


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


object Untyped
{
  def method(c: Class[_], name: String, arg_types: Class[_]*): Method =
  {
    val m = c.getDeclaredMethod(name, arg_types: _*)
    m.setAccessible(true)
    m
  }

  def classes(obj: AnyRef): Iterator[Class[_ <: AnyRef]] = new Iterator[Class[_ <: AnyRef]] {
    private var next_elem: Class[_ <: AnyRef] = obj.getClass
    def hasNext(): Boolean = next_elem != null
    def next(): Class[_ <: AnyRef] = {
      val c = next_elem
      next_elem = c.getSuperclass.asInstanceOf[Class[_ <: AnyRef]]
      c
    }
  }

  def field(obj: AnyRef, x: String): Field =
  {
    val iterator =
      for {
        c <- classes(obj)
        field <- c.getDeclaredFields.iterator
        if field.getName == x
      } yield {
        field.setAccessible(true)
        field
      }
    if (iterator.hasNext) iterator.next
    else error("No field " + quote(x) + " for " + obj)
  }

  def get[A](obj: AnyRef, x: String): A =
    if (obj == null) null.asInstanceOf[A]
    else field(obj, x).get(obj).asInstanceOf[A]

  def set[A](obj: AnyRef, x: String, y: A): Unit =
    field(obj, x).set(obj, y)
} 
Example 16
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 17
Source File: untyped.scala    From libisabelle   with Apache License 2.0 5 votes vote down vote up
package isabelle


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


object Untyped
{
  def method(c: Class[_], name: String, arg_types: Class[_]*): Method =
  {
    val m = c.getDeclaredMethod(name, arg_types: _*)
    m.setAccessible(true)
    m
  }

  def classes(obj: AnyRef): Iterator[Class[_ <: AnyRef]] = new Iterator[Class[_ <: AnyRef]] {
    private var next_elem: Class[_ <: AnyRef] = obj.getClass
    def hasNext(): Boolean = next_elem != null
    def next(): Class[_ <: AnyRef] = {
      val c = next_elem
      next_elem = c.getSuperclass.asInstanceOf[Class[_ <: AnyRef]]
      c
    }
  }

  def field(obj: AnyRef, x: String): Field =
  {
    val iterator =
      for {
        c <- classes(obj)
        field <- c.getDeclaredFields.iterator
        if field.getName == x
      } yield {
        field.setAccessible(true)
        field
      }
    if (iterator.hasNext) iterator.next
    else error("No field " + quote(x) + " for " + obj)
  }

  def get[A](obj: AnyRef, x: String): A =
    if (obj == null) null.asInstanceOf[A]
    else field(obj, x).get(obj).asInstanceOf[A]

  def set[A](obj: AnyRef, x: String, y: A): Unit =
    field(obj, x).set(obj, y)
} 
Example 18
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 19
Source File: ThriftRandomGenerator.scala    From streamliner-examples   with Apache License 2.0 5 votes vote down vote up
package com.memsql.spark.examples.thrift

import collection.JavaConversions._
import java.lang.reflect.Method
import java.nio.ByteBuffer
import org.apache.thrift.{TBase, TFieldIdEnum}
import org.apache.thrift.protocol.{TField, TType}
import org.apache.thrift.meta_data._

import scala.util.Random

object ThriftRandomGenerator {
  val random = new Random
  val MAX_RECURSION_LEVEL = 5

  def next[F <: TFieldIdEnum](c: Class[_], level: Int = 0): Any = {
    if (level > MAX_RECURSION_LEVEL) {
      return null
    }
    val className = c.getName
    try {
      val tBaseClass = c.asInstanceOf[Class[TBase[_ <: TBase[_, _], F]]]
      val instance = tBaseClass.newInstance()
      val metaDataMap: Map[_ <: TFieldIdEnum, FieldMetaData] = FieldMetaData.getStructMetaDataMap(tBaseClass).toMap
      metaDataMap.foreach({ case (field, fieldMetaData) =>
        val valueMetaData = fieldMetaData.valueMetaData
        val value = getValue(valueMetaData, level)
        instance.setFieldValue(instance.fieldForId(field.getThriftFieldId), value)
      })
      instance
    } catch {
      case e: ClassCastException => throw new IllegalArgumentException(s"Class $className is not a subclass of org.apache.thrift.TBase")
    }
  }

  def getValue(valueMetaData: FieldValueMetaData, level: Int): Any = {
    if (level > MAX_RECURSION_LEVEL) {
      return null
    }
    valueMetaData.`type` match {
      case TType.BOOL => random.nextBoolean
      case TType.BYTE => random.nextInt.toByte
      case TType.I16 => random.nextInt.toShort
      case TType.I32 => random.nextInt
      case TType.I64 => random.nextLong
      case TType.DOUBLE => random.nextInt(5) * 0.25
      case TType.ENUM => {
        val enumClass = valueMetaData.asInstanceOf[EnumMetaData].enumClass
        getEnumValue(enumClass)
      }
      case TType.STRING => {
        val length: Int = 5 + random.nextInt(5)
        val s = (1 to length).map(x => ('a'.toInt + random.nextInt(26)).toChar).mkString
        if (valueMetaData.isBinary) {
          ByteBuffer.wrap(s.getBytes)
        } else {
          s
        }
      }
      case TType.LIST => {
        val elemMetaData = valueMetaData.asInstanceOf[ListMetaData].elemMetaData
        val length: Int = 5 + random.nextInt(5)
        val ret: java.util.List[Any] = (1 to length).map(x => getValue(elemMetaData, level + 1))
        ret
      }
      case TType.SET => {
        val elemMetaData = valueMetaData.asInstanceOf[SetMetaData].elemMetaData
        val length: Int = 5 + random.nextInt(5)
        val ret: Set[Any] = (1 to length).map(x => getValue(elemMetaData, level + 1)).toSet
        val javaSet: java.util.Set[Any] = ret
        javaSet
      }
      case TType.MAP => {
        val mapMetaData = valueMetaData.asInstanceOf[MapMetaData]
        val keyMetaData = mapMetaData.keyMetaData
        val mapValueMetaData = mapMetaData.valueMetaData
        val length: Int = 5 + random.nextInt(5)
        val ret: Map[Any, Any] = (1 to length).map(_ => {
          val mapKey = getValue(keyMetaData, level + 1)
          val mapValue = getValue(mapValueMetaData, level + 1)
          mapKey -> mapValue
        }).toMap
        val javaMap: java.util.Map[Any, Any] = ret
        javaMap
      }
      case TType.STRUCT => {
        val structClass = valueMetaData.asInstanceOf[StructMetaData].structClass
        next(structClass, level = level + 1)
      }
      case _ => null
    }
  }

  def getEnumValue(enumType: Class[_]): Any = {
    val enumConstants = enumType.getEnumConstants
    enumConstants(random.nextInt(enumConstants.length))
  }
} 
Example 20
Source File: SlickJdbcMigration.scala    From reliable-http-client   with Apache License 2.0 5 votes vote down vote up
package rhttpc.transport.amqpjdbc.slick

import java.io.PrintWriter
import java.lang.reflect.{InvocationHandler, Method, Proxy}
import java.sql.Connection
import java.util.logging.Logger

import javax.sql.DataSource
import org.flywaydb.core.api.migration.{BaseJavaMigration, Context}
import slick.jdbc.JdbcProfile

import scala.concurrent.Await
import scala.concurrent.duration._

trait SlickJdbcMigration extends BaseJavaMigration {

  protected val profile: JdbcProfile

  import profile.api._

  def migrateActions: DBIOAction[Any, NoStream, _ <: Effect]

  override final def migrate(context: Context): Unit = {
    val database = Database.forDataSource(new AlwaysUsingSameConnectionDataSource(context.getConnection), None)
    Await.result(database.run(migrateActions), 10 minute)
  }

}

class AlwaysUsingSameConnectionDataSource(conn: Connection) extends DataSource {
  private val notClosingConnection = Proxy.newProxyInstance(
    ClassLoader.getSystemClassLoader,
    Array[Class[_]](classOf[Connection]),
    SuppressCloseHandler
  ).asInstanceOf[Connection]

  object SuppressCloseHandler extends InvocationHandler {
    override def invoke(proxy: AnyRef, method: Method, args: Array[AnyRef]): AnyRef = {
      if (method.getName != "close") {
        method.invoke(conn, args : _*)
      } else {
        null
      }
    }
  }

  override def getConnection: Connection = notClosingConnection
  override def getConnection(username: String, password: String): Connection = notClosingConnection
  override def unwrap[T](iface: Class[T]): T = conn.unwrap(iface)
  override def isWrapperFor(iface: Class[_]): Boolean = conn.isWrapperFor(iface)

  override def setLogWriter(out: PrintWriter): Unit = ???
  override def getLoginTimeout: Int = ???
  override def setLoginTimeout(seconds: Int): Unit = ???
  override def getParentLogger: Logger = ???
  override def getLogWriter: PrintWriter = ???
} 
Example 21
Source File: TransportRegistrar.scala    From hydra   with Apache License 2.0 5 votes vote down vote up
package hydra.ingest.services

import java.lang.reflect.Method

import akka.actor.{Actor, ActorRef, ActorRefFactory, Props}
import com.typesafe.config.Config
import hydra.common.config.ConfigSupport
import hydra.common.logging.LoggingAdapter
import hydra.common.reflect.ReflectionUtils
import hydra.common.util.ActorUtils
import hydra.core.transport.Transport
import hydra.ingest.bootstrap.ClasspathHydraComponentLoader
import hydra.ingest.services.TransportRegistrar.{
  GetTransports,
  GetTransportsResponse
}

import scala.util.Try


  private def companion[T](clazz: Class[T]): Option[(T, Method)] = {
    try {
      val companion = ReflectionUtils.companionOf(clazz)
      companion.getClass.getMethods.toList.filter(m =>
        m.getName == "props"
          && m.getParameterTypes.toList == List(classOf[Config])
      ) match {
        case Nil           => None
        case method :: Nil => Some(companion, method)
        case _             => None
      }
    } catch {
      case _: Throwable => None
    }
  }
} 
Example 22
Source File: ComponentInstantiator.scala    From hydra   with Apache License 2.0 5 votes vote down vote up
package hydra.common.reflect

import java.lang.reflect.Method

import scala.util.Try


  private def companion[T](
      clazz: Class[T],
      methodName: String,
      parameterTypes: List[Class[_]]
  ): Option[(T, Method)] = {
    try {
      val companion = ReflectionUtils.companionOf(clazz)
      companion.getClass.getMethods.toList.filter(m =>
        m.getName == methodName
          && areParamsAssignable(m.getParameterTypes.toList, parameterTypes)
      ) match {
        case Nil           => None
        case method :: Nil => Some(companion, method)
        case _             => None
      }
    } catch {
      case _: ClassNotFoundException => None
    }
  }

  private def areParamsAssignable(
      methodParamTypes: List[Class[_]],
      argParamTypes: List[Class[_]]
  ): Boolean = {
    methodParamTypes
      .zip(argParamTypes)
      .filter(x => x._1.isAssignableFrom(x._2))
      .size > 0
  }
} 
Example 23
Source File: TokenAuthorizingInterceptor.scala    From meteorite-core   with Apache License 2.0 5 votes vote down vote up
package bi.meteorite.core.security.authorization

import java.lang.reflect.Method
import org.apache.cxf.security.SecurityContext

import java.util

import scala.collection.mutable.HashMap
import scala.collection.mutable.ListBuffer

import scala.collection.JavaConversions._
import TokenAuthorizingInterceptor._
import scala.collection.JavaConverters._

object TokenAuthorizingInterceptor {

  private def parseRolesMap(rolesMap: Map[String, String]): scala.collection.mutable.HashMap[String, List[String]] = {
    val map = new scala.collection.mutable.HashMap[String, List[String]]()
    for ((key, value) <- rolesMap) {
      map.put(key, value.split(" ").toList)
    }
    map
  }
}


class TokenAuthorizingInterceptor(uniqueId: Boolean) extends TokenAbstractAutorizingInInterceptor(uniqueId) {

  private val methodRolesMap = new HashMap[String, List[String]]()

  private var userRolesMap = new scala.collection.mutable.HashMap[String, List[String]]

  private var globalRoles =  new scala.collection.mutable.ListBuffer[String]

  private var checkConfiguredRolesOnly: Boolean = _

  def this() {
    this(true)
  }

  protected override def isUserInRole(sc: SecurityContext, roles: util.List[String], deny: Boolean): Boolean = {
    if (!checkConfiguredRolesOnly && !super.isUserInRole(sc, roles, deny)) {
      return false
    }
    if (userRolesMap.nonEmpty) {
      val userRoles = userRolesMap.get(sc.getUserPrincipal.getName)
      if (userRoles == null) {
        return false
      }
      for (role <- roles if userRoles.get.contains(role)) {
        return true
      }
      false
    } else {
      !checkConfiguredRolesOnly
    }
  }

  private def createMethodSig(method: Method): String = {
    val b = new StringBuilder(method.getReturnType.getName)
    b.append(' ').append(method.getName).append('(')
    for (cls <- method.getParameterTypes) {
      b.append(cls.getName)
    }
    b.append(')')
    b.toString

    method.getName
  }

  protected override def getExpectedRoles(method: Method): util.List[String] = {

    var roles = methodRolesMap.get(createMethodSig(method))

    if(roles.isEmpty) {
      roles = methodRolesMap.get(method.getName)
    }

    if(roles.isEmpty){
      globalRoles.toList
    }
    else{
      roles.get
    }

  }

  def setMethodRolesMap(rolesMap: java.util.Map[String, String]) =
    methodRolesMap.putAll(parseRolesMap(rolesMap.asScala.toMap))

  def setUserRolesMap(rolesMap: java.util.Map[String, String]) = userRolesMap = parseRolesMap(rolesMap.asScala.toMap)

  def setGlobalRoles(roles: String) = globalRoles = roles.split(" ").to[ListBuffer]

  def setCheckConfiguredRolesOnly(checkConfiguredRolesOnly: Boolean) = this.checkConfiguredRolesOnly =
    checkConfiguredRolesOnly

} 
Example 24
Source File: TokenAbstractAutorizingInInterceptor.scala    From meteorite-core   with Apache License 2.0 5 votes vote down vote up
package bi.meteorite.core.security.authorization

import java.lang.reflect.Method
import java.util
import java.util.logging.Level

import org.apache.cxf.common.logging.LogUtils
import org.apache.cxf.interceptor.security.{AbstractAuthorizingInInterceptor, AccessDeniedException}
import org.apache.cxf.message.Message
//remove if not needed
import scala.collection.JavaConversions._

object TokenAbstractAutorizingInInterceptor {

  private val LOG = LogUtils.getL7dLogger(classOf[TokenAbstractAutorizingInInterceptor])

  private val ALL_ROLES = "*"
}


abstract class TokenAbstractAutorizingInInterceptor(uniqueId: Boolean) extends AbstractAuthorizingInInterceptor(uniqueId) {

  def this() {
    this(true)
  }

  override def handleMessage(message: Message) {
    val method = getTargetMethod(message)
    val sc = message.get(classOf[javax.ws.rs.core.SecurityContext])
    if (sc == null) {
      val sc2 = message.get(classOf[org.apache.cxf.security.SecurityContext])
      if (authorize(sc2, method)) {
        return
      }
    } else if (sc.getUserPrincipal != null) {
      if (authorize(sc, method)) {
        return
      }
    } else if (!isMethodProtected(method) && isAllowAnonymousUsers) {
      return
    }
    throw new AccessDeniedException("Unauthorized")
  }

  protected def authorize(sc: javax.ws.rs.core.SecurityContext, method: Method): Boolean = {
    val expectedRoles = getExpectedRoles(method)
    if (expectedRoles.isEmpty) {
      val denyRoles = getDenyRoles(method)
      return denyRoles.isEmpty || isUserInRole(sc, denyRoles, deny = true)
    }
    if (isUserInRole(sc, expectedRoles, deny = false)) {
      return true
    }
    if (TokenAbstractAutorizingInInterceptor.LOG.isLoggable(Level.FINE)) {
      TokenAbstractAutorizingInInterceptor.LOG.fine(sc.getUserPrincipal.getName + " is not authorized")
    }
    false
  }


  protected def isUserInRole(sc: javax.ws.rs.core.SecurityContext, roles: util.List[String], deny: Boolean): Boolean = {
    if (roles.size == 1 && TokenAbstractAutorizingInInterceptor.ALL_ROLES == roles.get(0)) {
      return !deny
    }
    for (role <- roles if sc.isUserInRole(role)) {
      return !deny
    }
    deny
  }
} 
Example 25
Source File: PropertyDescriptor.scala    From mango   with Apache License 2.0 5 votes vote down vote up
package com.kakao.shaded.jackson.module.scala
package introspect

import util.Implicits._
import java.lang.reflect.{AccessibleObject, Constructor, Field, Method}

import scala.language.existentials

case class ConstructorParameter(constructor: Constructor[_], index: Int, defaultValueMethod: Option[Method])

case class PropertyDescriptor(name: String,
                              param: Option[ConstructorParameter],
                              field: Option[Field],
                              getter: Option[Method],
                              setter: Option[Method],
                              beanGetter: Option[Method],
                              beanSetter: Option[Method])
{
  if (List(field, getter).flatten.isEmpty) throw new IllegalArgumentException("One of field or getter must be defined.")

  def findAnnotation[A <: java.lang.annotation.Annotation](implicit mf: Manifest[A]): Option[A] = {
    val cls = mf.runtimeClass.asInstanceOf[Class[A]]
    lazy val paramAnnotation = (param flatMap { cp =>
      val paramAnnos = cp.constructor.getParameterAnnotations
      paramAnnos(cp.index).find(cls.isInstance)
    }).asInstanceOf[Option[A]]
    val getAnno = (o: AccessibleObject) => o.getAnnotation(cls)
    lazy val fieldAnnotation = field optMap getAnno
    lazy val getterAnnotation = getter optMap getAnno
    lazy val beanGetterAnnotation = beanGetter optMap getAnno

    paramAnnotation orElse fieldAnnotation orElse getterAnnotation orElse beanGetterAnnotation
  }

} 
Example 26
Source File: Accessible.scala    From mango   with Apache License 2.0 5 votes vote down vote up
package com.kakao.mango.reflect

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

import scala.reflect._


object Accessible {

  val modifiers: Field = {
    val field = classOf[Field].getDeclaredField("modifiers")
    field.setAccessible(true)
    field
  }

  def field[T: ClassTag](name: String): Field = {
    field(classTag[T].runtimeClass, name)
  }

  def field(clazz: Class[_], name: String): Field = {
    val field = clazz.getDeclaredField(name)
    field.setAccessible(true)
    modifiers.setInt(field, field.getModifiers & ~FINAL)
    field
  }

  def method[T: ClassTag](name: String, parameterTypes: Class[_]*): Method = {
    method(classTag[T].runtimeClass, name, parameterTypes: _*)
  }

  def method(clazz: Class[_], name: String, parameterTypes: Class[_]*): Method = {
    val method = clazz.getDeclaredMethod(name, parameterTypes: _*)
    method.setAccessible(true)
    method
  }

  def constructor[T](clazz: Class[T], parameterTypes: Class[_]*): Constructor[T] = {
    val constructor = clazz.getDeclaredConstructor(parameterTypes: _*)
    constructor.setAccessible(true)
    constructor
  }

  def firstConstructor[T: ClassTag]: Constructor[T] = {
    firstConstructor(classTag[T].runtimeClass.asInstanceOf[Class[T]])
  }

  def firstConstructor[T](clazz: Class[T]): Constructor[T] = {
    val constructor = clazz.getDeclaredConstructors()(0).asInstanceOf[Constructor[T]]
    constructor.setAccessible(true)
    constructor
  }

} 
Example 27
Source File: DefaultParameters.scala    From mango   with Apache License 2.0 5 votes vote down vote up
package com.kakao.mango.reflect

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

import scala.reflect.runtime.universe._
import scala.util.control.NonFatal


  def apply(obj: AnyRef, method: Method): Array[AnyRef] = {
    val clazz = method.getDeclaringClass
    val name = method.getName

    val count = method.getParameterTypes.length
    val result = new Array[AnyRef](count)

    try {
      for (i <- 0 until count) {
        util.Try(clazz.getMethod(s"$name$$default$$${i+1}")).foreach { method =>
          result(i) = method.invoke(obj)
        }
      }
    } catch {
      case NonFatal(e) => // if there is no default parameters, return the array with null entries
    }

    result
  }

} 
Example 28
Source File: MenuIO.scala    From hacktoberfest-scala-algorithms   with GNU General Public License v3.0 5 votes vote down vote up
package io.github.sentenza.hacktoberfest

import java.lang.System.out.println
import java.lang.reflect.Method
import java.util.concurrent.atomic.AtomicInteger

import io.github.sentenza.hacktoberfest.algos.{ImmutableSorting, MutableSorting, Sorting}

import scala.annotation.tailrec
import scala.util.{Success, Try}


  def printDisclaimer() { println(heading + gplDisclaimer) }

  private val noOp = () => ()

  def readNumberInputs = scala.io.StdIn.readLine().split(",").map(_.toInt)

  case class MenuEntry(selector: Int, display: String, code: () => Unit)
  private val entries =
    List(
      MenuEntry(1, "Sorting algorithms", () => {
        println("You chose sorting\n")
        renderInteractiveMenu(List(
          MenuEntry(2, "MutableSorting", () => {
            println("You chose mutable sorting.")
            renderInteractiveMenu(createMethodMenuEntries(MutableSorting))
          }),
          MenuEntry(1, "ImmutableSorting", () => {
            println("You chose immutable sorting.")
            renderInteractiveMenu(createMethodMenuEntries(ImmutableSorting))
          }),
          MenuEntry(0, "Quit sorting", () => noOp)
        ))
      }),
      MenuEntry(0, "Quit the program",() => System.exit(0))
    )

  private def createMethodMenuEntries(sorting: Sorting[_,_]) = {
    val count = new AtomicInteger()
    retrieveMethodNames(sorting)
      .map(mName =>
        MenuEntry(count.incrementAndGet(), mName, () => executeSortMethod(sorting, mName))
      ).toList
  }

  private def retrieveMethodNames(sorting:Sorting[_,_]) =
    sorting.getClass.getMethods.map(_.getName).filter(_.endsWith("Sort")).distinct

  private def executeSortMethod(sorting: Sorting[_,_], method: String) = {
    println("You've chosen " + method + "! Please enter a list of comma separated integers.")
    val numberInputs = readNumberInputs
    println(s"You entered:${numberInputs.mkString(",")}. They are going to be sorted by $method.\n Sorting...")
    val sorted = execute(sorting, method, numberInputs)
    println(s"Your number entries sorted are: ${sorted.mkString(",")}")
  }

  private def execute[F[_],T](sorting: Sorting[_,_], method: String, numberInputs: F[_]) = {
    findMethod(sorting, method) match {
      case Some(m:Method) => m.invoke(sorting, numberInputs).asInstanceOf[F[_]]
      case None => throw new RuntimeException(s"Method $method not found in $sorting")
    }
  }

  private def findMethod(sorting: Sorting[_,_], method: String) =
    sorting.getClass.getMethods.find(m => m.getName.compare(method) == 0)

  @tailrec
  def renderInteractiveMenu(entries:List[MenuEntry]=entries): Unit = {
    println("Please choose:")
    entries.foreach {
      case MenuEntry(num, label, _) =>
        println(s"$num: $label")
    }

      Try(scala.io.StdIn.readInt()) match {
        case Success(0) =>
          ()
        case Success(choice) if entries.exists(_.selector == choice) =>
          entries.find(_.selector == choice).foreach{
            case MenuEntry(_, _, code) => code()
          }
          renderInteractiveMenu()
        case _ =>
          println("Invalid selection\n")
          renderInteractiveMenu()
      }
    }
} 
Example 29
Source File: ReflectiveFunctionExport.scala    From rug   with GNU General Public License v3.0 5 votes vote down vote up
package com.atomist.rug.spi

import java.lang.reflect.Method

import org.springframework.util.ReflectionUtils


object ReflectiveFunctionExport {

  def allExportedOperations(c: Class[_]): Seq[TypeOperation] =
    if (c == null) Nil
    else operations(ReflectionUtils.getAllDeclaredMethods(c))

  def exportedOperations(c: Class[_]): Seq[TypeOperation] =
    if (c == null) Nil
    else operations(c.getDeclaredMethods)

  private def operations(methods: Array[Method]) =
    methods
      .filter(_.getAnnotations.exists(_.isInstanceOf[ExportFunction]))
      .map(m => {
        val a = m.getAnnotation(classOf[ExportFunction])
        val params = extractExportedParametersAndDocumentation(m)
        TypeOperation(m.getName, a.description(),
          a.readOnly(),
          params,
          SimpleParameterOrReturnType.fromJavaType(m.getGenericReturnType),
          m.getDeclaringClass,
          a.example() match {
            case "" => None
            case ex => Some(ex)
          },
          exposeAsProperty = a.exposeAsProperty(),
          exposeResultDirectlyToNashorn = a.exposeResultDirectlyToNashorn(),
          deprecated = m.isAnnotationPresent(classOf[Deprecated]))
      })

  private def extractExportedParametersAndDocumentation(m: Method): Array[TypeParameter] = {
    m.getParameters.map(p =>
      if (p.isAnnotationPresent(classOf[ExportFunctionParameterDescription])) {
        val annotation = p.getDeclaredAnnotation(classOf[ExportFunctionParameterDescription])
        TypeParameter(annotation.name(),
          SimpleParameterOrReturnType.fromJavaType(p.getParameterizedType),
          Some(annotation.description()))
      }
      else
        TypeParameter(p.getName,
          SimpleParameterOrReturnType.fromJavaType(p.getParameterizedType),
          None)
    )
  }

} 
Example 30
Source File: AnnotatedRugFunction.scala    From rug   with GNU General Public License v3.0 5 votes vote down vote up
package com.atomist.rug.spi

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

import com.atomist.param.{Parameter, ParameterValues, Tag}
import org.springframework.core.annotation.AnnotationUtils


  private def convert(param: java.lang.reflect.Parameter, avalue: Any): AnyRef = {
    avalue match {
      case o: String => (param.getType, o) match {
        case (p, "") if p == classOf[Int] => new Integer(0)
        case (p, _)  if p == classOf[Int] => o.toInt.asInstanceOf[AnyRef]
        case (p, "") if p == classOf[Integer] => new Integer(0)
        case (p, _)  if p == classOf[Integer] => Integer.parseInt(o).asInstanceOf[AnyRef]
        case (p, "") if p == classOf[Boolean] => false.asInstanceOf[AnyRef]
        case (p , _) if p == classOf[Boolean] => o.toBoolean.asInstanceOf[AnyRef]
        case (p, "") if p == classOf[Double] => 0d.asInstanceOf[AnyRef]
        case (p, _) if p == classOf[Double] => o.toDouble.asInstanceOf[AnyRef]
        case (p, "") if p == classOf[java.lang.Double] => 0d.asInstanceOf[AnyRef]
        case (p, _) if p == classOf[java.lang.Double] => java.lang.Double.parseDouble(o).asInstanceOf[AnyRef]
        case (p, "") if p == classOf[Float] => 0f.asInstanceOf[AnyRef]
        case (p, _) if p == classOf[Float] => o.toFloat.asInstanceOf[AnyRef]
        case (p, "") if p == classOf[java.lang.Float] => 0f.asInstanceOf[AnyRef]
        case (p, _) if p == classOf[java.lang.Float] => java.lang.Float.parseFloat(o).asInstanceOf[AnyRef]
        case (p, _) if p == classOf[String] => o
      }
      case _ => avalue.asInstanceOf[AnyRef]
    }
  }
} 
Example 31
Source File: MethodTracer.scala    From money   with Apache License 2.0 5 votes vote down vote up
package com.comcast.money.core.logging

import java.lang.reflect.Method

import com.comcast.money.annotations.{ Timed, Traced }
import com.comcast.money.core.{ Money, Tracer }
import com.comcast.money.core.async.AsyncNotifier
import com.comcast.money.core.internal.{ MDCSupport, SpanContext, SpanLocal }
import com.comcast.money.core.reflect.Reflections
import org.slf4j.MDC

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

trait MethodTracer extends Reflections with TraceLogging {
  val tracer: Tracer = Money.Environment.tracer
  val asyncNotifier: AsyncNotifier = Money.Environment.asyncNotifier
  val mdcSupport: MDCSupport = new MDCSupport()
  val spanContext: SpanContext = SpanLocal

  def traceMethod(method: Method, annotation: Traced, args: Array[AnyRef], proceed: () => AnyRef): AnyRef = {
    val key = annotation.value()

    tracer.startSpan(key)
    recordTracedParameters(method, args, tracer)

    Try { proceed() } match {
      case Success(result) if annotation.async() =>
        traceAsyncResult(method, annotation, result) match {
          case Some(future) =>
            future
          case None =>
            tracer.stopSpan(true)
            result
        }
      case Success(result) =>
        tracer.stopSpan(true)
        result
      case Failure(exception) =>
        logException(exception)
        tracer.stopSpan(exceptionMatches(exception, annotation.ignoredExceptions()))
        throw exception
    }
  }

  def timeMethod(method: Method, annotation: Timed, proceed: () => AnyRef): AnyRef = {
    val key = annotation.value()
    try {
      tracer.startTimer(key)
      proceed()
    } finally {
      tracer.stopTimer(key)
    }
  }

  def traceAsyncResult(
    method: Method,
    annotation: Traced,
    returnValue: AnyRef): Option[AnyRef] = for {

    // resolve an async notification handler that supports the result
    handler <- asyncNotifier.resolveHandler(method.getReturnType, returnValue)

    // pop the current span from the stack as it will not be stopped by the tracer
    span <- spanContext.pop
    // capture the current MDC context to be applied on the callback thread
    mdc = Option(MDC.getCopyOfContextMap)

    result = handler.whenComplete(method.getReturnType, returnValue) { completed =>
      // reapply the MDC onto the callback thread
      mdcSupport.propogateMDC(mdc)

      // determine if the future completed successfully or exceptionally
      val result = completed match {
        case Success(_) => true
        case Failure(exception) =>
          logException(exception)
          exceptionMatches(exception, annotation.ignoredExceptions())
      }

      // stop the captured span with the success/failure flag
      span.stop(result)
      // clear the MDC from the callback thread
      MDC.clear()
    }
  } yield result
} 
Example 32
Source File: ScalaObjectHandler.scala    From fintrospect   with Apache License 2.0 5 votes vote down vote up
package io.fintrospect.templating

import java.io.Writer
import java.lang.reflect.{Field, Method}

import com.github.mustachejava.Iteration
import com.github.mustachejava.reflect.ReflectionObjectHandler

import scala.collection.JavaConversions.mapAsJavaMap
import scala.reflect.ClassTag
import scala.runtime.BoxedUnit

class ScalaObjectHandler extends ReflectionObjectHandler {

  override def checkMethod(member: Method) {}

  override def checkField(member: Field) {}

  override def coerce(value: AnyRef) = value match {
    case m: collection.Map[_, _] => mapAsJavaMap(m)
    case _: BoxedUnit => null
    case Some(some: AnyRef) => coerce(some)
    case None => null
    case _ => value
  }

  override def iterate(iteration: Iteration, writer: Writer, value: AnyRef, scopes: java.util.List[AnyRef]) = value match {
    case TraversableAnyRef(t) => {
      var newWriter = writer
      t foreach (next => newWriter = iteration.next(newWriter, coerce(next), scopes))
      newWriter
    }
    case n: Number => if (n.intValue() == 0) writer else iteration.next(writer, coerce(value), scopes)
    case _ => super.iterate(iteration, writer, value, scopes)
  }

  override def falsey(iteration: Iteration, writer: Writer, value: AnyRef, scopes: java.util.List[AnyRef]) = value match {
    case TraversableAnyRef(t) => if (t.isEmpty) iteration.next(writer, value, scopes) else writer
    case n: Number => if (n.intValue() == 0) iteration.next(writer, coerce(value), scopes) else writer
    case _ => super.falsey(iteration, writer, value, scopes)
  }

  private val TraversableAnyRef = new Def[Traversable[AnyRef]]

  private class Def[C: ClassTag] {
    def unapply[X: ClassTag](x: X): Option[C] = x match {
      case c: C => Some(c)
      case _ => None
    }
  }

} 
Example 33
Source File: PlayServiceConfiguration.scala    From play-soap   with Apache License 2.0 5 votes vote down vote up
package play.soap

import java.lang.reflect.Method
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

import org.apache.cxf.wsdl.service.factory.AbstractServiceConfiguration
import java.util.concurrent.CompletionStage

import scala.concurrent.Future

import java.lang.Boolean.FALSE

private[soap] class PlayServiceConfiguration extends AbstractServiceConfiguration {

  
  override def hasOutMessage(m: Method) = {
    m.getGenericReturnType match {
      case future: ParameterizedType
          if future.getRawType == classOf[Future[_]] ||
            future.getRawType == classOf[CompletionStage[_]] =>
        future.getActualTypeArguments.headOption match {
          case Some(unit) if unit == classOf[Unit] || unit == classOf[Void] => FALSE
          case _                                                            => null
        }
      case _ => null
    }
  }
} 
Example 34
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 35
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 36
Source File: LaunchException.scala    From coursier   with Apache License 2.0 5 votes vote down vote up
package coursier.cli.launch

import java.lang.reflect.Method

sealed abstract class LaunchException(message: String, cause: Throwable = null) extends Exception(message, cause)

object LaunchException {
  // Specify one with -M or --main.
  final class NoMainClassFound extends LaunchException("Cannot find default main class")
  final class MainClassNotFound(mainClass: String, cause: Throwable) extends LaunchException(s"Class $mainClass not found", cause)
  final class MainMethodNotFound(mainClass: Class[_], cause: Throwable) extends LaunchException(s"Main method not found in $mainClass", cause)
  final class NonStaticMainMethod(mainClass: Class[_], method: Method) extends LaunchException(s"Main method in $mainClass is not static")

  // constraint to be lifted later
  final class ClasspathHierarchyUnsupportedWhenForking extends LaunchException("Cannot start an application with a hierarchical classpath by forking")
}