• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala NoTypeHints类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中org.json4s.NoTypeHints的典型用法代码示例。如果您正苦于以下问题:Scala NoTypeHints类的具体用法?Scala NoTypeHints怎么用?Scala NoTypeHints使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了NoTypeHints类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: DomainLists

//设置package包名称以及导入依赖的类
package org.dele.text.lapa.patterns

import org.dele.text.lapa.ErrorHandling.{DomainListDefsErrorDomainNotFound}
import DomainStructure.{LangDomainManager, Domain}
import TLangPattern.LangPatternDomain
import org.dele.text.maen.{AtomPropMatcherLib, ConfValueStringParser, TAtomMatcher}
import org.dele.text.maen.matchers.{SubMatchCheckerLib, TMatcher}
import org.json4s.NoTypeHints
import org.json4s.jackson.JsonMethods._
import org.json4s.jackson.Serialization


object DomainLists {
  import TMatcher._
  import DomainStructure.genId

  //private def parseEntry(entry:String, matcherGen:TMatcherGen):TAtomMatcher = {
    //val (tmplId, tmplParams) = ConfValueStringParser.parse(entry)
    //AtomPropMatcherLib.spawn(tmplId, tmplParams)
    //matcherGen.spawn(entry, )
  //}

  sealed class ListDef(val id:String, val lines:List[List[String]]) {
    def getMatcher(domain:Domain, matcherGen:TMatcherGen, regexDict:Map[String,String])(implicit domainManager:LangDomainManager, subMatchCheckerLib: SubMatchCheckerLib):TMatcher = {
      val mid = genId(domain.id, id)

      implicit val domainId = Option(domain.id)
      if (lines.size == 1) ListNGram(lines.head.map(e => {
        val parsed = ConfValueStringParser.parse(e)
        matcherGen.spawn(parsed, None, regexDict).get
      }), Option(mid))
      else matchersOR(mid, lines.map(
        l => {
          ListNGram(l.map(e => {
            val parsed = ConfValueStringParser.parse(e)
            matcherGen.spawn(parsed, None, regexDict).get
          }))
        }
      ))
    }
  }

  sealed class DomainListDefs(val domain:String, val lists:List[ListDef]) {
    private val _map:Map[String,ListDef] = lists.map(l => (l.id, l)).toMap
    def getMatchers(matcherGen:TMatcherGen, regexDict:Map[String,String])(implicit domainManager:LangDomainManager, subMatchCheckerLib: SubMatchCheckerLib):Set[TMatcher] = {
      val d = domainManager.getDomain(domain)
      if (d.isEmpty) throw DomainListDefsErrorDomainNotFound(domain)
      else lists.map(_.getMatcher(d.get, matcherGen, regexDict)).toSet
    }
  }

  sealed class LangDomainLists(val lang:String, val domainLists:List[DomainListDefs]) {
    private val _map:Map[String,DomainListDefs] = domainLists.map(dl => (dl.domain, dl)).toMap
    def getMatchers(matcherGen:TMatcherGen, regexDict:Map[String,String])(implicit domainManager:LangDomainManager, subMatchCheckerLib: SubMatchCheckerLib):Set[TMatcher] =
      domainLists.map(_.getMatchers(matcherGen, regexDict)).foldLeft(Set[TMatcher]())(_ ++ _)
  }

  implicit val _formats = Serialization.formats(NoTypeHints)
  def loadDomainLists(json:String):LangDomainLists = parse(json).extract[LangDomainLists]
} 
开发者ID:new2scala,项目名称:text-util,代码行数:61,代码来源:DomainLists.scala


示例2: EventDeserialiser

//设置package包名称以及导入依赖的类
package serialisation

import java.util

import model.Event
import org.apache.kafka.common.serialization.{Deserializer, StringDeserializer}
import org.json4s.native.Serialization
import org.json4s.native.Serialization.read
import org.json4s.{Formats, NoTypeHints}

class EventDeserialiser extends Deserializer[Event] {

  implicit val formats: Formats = Serialization.formats(NoTypeHints)

  val stringDeserialiser = new StringDeserializer

  override def configure(configs: util.Map[String, _], isKey: Boolean): Unit = {
    stringDeserialiser.configure(configs, isKey)
  }

  override def deserialize(topic: String, data: Array[Byte]): Event = {
    val stringValue = stringDeserialiser.deserialize(topic, data)
    read[Event](stringValue)
  }

  override def close(): Unit = {
    stringDeserialiser.close()
  }
} 
开发者ID:benwheeler,项目名称:kafka-streams-poc,代码行数:30,代码来源:EventDeserialiser.scala


示例3: EventSerialiser

//设置package包名称以及导入依赖的类
package serialisation

import java.util

import model.Event
import org.apache.kafka.common.serialization.{Serializer, StringSerializer}
import org.json4s.native.Serialization
import org.json4s.native.Serialization.write
import org.json4s.{Formats, NoTypeHints}

class EventSerialiser extends Serializer[Event] {

  implicit val formats: Formats = Serialization.formats(NoTypeHints)

  val stringSerialiser = new StringSerializer

  override def configure(configs: util.Map[String, _], isKey: Boolean): Unit = {
    stringSerialiser.configure(configs, isKey)
  }

  override def serialize(topic: String, data: Event): Array[Byte] = {
    val stringValue = write(data)
    stringSerialiser.serialize(topic, stringValue)
  }

  override def close(): Unit = {
    stringSerialiser.close()
  }
} 
开发者ID:benwheeler,项目名称:kafka-streams-poc,代码行数:30,代码来源:EventSerialiser.scala


示例4: StringEventCollector

//设置package包名称以及导入依赖的类
package transformation

import model.Event
import org.apache.kafka.streams.KeyValue
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{read, write}
import org.json4s.{Formats, NoTypeHints}

class StringEventCollector(storeName: String)
  extends CollectTransformer[String, String, String, String, String](storeName) {

  implicit val formats: Formats = Serialization.formats(NoTypeHints)

  override def appendToStore(storeValue: String, appendValue: String): String = {
    appendValue
  }

  override def collectComplete(storeValue: String, appendValue: String): Boolean = {
    // just merges two events
    storeValue.nonEmpty && appendValue.nonEmpty
  }

  override def collectOutput(inputKey: String, storeValue: String, mergeValue: String): KeyValue[String, String] = {
    new KeyValue(inputKey, collect(storeValue, mergeValue))
  }

  def collect(storeValue: String, mergeValue: String): String = {
    log.info(s"Collecting ...")
    log.info(s"   with store : $storeValue")
    log.info(s"   with event : $mergeValue")
    val firstEvent = read[Event](storeValue)
    val secondEvent = read[Event](mergeValue)
    write(Event(firstEvent.eventType + secondEvent.eventType,
      firstEvent.count + secondEvent.count,
      firstEvent.name + secondEvent.name))
  }
} 
开发者ID:benwheeler,项目名称:kafka-streams-poc,代码行数:38,代码来源:StringEventCollector.scala


示例5: SerializationTest

//设置package包名称以及导入依赖的类
package org.argus.amandroid.serialization

import java.io.{FileReader, FileWriter}

import org.argus.amandroid.alir.componentSummary.ApkYard
import org.argus.amandroid.core.decompile.{ConverterUtil, DecompileLayout, DecompileStrategy, DecompilerSettings}
import org.argus.amandroid.core.model.ApkModel
import org.argus.jawa.core.DefaultReporter
import org.json4s.NoTypeHints
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{read, write}
import org.scalatest.{FlatSpec, Matchers}
import org.argus.jawa.core.util.FileUtil


class SerializationTest extends FlatSpec with Matchers {

  "ApkModel" should "successfully serialized and deserialized" in {
    val apkFile = getClass.getResource("/icc-bench/IccHandling/icc_explicit_src_sink.apk").getPath
    val apkUri = FileUtil.toUri(apkFile)
    val outputUri = FileUtil.toUri(apkFile.substring(0, apkFile.length - 4))
    val reporter = new DefaultReporter
    val yard = new ApkYard(reporter)
    val layout = DecompileLayout(outputUri)
    val strategy = DecompileStrategy(layout)
    val settings = DecompilerSettings(debugMode = false, forceDelete = true, strategy, reporter)
    val apk = yard.loadApk(apkUri, settings, collectInfo = true)
    val model = apk.model
    implicit val formats = Serialization.formats(NoTypeHints) + ApkModelSerializer
    val apkRes = FileUtil.toFile(FileUtil.appendFileName(outputUri, "apk.json"))
    val oapk = new FileWriter(apkRes)
    try {
      write(model, oapk)
    } catch {
      case e: Exception =>
        e.printStackTrace()
    } finally {
      oapk.flush()
      oapk.close()
    }
    val iapk = new FileReader(apkRes)
    var newApkModel: ApkModel = null
    try {
      newApkModel = read[ApkModel](iapk)
    } catch {
      case e: Exception =>
        e.printStackTrace()
    } finally {
      iapk.close()
      ConverterUtil.cleanDir(outputUri)
    }
    require(
      model.getAppName == newApkModel.getAppName &&
      model.getComponents == newApkModel.getComponents &&
      model.getLayoutControls == newApkModel.getLayoutControls &&
      model.getCallbackMethods == newApkModel.getCallbackMethods &&
      model.getComponentInfos == newApkModel.getComponentInfos &&
      model.getEnvMap == newApkModel.getEnvMap)
  }
} 
开发者ID:arguslab,项目名称:Argus-SAF,代码行数:61,代码来源:SerializationTest.scala


示例6: HBaseWriterActivity

//设置package包名称以及导入依赖的类
package yumi.pipeline.activities.connectors.hbase

import org.apache.spark.sql.execution.datasources.hbase.{HBaseRelation, HBaseTableCatalog}
import org.json4s.NoTypeHints
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization.write
import yumi.pipeline.{Activity, Parameters, SessionData, YumiContext}

class HBaseWriterActivity (val parameters: Parameters) extends Activity{

  val format = "org.apache.spark.sql.execution.datasources.hbase"
  val mode = parameters
    .getOptionAs[String]("mode")
    .getOrElse("append")

  val table = parameters.getAs[String]("table")
  val as = parameters.getAs[String]("as")
  val namespace = parameters.getAs[String]("namespace")
  val rowKey = parameters.getAs[String]("rowKey")
  val columns = parameters.getAs[List[Map[Any, Any]]]("columns")
  val zookeeperQuorum = parameters.getAs[String]("zookeeper.quorum")
  val zookeeperZnodeParent = parameters.getAs[String]("zookeeper.znode.parent")


  override protected[this] def onInvoke(sessionData: SessionData)
                                       (implicit yumiContext: YumiContext): SessionData = {

    import yumiContext._

    implicit val formats = Serialization.formats(NoTypeHints)

    val columnString = columns.map(x=> write(x).stripPrefix("{").stripSuffix("}")).mkString(",")


    val catalog = s"""{
                     |"table":{"namespace":"$namespace", "name":"$as"},
                     |"rowkey":"$rowKey",
                     |"columns":{$columnString}
                     |}""".stripMargin


    val connection = s"""{
        "hbase.zookeeper.quorum":"$zookeeperQuorum",
        "zookeeper.znode.parent":"$zookeeperZnodeParent"
      }
      """

    dataFrameWriter.write(
      dataFrame = sparkSession.table(table),
      format = format,
      mode = mode,
      options = Map(HBaseTableCatalog.tableCatalog -> catalog,
        HBaseRelation.HBASE_CONFIGURATION -> connection),
      path = format
    )

    sessionData
  }
} 
开发者ID:coderdiaries,项目名称:yumi,代码行数:60,代码来源:HBaseWriterActivity.scala


示例7: HBaseReaderActivity

//设置package包名称以及导入依赖的类
package yumi.pipeline.activities.connectors.hbase


import org.apache.spark.sql.execution.datasources.hbase.{HBaseRelation, HBaseTableCatalog}
import org.json4s.NoTypeHints
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization.write
import yumi.pipeline.{Activity, Parameters, SessionData, YumiContext}

class HBaseReaderActivity(val parameters: Parameters) extends Activity {

  val table = parameters.getString("table")
  val asView = parameters.getString("as")
  val namespace = parameters.getString("namespace")
  val rowKey = parameters.getString("rowKey")
  val columns = parameters.getAs[List[Map[Any, Any]]]("columns")
  val zookeeperQuorum = parameters.getString("zookeeper.quorum")
  val zookeeperZnodeParent = parameters.getString("zookeeper.znode.parent")

  override protected[this] def onInvoke(sessionData: SessionData)
                                       (implicit yumiContext: YumiContext): SessionData = {

    import yumiContext._

    implicit val formats = Serialization.formats(NoTypeHints)

    val columnString = columns.map(x=> write(x).stripPrefix("{").stripSuffix("}")).mkString(",")

    val catalog = s"""{
                     |"table":{"namespace":"$namespace", "name":"$table"},
                     |"rowkey":"$rowKey",
                     |"columns":{$columnString}
                     |}""".stripMargin

    val connection = s"""{
        "hbase.zookeeper.quorum":"$zookeeperQuorum",
        "zookeeper.znode.parent":"$zookeeperZnodeParent"
      }
      """

    sparkSession
      .read
      .options(Map(HBaseTableCatalog.tableCatalog -> catalog,
        HBaseRelation.HBASE_CONFIGURATION -> connection))
      .format("org.apache.spark.sql.execution.datasources.hbase")
      .load()
      .createTempView(asView)

    sessionData
  }
} 
开发者ID:coderdiaries,项目名称:yumi,代码行数:52,代码来源:HBaseReaderActivity.scala


示例8: Ticket

//设置package包名称以及导入依赖的类
package com.octo.nad.handson.model

import org.json4s.NoTypeHints
import org.json4s.native.Serialization
import org.json4s.native.Serialization._


case class Ticket(
                   id_day:Int,
                   sid_store:Int,
                   id_basket:Int,
                   libelle_min:String,
                   id_client:Option[Int],
                   nb_articles:Int,
                   total_ticket:BigDecimal,
                   liste_produits:List[Produit]){
  def toJson = write(this)(Serialization.formats(NoTypeHints))
}
object Ticket{
  implicit val formats = Serialization.formats(NoTypeHints)
  def fromJson(str: String) = read[Ticket](str)
} 
开发者ID:tmouron,项目名称:hands-on-spark,代码行数:23,代码来源:Ticket.scala


示例9: UserApiTesting

//设置package包名称以及导入依赖的类
package com.innoq.tests.utils

import com.innoq.framework.TestingBase
import com.innoq.framework.utils.{HttpInterceptionTesting, Methods}
import org.json4s.NoTypeHints
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization._

object UserApiTesting {

  implicit private val formats = Serialization.formats(NoTypeHints)

  case class CreateUser(name: String, password: String)

  case class User(id: String, name: String, password: String, balance: Int)

}

class UserApiTesting(test: TestingBase with HttpInterceptionTesting) {

  import UserApiTesting._

  private val userApiUrl = test.infrastructureConfig.getString("services.user.url")

  def createUser(name: String, password: String) = {
    val createUser = CreateUser(name, password)
    val json = write(createUser)
    val r = test.requestAndWait(s"$userApiUrl/users/", Methods.POST, json)
    test.parseResponse[User](r)
  }

  def getUser(id: String) = {
    val r = test.requestAndWait(s"$userApiUrl/users/$id", Methods.GET)
    test.parseResponse[User](r)
  }

  def credit(userId: String, amount: Int) = {
    val r = test.requestAndWait(s"$userApiUrl/users/$userId/credit/$amount", Methods.POST)
    test.parseResponse[User](r)
  }

  def debit(userId: String, amount: Int) = {
    val r = test.requestAndWait(s"$userApiUrl/users/$userId/debit/$amount", Methods.POST)
    test.parseResponse[User](r)
  }
} 
开发者ID:mputz86,项目名称:testing-with-logging,代码行数:47,代码来源:UserApiTesting.scala


示例10: ApiDecoder

//设置package包名称以及导入依赖的类
package smarthouse.restapi.http.ws

import org.json4s.JsonAST.JString
import org.json4s.NoTypeHints
import org.json4s.jackson.JsonMethods._
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization._
import smarthouse.restapi.http.ws.models.{ApiMessage, Heartbeat}

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

object ApiDecoder extends JsonSerializers {
  implicit val formats = Serialization.formats(NoTypeHints) + memberStatusSerializer + uriSerializer + offsetDateTime

  def decodeRequest(requestString: String): Option[ApiMessage] = {
    Try {
      parse(requestString) \ "messageType" match {
        case JString("Heartbeat") => read[Heartbeat](requestString)
        case _ => throw InvalidRequestException
      }
    } match {
      case Success(x) => Some(x)
      case Failure(_) => None
    }
  }


  def encodeRequest(apiMessage: ApiMessage): String = {
    write(apiMessage)
  }

  def encodeCustom(msg: AnyRef): String = {
    write(msg)
  }

  case object InvalidRequestException extends RuntimeException

} 
开发者ID:andrewobukhov,项目名称:smart-house,代码行数:39,代码来源:ApiDecoder.scala


示例11: Athanor

//设置package包名称以及导入依赖的类
package au.edu.utscic.athanorserver.athanor

import au.edu.utscic.athanorserver.data.RhetoricalImplicits
import au.edu.utscic.athanorserver.data.RhetoricalTypes._
import com.typesafe.config.{Config, ConfigFactory}
import com.xerox.jatanor.JAtanor
import org.json4s.JsonAST.JValue
import org.json4s.NoTypeHints
import org.json4s.jackson.JsonMethods.parse
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization.write

import scala.io.Source


object Athanor {

  lazy val config: Config = ConfigFactory.load()
  lazy val path: String = config.getString("app.path")
  lazy val athanor = new JAtanor
  lazy val handler = athanor.LoadProgram(program,"")
  lazy val program: String = fullPath("apply.kif")
  lazy val testSentence: String = fullPath("sentence.json")
  lazy val demoFile:String = Source.fromFile(testSentence).getLines.mkString

  def fullPath(file:String): String = {
    s"$path/scripts/$file"
  }


  def parseJsonSentence(sent:String):ParsedSentence = {

    import RhetoricalImplicits._

    val json:JValue = parse(sent)
    val lexNodes:LexicalNodes = json(0)
    val constTree:ConstituentTree = json(1).extract[ConstituentTree]
    val deps:Dependencies = json(2).extract[Dependencies]
    (lexNodes,constTree,deps)
  }

  def parsedSentenceToJsonString(parsedSent:ParsedSentence):String = {
    implicit val formats = Serialization.formats(NoTypeHints)
    val l = write(parsedSent._1)
    val c = write(parsedSent._2).replaceAll("""(\"(?=[0-9]))|((?<=[0-9])\")""","") //remove quotes around Ints for json
    val d = write(parsedSent._3)
    s"[$l,$c,$d]"
  }

  def analyseParsedSentence(parsed:ParsedSentence):List[String] = {
    val jsonStr:String = parsedSentenceToJsonString(parsed)
    this.analyseJson(jsonStr)
  }

  def analyseJson(json:String):List[String] = {
    athanor.ExecuteFunctionArray(handler,"Apply",List(json).toArray).toList
  }

} 
开发者ID:uts-cic,项目名称:athanor-server,代码行数:60,代码来源:Athanor.scala


示例12: unjsonify

//设置package包名称以及导入依赖的类
package com.telegram.json

import org.json4s.JsonAST.JValue
import org.json4s.NoTypeHints
import org.json4s.native.JsonMethods._
import org.json4s.native.Serialization
import org.json4s.native.Serialization._


  def unjsonify[T : Manifest](json: String): T = {
    unjsonify(parse(json))
  }

  def unjsonify[T : Manifest](json: JValue): T = {
    implicit val formats = Serialization.formats(NoTypeHints)
    val camelCased = json transformField {
      case (name, value) => (underscoreToCamel(name), value)
    }
    camelCased.extract[T]
  }
} 
开发者ID:rub0,项目名称:tbot,代码行数:22,代码来源:JsonUtils.scala


示例13: toJson

//设置package包名称以及导入依赖的类
package se.apogo.kdom.api.model

import org.json4s.NoTypeHints
import org.json4s.jackson.Serialization

trait JsonSerializable {
  import org.json4s.native.JsonMethods._
  implicit val formats = Serialization.formats(NoTypeHints)
  def toJson: String = {
    val json = Serialization.writePretty(this)
    pretty(render(parse(json)))
  }
}

case class JsonString(string: String) extends JsonSerializable {
  override def toJson: String = string
} 
开发者ID:mratin,项目名称:kdom,代码行数:18,代码来源:JsonSerializable.scala


示例14: toJson

//设置package包名称以及导入依赖的类
package se.apogo.kdomai.client

import org.json4s.NoTypeHints
import org.json4s.jackson.Serialization

trait JsonSerializable {
  import org.json4s.native.JsonMethods._
  implicit val formats = Serialization.formats(NoTypeHints)
  def toJson: String = {
    val json = Serialization.writePretty(this)
    pretty(render(parse(json)))
  }
}

case class JsonString(string: String) extends JsonSerializable {
  override def toJson: String = string
} 
开发者ID:mratin,项目名称:kdom-ai,代码行数:18,代码来源:JsonSerializable.scala


示例15: TimestampSerializer

//设置package包名称以及导入依赖的类
package articlestreamer.shared.marshalling

import java.sql.Timestamp

import articlestreamer.shared.exception.exceptions._
import com.typesafe.scalalogging.LazyLogging
import org.json4s.JsonAST.{JInt, JLong}
import org.json4s.{CustomSerializer, NoTypeHints, native}

trait CustomJsonFormats extends LazyLogging {

  val dformat: String = "yyyy-MM-dd hh:mm:ss"

  case object TimestampSerializer extends CustomSerializer[java.sql.Timestamp](format => (
    {
      case JInt(l) =>
        try {
          new Timestamp(l.toLong)
        } catch {
          case ex: Throwable => {
            logger.error(s"Error while parsing date : ${ex.getStackTraceAsString}")
            null
          }
        }
      case JLong(l) =>
        try {
          new Timestamp(l)
        } catch {
          case ex: Throwable => {
            logger.error(s"Error while parsing date : ${ex.getStackTraceAsString}")
            null
          }
        }
      case _ => null
    },
    {
      case ts: Timestamp =>
        JLong(ts.getTime)
    }
    )
  )

  implicit val json4sFormats =  native.Serialization.formats(NoTypeHints) + TimestampSerializer

} 
开发者ID:firens,项目名称:article-streamer,代码行数:46,代码来源:CustomJsonFormats.scala


示例16: HttpServer

//设置package包名称以及导入依赖的类
package com.pragmasoft.eventaggregator.http

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import akka.util.Timeout
import com.typesafe.config.Config
import com.typesafe.scalalogging.LazyLogging
import de.heikoseeberger.akkahttpjson4s.Json4sSupport
import org.json4s.jackson.Serialization
import org.json4s.{NoTypeHints, jackson}

import scala.concurrent.duration._
import scala.util.{Failure, Success}

class HttpServer(port: Int)(implicit actorSystem: ActorSystem) extends LazyLogging with Json4sSupport {

  private val metaService = MetaService.create()

  implicit val materializer = ActorMaterializer()
  implicit val timeout = Timeout(10.seconds)

  implicit val serialization = jackson.Serialization // or native.Serialization
  implicit val jsonFormats = Serialization.formats(NoTypeHints)

  val route =
    path("meta") {
      get {
        complete(metaService.metaInfo)
      }
    }

  def start(): Unit = {
    implicit val executionContext = actorSystem.dispatcher

    Http().bindAndHandle(route, "0.0.0.0", port).onComplete {
      case Success(binding) =>
        logger.info("HTTP server started successfully and bound to {}", binding.localAddress)

      case Failure(ex) =>
        logger.error(s"Error while starting HTTP server ${ex.getMessage}", ex)
    }
  }
} 
开发者ID:galarragas,项目名称:event-aggregator,代码行数:46,代码来源:http.scala


示例17: HttpService

//设置package包名称以及导入依赖的类
package com.example.services

import com.example.ApiSettings
import org.json4s.NoTypeHints
import org.json4s.native.Serialization
import org.json4s.native.Serialization.read

class HttpService extends HttpServiceTrait {

  implicit val formats = Serialization.formats(NoTypeHints)

  def get[T](url: String)(implicit m: Manifest[T]): T = {

    val jsonString = scala.io.Source.fromURL(buildUrl(url)).mkString
    read[T](jsonString)
  }
}

object HttpService {
  def apply() = new HttpService()
}

trait HttpServiceTrait {

  val API_SECRET = ApiSettings.secret
  val API_URL = "https://maps.googleapis.com"

  def buildUrl(url: String): String = {
    s"$API_URL$url&key=$API_SECRET"
  }
} 
开发者ID:divanvisagie,项目名称:lazy-places,代码行数:32,代码来源:HttpService.scala


示例18: Messenger

//设置package包名称以及导入依赖的类
package com.example.services

import com.example.models.SystemMessage
import com.rabbitmq.client.{Channel, Connection, ConnectionFactory}
import org.json4s.NoTypeHints
import org.json4s.native.Serialization
import org.json4s.native.Serialization.write

class Messenger {
  private val QUEUE_NAME: String = "places"
  implicit val formats = Serialization.formats(NoTypeHints)


  def send(message: String) : Unit = {
    val factory: ConnectionFactory = new ConnectionFactory
    factory.setHost("localhost")
    val connection: Connection = factory.newConnection
    val channel: Channel = connection.createChannel


    channel.queueDeclare(QUEUE_NAME, false, false, false, null)
    channel.basicPublish("", QUEUE_NAME, null, message.getBytes())


    channel.close()
    connection.close()
  }

  def send(message: SystemMessage): Unit = {
    send(write(message))
  }

}
object Messenger {
  def apply() = new Messenger()
} 
开发者ID:divanvisagie,项目名称:lazy-places,代码行数:37,代码来源:Messenger.scala


示例19: HelloLambda

//设置package包名称以及导入依赖的类
package com.virtuslab.lambda.hello

import java.io.{InputStream, OutputStream, OutputStreamWriter}

import com.amazonaws.services.lambda.runtime.{Context, RequestStreamHandler}
import com.virtuslab.lambda.hello.HelloLambda.formats
import org.json4s.NoTypeHints
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization._

object HelloLambda {
  implicit val formats = Serialization.formats(NoTypeHints)
}

class HelloLambda extends RequestStreamHandler {

  override def handleRequest(input: InputStream, output: OutputStream, context: Context): Unit = {
    context.getLogger.log(s"Log: ${context.getRemainingTimeInMillis}")
    println(s"Test ${context.getAwsRequestId}")

    try {
      val writer = new OutputStreamWriter(output, "UTF-8")
      writer.write(write(s"Fetched with ID: ${context.getAwsRequestId}"))
      writer.flush()
      writer.close()
    } catch {
      case e: Throwable => context.getLogger.log(s"exception? -> ${e.getCause}")
    }
  }
} 
开发者ID:pdolega,项目名称:lambda-samples,代码行数:31,代码来源:HelloLambda.scala


示例20: Response

//设置package包名称以及导入依赖的类
package com.virtuslab.lambda.http

import java.io.{InputStream, OutputStream, OutputStreamWriter}

import com.amazonaws.services.lambda.runtime.{Context, RequestStreamHandler}
import org.json4s.NoTypeHints
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization._
import HttpLambda.formats

case class Response(body: Option[String] = None,
                    statusCode: Int = 200,
                    headers: Map[String, Any] = Map.empty[String, Any])



object HttpLambda {
  implicit val formats = Serialization.formats(NoTypeHints)
}

class HttpLambda extends RequestStreamHandler {

  override def handleRequest(input: InputStream, output: OutputStream, context: Context): Unit = {
    context.getLogger.log(s"Log: ${context.getRemainingTimeInMillis}")
    println(s"Test ${context.getAwsRequestId}")
    
    try {
      val response = write(Response(Some(s"Fetched with ID: ${context.getAwsRequestId}")))
      context.getLogger.log(s"Generated response is: ${response}")

      val writer = new OutputStreamWriter(output, "UTF-8")
      writer.write(response)
      writer.flush()
      writer.close()
    } catch {
      case e: Throwable => context.getLogger.log(s"exception? -> ${e}")
    }
  }
} 
开发者ID:pdolega,项目名称:lambda-samples,代码行数:40,代码来源:HttpLambda.scala



注:本文中的org.json4s.NoTypeHints类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala Manifest类代码示例发布时间:2022-05-23
下一篇:
Scala Driver类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap