java.lang.reflect.ParameterizedType Scala Examples

The following examples show how to use java.lang.reflect.ParameterizedType. 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: RPCProduct.scala    From Linkis   with Apache License 2.0 5 votes vote down vote up
package com.webank.wedatasphere.linkis.rpc.transform

import java.lang.reflect.{ParameterizedType, Type}
import java.util

import com.webank.wedatasphere.linkis.DataWorkCloudApplication
import com.webank.wedatasphere.linkis.common.utils.Logging
import com.webank.wedatasphere.linkis.rpc.exception.DWCURIException
import com.webank.wedatasphere.linkis.server.{BDPJettyServerHelper, EXCEPTION_MSG, Message}
import org.apache.commons.lang.ClassUtils
import org.json4s.jackson.Serialization
import org.json4s.{DefaultFormats, Formats, Serializer}

import scala.collection.JavaConversions


private[linkis] trait RPCProduct {

  def toMessage(t: Any): Message

  def notFound(): Message

  def ok(): Message

}
private[linkis] object RPCProduct extends Logging {
  private[rpc] val IS_SCALA_CLASS = "rpc_is_scala_class"
  private[rpc] val CLASS_VALUE = "rpc_object_class"
  private[rpc] val OBJECT_VALUE = "rpc_object_value"
  private[rpc] implicit var formats: Formats = DefaultFormats + JavaCollectionSerializer + JavaMapSerializer
  private var serializerClasses: List[Class[_]] = List.empty
  private val rpcProduct: RPCProduct = new RPCProduct {
    private val rpcFormats = DataWorkCloudApplication.getApplicationContext.getBeansOfType(classOf[RPCFormats])
    if(rpcFormats != null && !rpcFormats.isEmpty) {
      val serializers = JavaConversions.mapAsScalaMap(rpcFormats).map(_._2.getSerializers).toArray.flatMap(_.iterator)
      setFormats(serializers)
    }
    override def toMessage(t: Any): Message = {
      if(t == null) throw new DWCURIException(10001, "The transmitted bean is Null.(传输的bean为Null.)")
      val message = Message.ok("RPC Message.")
      if(isScalaClass(t)){
        message.data(IS_SCALA_CLASS, "true")
        message.data(OBJECT_VALUE, Serialization.write(t.asInstanceOf[AnyRef]))
      } else {
        message.data(IS_SCALA_CLASS, "false")
        message.data(OBJECT_VALUE, BDPJettyServerHelper.gson.toJson(t))
      }
      message.setMethod("/rpc/message")
      message.data(CLASS_VALUE, t.getClass.getName)
    }

    override def notFound(): Message = {
      val message = Message.error("RPC Message.")
      message.setMethod("/rpc/message")
      message.data(EXCEPTION_MSG, new DWCURIException(10000, "The service does not exist for the available Receiver.(服务不存在可用的Receiver.)").toMap)
    }

    override def ok(): Message = {
      val message = Message.ok("RPC Message.")
      message.setMethod("/rpc/message")
      message
    }
  }
  private[rpc] def setFormats(serializer: Array[Serializer[_]]): Unit ={
    this.formats = (serializer :+ JavaCollectionSerializer :+ JavaMapSerializer).foldLeft(DefaultFormats.asInstanceOf[Formats])(_ + _)
    serializerClasses = formats.customSerializers.map(s => getActualTypeClass(s.getClass.getGenericSuperclass))
      .filter(_ != null) ++: List(classOf[util.List[_]], classOf[util.Map[_, _]])
    info("RPC Serializers: " + this.formats.customSerializers.map(_.getClass.getSimpleName) + ", serializerClasses: " +
      "" + serializerClasses)
  }
  private def getActualTypeClass(classType: Type): Class[_] = classType match {
    case p: ParameterizedType =>
      val params = p.getActualTypeArguments
      if(params == null || params.isEmpty) null
      else getActualTypeClass(params(0))
    case c: Class[_] => c
    case _ => null
  }
  private[rpc] def isScalaClass(obj: Any): Boolean =
    (obj.isInstanceOf[Product] && obj.isInstanceOf[Serializable]) ||
      serializerClasses.exists(ClassUtils.isAssignable(obj.getClass, _)) ||
        obj.getClass.getName.startsWith("scala.")
  private[rpc] def getSerializableScalaClass(clazz: Class[_]): Class[_] =
    serializerClasses.find(ClassUtils.isAssignable(clazz, _)).getOrElse(clazz)
  def getRPCProduct: RPCProduct = rpcProduct
} 
Example 2
Source File: RPCFormatsTest.scala    From Linkis   with Apache License 2.0 5 votes vote down vote up
package com.webank.wedatasphere.linkis.rpc

import java.lang.reflect.ParameterizedType
import java.util

import com.webank.wedatasphere.linkis.rpc.transform.{JavaCollectionSerializer, JavaMapSerializer}
import org.apache.commons.lang.ClassUtils
import org.json4s.JsonAST.JObject
import org.json4s.JsonDSL._
import org.json4s.jackson.Serialization
import org.json4s.reflect.ManifestFactory
import org.json4s.{CustomSerializer, DefaultFormats, Extraction}

object RPCFormatsTest {

  trait ResultResource
  class AvailableResource(val ticketId: String) extends ResultResource

  object ResultResourceSerializer extends CustomSerializer[ResultResource](implicit formats => ({
    case JObject(List(("AvailableResource", JObject(List(("ticketId", ticketId)))))) => new AvailableResource(ticketId.extract[String])
  },{
    case r: AvailableResource => ("AvailableResource", ("ticketId", Extraction.decompose(r.ticketId)))
  }))

  def testRPC1(args: Array[String]): Unit = {
    implicit val formats = DefaultFormats + ResultResourceSerializer
    val serializerClasses = formats.customSerializers.map(_.getClass.getGenericSuperclass match {
      case p: ParameterizedType =>
        val params = p.getActualTypeArguments
        if(params == null || params.isEmpty) null
        else params(0).asInstanceOf[Class[_]]
    }).filter(_ != null)
    val a = new AvailableResource("aaa")
    val str = Serialization.write(a)
    println(str)
    val clazz = classOf[AvailableResource]
    println(serializerClasses)
    val realClass1 = serializerClasses.find(ClassUtils.isAssignable(clazz, _))
    println(realClass1)
    val realClass = realClass1.getOrElse(clazz)
    val obj = Serialization.read(str)(formats, ManifestFactory.manifestOf(realClass))
    println(obj)
    println(classOf[Array[_]].getClass.getName)
  }

  case class TestCollection1(a: String, list: java.util.List[String])
  case class TestCollection2(a: String, list: java.util.Map[String, Integer])

  def testRPC2(args: Array[String]): Unit = {
    implicit val formats = DefaultFormats + JavaCollectionSerializer + JavaMapSerializer
    //    val a = TestCollection1("1", new util.ArrayList[String]())
    val a = TestCollection2("1", new util.HashMap[String, Integer]())
    //    a.list.add("1111")
    a.list.put("1111", 2)
    val str = Serialization.write(a)
    println(str)
    val realClass = classOf[TestCollection2]
    val obj = Serialization.read(str)(formats, ManifestFactory.manifestOf(realClass))
    println(obj)
  }

  def main(args: Array[String]): Unit = {
    testRPC2(args)
  }
} 
Example 3
Source File: EnumResolver.scala    From mango   with Apache License 2.0 5 votes vote down vote up
package com.kakao.shaded.jackson.module.scala
package util

import java.lang.reflect.ParameterizedType

import com.kakao.shaded.jackson.databind.BeanProperty
import com.kakao.shaded.jackson.module.scala.introspect.ScalaAnnotationIntrospector
import com.kakao.shaded.jackson.module.scala.JsonScalaEnumeration

object EnumResolver {

  def apply(property: BeanProperty): Option[EnumResolver] = {
    Option(property)
      .flatMap(p => ScalaAnnotationIntrospector.propertyFor(p.getMember))
      .flatMap(_.findAnnotation[JsonScalaEnumeration])
      .map(a => apply(a))
  }

  def apply(a: JsonScalaEnumeration): EnumResolver = {
    val pt = a.value().getGenericSuperclass.asInstanceOf[ParameterizedType]
    val args = pt.getActualTypeArguments
    apply(args(0).asInstanceOf[Class[Enumeration]])
  }

  def apply[T <: Enumeration](cls: Class[T]): EnumResolver = {
    val enum = cls.getField("MODULE$").get(null).asInstanceOf[T]
    apply(enum)
  }

  def apply(e: Enumeration): EnumResolver = {
    val valueSet = e.values
    val map: Map[String, e.type#Value] = valueSet.map(v => (v.toString, v)).toMap
    new EnumResolver(e.getClass, valueSet, map)
  }
}

class EnumResolver(cls: Class[_], valueSet: Enumeration#ValueSet, enumsByName: Map[String, Enumeration#Value]) {

  def getEnum(key: String): Enumeration#Value = enumsByName(key)

  def getEnumClass = cls

} 
Example 4
Source File: JsonJacksonMarshaller.scala    From wix-http-testkit   with MIT License 5 votes vote down vote up
package com.wix.e2e.http.json

import java.lang.reflect.{ParameterizedType, Type}

import com.fasterxml.jackson.core.`type`.TypeReference
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module
import com.fasterxml.jackson.datatype.joda.JodaModule
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.wix.e2e.http.api.Marshaller

class JsonJacksonMarshaller extends Marshaller {

  def unmarshall[T : Manifest](jsonStr: String): T = objectMapper.readValue(jsonStr, typeReference[T])
  def marshall[T](t: T): String = objectMapper.writeValueAsString(t)

  def configure: ObjectMapper = objectMapper

  private val objectMapper = new ObjectMapper()
                                    .registerModule(new Jdk8Module().configureAbsentsAsNulls(true))
                                    .registerModules(new JodaModule, new ParameterNamesModule, new JavaTimeModule) // time modules
                                    .registerModule(new DefaultScalaModule)
                                    .disable( WRITE_DATES_AS_TIMESTAMPS )

  private def typeReference[T: Manifest] = new TypeReference[T] {
    override def getType = typeFromManifest(manifest[T])
  }

  private def typeFromManifest(m: Manifest[_]): Type = {
    if (m.typeArguments.isEmpty) { m.runtimeClass }
    else new ParameterizedType {
      def getRawType = m.runtimeClass
      def getActualTypeArguments = m.typeArguments.map(typeFromManifest).toArray
      def getOwnerType = null
    }
  }
} 
Example 5
Source File: ReflectionUtils.scala    From DynaML   with Apache License 2.0 5 votes vote down vote up
package io.github.mandar2812.dynaml.utils.sumac

import annotation.tailrec
import java.lang.reflect.{Type, ParameterizedType, Field}

import scala.reflect.ClassTag


object ReflectionUtils {

  @tailrec
  def getAllDeclaredFields(cls: Class[_], acc: Seq[Field] = Seq.empty): Seq[Field] = {
    val fields = acc ++ cls.getDeclaredFields
    Option(cls.getSuperclass) match {
      case Some(clazz) => getAllDeclaredFields(clazz, fields)
      case _ => fields
    }
  }

  def findGenericInterface(cls: Class[_], interface: Class[_]) : Option[ParameterizedType] = {
    val interfaces = cls.getGenericInterfaces
    //first check if this directly implements it
    findParameterizedType(interfaces, interface).orElse{
      //then check if its inherited by any of those interfaces
      interfaces.flatMap{tpe =>
        findGenericInterface(getRawClass(tpe), interface)
      }.headOption
    }
  }

  def getRawClass(tpe: Type) : Class[_] = {
    tpe match {
      case x: Class[_] => x
      case p: ParameterizedType => p.getRawType.asInstanceOf[Class[_]]
    }
  }

  def findParameterizedType(types: Array[Type], interface: Class[_]) : Option[ParameterizedType] = {
    types.find { tpe =>
      tpe match {
        case ptpe: ParameterizedType => ParseHelper.checkType(ptpe, classOf[Argable[_]])
        case _ => false
      }
    }.map{_.asInstanceOf[ParameterizedType]}
  }

  def construct[T](clz: Class[T]): T = {
    val ctors = clz.getDeclaredConstructors
    ctors.find(_.getGenericParameterTypes.length == 0) match {
      case Some(ctor) =>
        ctor.setAccessible(true)
        ctor.newInstance().asInstanceOf[T]
      case None => throw new AssertionError("No zero-arg constructor found")
    }
  }

  def construct[T](tag: ClassTag[T]): T = {
    construct(tag.runtimeClass.asInstanceOf[Class[T]])
  }
} 
Example 6
Source File: ThriftSchemaConverter.scala    From airbnb-spark-thrift   with Apache License 2.0 5 votes vote down vote up
package com.airbnb.spark.thrift

import java.lang.reflect.ParameterizedType
import java.util

import org.apache.spark.sql.types._
import org.apache.thrift.meta_data.FieldMetaData
import org.apache.thrift.meta_data.FieldValueMetaData
import org.apache.thrift.meta_data.ListMetaData
import org.apache.thrift.meta_data.MapMetaData
import org.apache.thrift.meta_data._
import org.apache.thrift.protocol.TType

import org.apache.thrift.{TFieldRequirementType, TFieldIdEnum, TBase}

import scala.collection.JavaConversions._

object ThriftSchemaConverter  {

  
  def convertField(fieldClasses: Seq[Class[_]], metaData: FieldValueMetaData): DataType = {
    val ttype = metaData.`type`
    ttype match {
      case TType.BOOL => BooleanType
      case TType.BYTE => BinaryType
      case TType.DOUBLE => DoubleType
      case TType.I16 => ShortType
      case TType.I32 => IntegerType
      case TType.I64 => LongType
      case TType.STRING |
           TType.ENUM => StringType

      case TType.STRUCT =>
        val structClass = fieldClasses(0).asInstanceOf[Class[TBase[_ <: TBase[_, _], _ <: TFieldIdEnum]]]
        convert(structClass)

      case TType.LIST =>
        val listMetaData = metaData.asInstanceOf[ListMetaData]
        val eleMetaData = listMetaData.elemMetaData
        ArrayType(convertField(fieldClasses, eleMetaData), containsNull = false)

      case TType.SET =>
        val setMetaData = metaData.asInstanceOf[SetMetaData]
        val eleMetaData = setMetaData.elemMetaData
        ArrayType(convertField(fieldClasses, eleMetaData), containsNull = false)

      case TType.MAP =>
        val mapMetaData = metaData.asInstanceOf[MapMetaData]
        MapType(
          convertField(Seq(fieldClasses(0)), mapMetaData.keyMetaData),
          convertField(Seq(fieldClasses(1)), mapMetaData.valueMetaData),
          valueContainsNull = false)

      case _ => throw new IllegalArgumentException(s"Illegal Thrift type: $ttype")
    }
  }
} 
Example 7
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 8
Source File: JSONHTTP.scala    From orders-aws   with Apache License 2.0 5 votes vote down vote up
package works.weave.socks.aws.orders.dataaccess.web

import com.amazonaws.util.IOUtils
import com.fasterxml.jackson.core.`type`.TypeReference
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import java.net.URI
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.HttpClientBuilder
import org.slf4j.LoggerFactory
import works.weave.socks.aws.orders.ProjectDefaultJacksonMapper

object JSONHTTP {

  val Log = LoggerFactory.getLogger(getClass)

  val objectMapper = ProjectDefaultJacksonMapper.build() // after (_.bla)

  def get[T : Manifest : NotNothing](uri : URI) : T = {
    val client = HttpClientBuilder.create.build
    val get = new HttpGet(uri)
    get.addHeader("Accept", "application/json")
    val response = client.execute(get)
    val responseString = IOUtils.toString(response.getEntity.getContent)
    Log.info(s"Got status ${response.getStatusLine.getStatusCode}")
    require(response.getStatusLine.getStatusCode == 200)
    Log.info(s"Got response from URI $uri: $responseString")
    objectMapper.readValue(responseString, typeReference[T])
  }

  def typeReference[T : Manifest] = new TypeReference[T] {
    override def getType = typeFromManifest(manifest[T])
  }

  def typeFromManifest(m : Manifest[_]) : Type = {
    if (m.typeArguments.isEmpty) { m.runtimeClass }
    else new ParameterizedType {
      def getRawType = m.runtimeClass
      def getActualTypeArguments = m.typeArguments.map(typeFromManifest).toArray
      def getOwnerType = null
    }
  }

  // Trick to disable nothign for type param
  sealed trait NotNothing[-T]

  object NotNothing {
    implicit object notNothing extends NotNothing[Any]
    implicit object `The error is because the missing type parameter was resolved to Nothing` extends NotNothing[Nothing]
  }

}