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

Scala DefaultFormats类代码示例

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

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



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

示例1: FibonacciREST

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

import com.doanduyhai.service.FibonacciService
import org.json4s.{DefaultFormats, Formats}
import org.scalatra.{InternalServerError, BadRequest, ScalatraServlet}
import org.scalatra.json.JacksonJsonSupport

class FibonacciREST extends ScalatraServlet with JacksonJsonSupport {

  protected implicit val jsonFormats: Formats = DefaultFormats

  before() {
    contentType = formats("json")
  }

  get("/:rank") {
    val rank = params("rank").toInt
    try {
      FibonacciService.computeFibonacci(rank)
    } catch {
      case ex: IllegalArgumentException => BadRequest(ex.getMessage)
      case throwable: Throwable => InternalServerError(throwable.getMessage)
    }
  }


  notFound {
    contentType = "text/html"
    serveStaticResource() getOrElse resourceNotFound()
  }
} 
开发者ID:doanduyhai,项目名称:FibonacciScalaDemo,代码行数:32,代码来源:FibonacciREST.scala


示例2: SimpleKafkaProducer

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

import java.util.Properties
import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}
import org.json4s.{DefaultFormats, jackson}

class SimpleKafkaProducer(kafkaSocket: Socket, topic: String, brokers: Int = 1) {

  private val serializer = "org.apache.kafka.common.serialization.StringSerializer"

  private def configuration = {
    val props = new Properties()
    props.put("bootstrap.servers", kafkaSocket.toString())
    props.put("key.serializer", serializer)
    props.put("value.serializer", serializer)
    props
  }

  def send[T <: AnyRef](message: T) = {
    implicit val serialization = jackson.Serialization
    implicit val formats = DefaultFormats

    val producer = new KafkaProducer[String, String](configuration)
    val jsonMessage = serialization.write[T](message)
    val data = new ProducerRecord[String, String](topic, jsonMessage)

    producer.send(data)
    producer.close()
  }
} 
开发者ID:frossi85,项目名称:financial-statistics-crawler,代码行数:31,代码来源:SimpleKafkaProducer.scala


示例3: ItemController

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

import javax.inject.Inject

import com.github.tototoshi.play2.json4s.native.Json4s
import models.{Item, ItemDetail}
import org.json4s.{DefaultFormats, Extraction}
import parsers.ItemParser
import play.api.mvc.{Action, Controller}
import requests.UploadZipItemForm
import scalikejdbc.DB

class ItemController @Inject()(json4s: Json4s) extends Controller {
  import json4s._
  import Responses._
  import models.PersistItem.getItemId
  implicit val formats = DefaultFormats

  def list() = Action {
    import models.Aliases.i
    val items = Item.findAll(i.name :: Nil)
    Ok(Extraction.decompose(items))
  }

  def show(itemId: Long) = Action {
    Item.findById(itemId).fold(notFound(s"itemId = ${itemId}")) { item =>
      Ok(Extraction.decompose(item))
    }
  }

  def upload() = Action(parse.multipartFormData){ implicit req =>
    UploadZipItemForm.fromReq(req).fold(BadRequest("Form error")){ form =>
      DB localTx { implicit session =>
        ZipUtil.inputStreams(form.file.ref.file).foreach{ is =>
          ItemParser.parse(is).foreach{ item =>
            val itemId = getItemId(item.name)
            ItemDetail.deleteById(itemId)
            ItemDetail.create(item.detail(itemId))
          }
        }
      }
      Redirect(routes.MyAssets.at("uploader.html"))
    }
  }
} 
开发者ID:ponkotuy,项目名称:FactorioRecipe,代码行数:46,代码来源:ItemController.scala


示例4: TwitterService

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

import javax.inject.{Inject, Singleton}

import akka.actor.{ActorRef, ActorSystem}
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Sink
import com.inspiringsolutions.tweet.actors.CompleteStream
import com.inspiringsolutions.tweet.models.{LimitNotice, Tweet}
import org.json4s.DefaultFormats
import org.json4s.native.JsonMethods._
import org.slf4j.LoggerFactory
import play.api.Play

import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Failure, Success, Try}

@Singleton
class TwitterService @Inject() (twitterStreamService: TwitterStreamProducerService)  {

  private val log = LoggerFactory.getLogger(getClass)

  implicit lazy val actorSystem: ActorSystem = Play.unsafeApplication.injector.instanceOf[ActorSystem]
  implicit val materializer = ActorMaterializer()

  implicit val formats = DefaultFormats

  def processStreamToActorRef(streamConsumerRef: ActorRef, hashTag: String) {
    val streamFuture = twitterStreamService.produceStream(hashTag)

    streamFuture.onComplete {
      case Failure(ex) => log.error("Error while processing stream", ex)
      case Success(stream) =>
        stream.scan("")((acc, curr) => {
          if (acc.contains("\r\n"))
            curr.utf8String
          else
            acc + curr.utf8String
        })
        .filter(_.contains("\r\n")).filterNot(_.trim.isEmpty)
        .map { tryParse }
        .runWith(Sink.actorRef(streamConsumerRef, CompleteStream))
    }
  }

  private def tryParse(json: String) = {
    val parsed = parse(json)
    val tweetAttempt = Try(parsed.extract[Tweet])
    if (tweetAttempt.isSuccess) {
      tweetAttempt
    } else {
      Try(parsed.extract[LimitNotice])
    }
  }
} 
开发者ID:gitter-badger,项目名称:inspiring-tooling,代码行数:56,代码来源:TwitterService.scala


示例5: DataConsumer

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

import akka.http.scaladsl.server.Directives._
import de.heikoseeberger.akkahttpjson4s.Json4sSupport
import org.json4s.jackson.Serialization.writePretty
import org.json4s.{DefaultFormats, jackson}

import scala.concurrent.Future

object DataConsumer extends Json4sSupport {

  implicit val serialization = jackson.Serialization // or native.Serialization
  implicit val formats = DefaultFormats

  val route =
    path("data") {
      post {
      entity(as[RootObject]) {
        data =>
          println(writePretty(data))
          complete(Future.successful(data.toString))
      }

      }
    }
} 
开发者ID:rmorais,项目名称:akka-http-playground,代码行数:27,代码来源:DataConsumer.scala


示例6: TweetReader

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

import org.json4s._
import org.json4s.native.JsonMethods._
import org.json4s.DefaultFormats

object TweetReader {

  implicit val format = new DefaultFormats {
  }

  def getTweets(json: String): List[Tweet] = parse(json).extract[List[Tweet]]

  def toTweetSet(l: List[Tweet]): TweetSet = l.foldLeft(new Empty: TweetSet)(_.incl(_))

  def unparseToData(tws: List[Tweet]): String = {
    val buf = new StringBuilder
    for (tw <- tws) {
      val json = "{ \"user\": \"" + tw.user + "\", \"text\": \"" +
        tw.text.replaceAll( """"""", "\\\\\\\"") + "\", \"retweets\": " +
        tw.retweets + ".0 }"
      buf.append(json + ",\n")
    }
    buf.toString()
  }

  val sites = List("gizmodo", "TechCrunch", "engadget", "amazondeals", "CNET", "gadgetlab", "mashable")

  private val gizmodoTweets = getTweets(TweetData.gizmodo)
  private val techCrunchTweets = getTweets(TweetData.TechCrunch)
  private val engadgetTweets = getTweets(TweetData.engadget)
  private val amazondealsTweets = getTweets(TweetData.amazondeals)
  private val cnetTweets = getTweets(TweetData.CNET)
  private val gadgetlabTweets = getTweets(TweetData.gadgetlab)
  private val mashableTweets = getTweets(TweetData.mashable)

  private val sources = List(gizmodoTweets, techCrunchTweets, engadgetTweets, amazondealsTweets, cnetTweets, gadgetlabTweets, mashableTweets)

  val tweetMap: Map[String, List[Tweet]] =
    Map() ++ Seq(sites(0) -> gizmodoTweets,
      sites(1) -> techCrunchTweets,
      sites(2) -> engadgetTweets,
      sites(3) -> amazondealsTweets,
      sites(4) -> cnetTweets,
      sites(5) -> gadgetlabTweets,
      sites(6) -> mashableTweets)

  val tweetSets: List[TweetSet] = sources.map(toTweetSet)

  private val siteTweetSetMap: Map[String, TweetSet] =
    Map() ++ (sites zip tweetSets)

  private def unionOfAllTweetSets(curSets: List[TweetSet], acc: TweetSet): TweetSet =
    if (curSets.isEmpty) acc
    else unionOfAllTweetSets(curSets.tail, acc.union(curSets.head))

  val allTweets: TweetSet = unionOfAllTweetSets(tweetSets, new Empty)
} 
开发者ID:mumukiller,项目名称:scala-course-one,代码行数:59,代码来源:TweetReader.scala


示例7: JsonExtraction

//设置package包名称以及导入依赖的类
package uk.gov.hmrc.utils.json

import java.net.{URI, URL}

import org.json4s.JsonAST.JString
import org.json4s.jackson.JsonMethods.parse
import org.json4s.{CustomSerializer, DefaultFormats, Formats, JNull}

object JsonExtraction {

  val formats = DefaultFormats + json4sDateTimeSerializer + json4sLocalDateSerializer + UriSerializer + UrlSerializer + Json4sIntToBigDecimalSerializer

  def apply[A](body: String)(implicit m: Manifest[A], formats: Formats = formats): A = extractResponse[A](body)

  private def extractResponse[A](body: String)(implicit m: Manifest[A], format: Formats = formats): A = Option(body) match {
    case Some(b) if b.length > 0 =>
      try {
        parse(b, useBigDecimalForDouble = true).extract
      } catch {
        case t: Throwable =>
          throw t
      }
    case _ => throw new IllegalArgumentException("A string value is required for transformation")
  }

  case object UriSerializer extends CustomSerializer[URI](format => ( {
    case JString(uri) => URI.create(uri)
    case JNull => null
  }, {
    case uri: URI => JString(uri.toString)
  }
  ))

  case object UrlSerializer extends CustomSerializer[URL](format => ( {
    case JString(url) => new URL(url)
    case JNull => null
  }, {
    case url: URL => JString(url.toString)
  }
  ))

} 
开发者ID:danewatts,项目名称:zap-automation,代码行数:43,代码来源:JsonExtraction.scala


示例8: JsoupTest

//设置package包名称以及导入依赖的类
package org.dele.misc.scraping



import jdk.nashorn.internal.parser.JSONParser
import org.json4s.DefaultFormats
import org.jsoup._

import collection.JavaConverters._
import org.json4s.jackson.JsonMethods._
object JsoupTest extends App {

  val ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"
  val searchTerm = "whitebacked planthopper"
  val searchUrl = "https://www.google.com/search?site=imghp&tbm=isch&source=hp&biw=1920&bih=955&q=" + searchTerm.replace(" ", "+") + "&gws_rd=cr";

  val doc = Jsoup.connect(searchUrl)
    .userAgent(ua)
    .referrer("https://www.google.com/").get()

  implicit val fmt = DefaultFormats
  doc.select("div.rg_meta").asScala.foreach{ elem =>
    val src = elem.text()
    val json = parse(src)
    val url = (json \ "ou")
    if (url != null) {
      val out = url.extract[String]
      println(out)
    }
  }

  println("end")
} 
开发者ID:new2scala,项目名称:text-util,代码行数:34,代码来源:JsoupTest.scala


示例9: SimpleKafkaConsumer

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

import java.nio.charset.StandardCharsets
import java.util.Properties
import kafka.consumer.ConsumerConfig
import org.json4s.{DefaultFormats, jackson}
import scala.collection.immutable.HashMap

class SimpleKafkaConsumer(kafkaSocket: Socket, zooKeeperSocket: Socket, groupId: String, topic: String) {

  private def configuration = {
    val deserializer = "org.apache.kafka.common.serialization.StringDeserializer"
    val props = new Properties()
    props.put("bootstrap.servers", kafkaSocket.toString())
    props.put("key.deserializer", deserializer)
    props.put("value.deserializer", deserializer)
    props.put("group.id", groupId)
    props.put("consumer.id", "consumer0")
    props.put("consumer.timeout", "-1")
    props.put("auto.offset.reset", "smallest")
    props.put("zookeeper.sync.time.ms", "200")
    props.put("zookeeper.session.timeout.ms", "6000")
    props.put("zookeeper.connect", zooKeeperSocket.toString())
    props.put("num.consumer.fetchers", "2")
    props.put("rebalance.max.retries", "4")
    props.put("auto.commit.interval.ms", "1000")
    props
  }

  private val consumer = kafka.consumer.Consumer.create(new ConsumerConfig(configuration))

  def read[T <: AnyRef]()(implicit m: Manifest[T]): Iterable[T] = {
    implicit val serialization = jackson.Serialization
    implicit val formats = DefaultFormats

    val topicCountMap = HashMap(topic -> 1)
    val consumerMap = consumer.createMessageStreams(topicCountMap)
    val stream = consumerMap.get(topic).get(0)
    val iterator = stream.iterator()

    iterator.map(x => serialization.read[T](new String(x.message(), StandardCharsets.UTF_8))).toStream
  }

  def shutdown() = {
    consumer.shutdown()
  }
} 
开发者ID:frossi85,项目名称:financial-statistics-collector,代码行数:48,代码来源:SimpleKafkaConsumer.scala


示例10: save

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

import model.IDTrait
import com.sksamuel.elastic4s.ElasticDsl.index
import com.sksamuel.elastic4s.source.JsonDocumentSource
import org.json4s.jackson.Serialization._
import org.json4s.{DefaultFormats, Formats, FieldSerializer}
import com.sksamuel.elastic4s.{ElasticClient}
import com.sksamuel.elastic4s.ElasticDsl._
import org.json4s.FieldSerializer.renameTo
import org.elasticsearch.common.settings.ImmutableSettings


  def save[T <: IDTrait[E]: Manifest, E](record: T, indexName: String, indexType: String): Unit = {
    val rename = FieldSerializer[T](renameTo("_id", s"${indexType}_id"))
    implicit val format: Formats = DefaultFormats + rename ++ org.json4s.ext.JodaTimeSerializers.all

    val _id = record._id
    val jsonString = write(record)
    
    client.execute {
      index into indexName -> indexType doc JsonDocumentSource(jsonString) id _id
    }
  }

  def close = {
    client.close()
  }

} 
开发者ID:krzasteka,项目名称:ScalaTest,代码行数:31,代码来源:ElasticsearchService.scala


示例11: Connect4API

//设置package包名称以及导入依赖的类
package com.ntsdev.connect4.web


import com.ntsdev.connect4.game.Game
import com.ntsdev.connect4.model.{Cell, Board}
import com.ntsdev.connect4.wire.OptionCellSerializer
import org.json4s.{DefaultFormats, Formats}
import org.scalatra._
import org.scalatra.json._

import scala.concurrent.ExecutionContext


class Connect4API extends ScalatraServlet with JacksonJsonSupport with FutureSupport {
  protected implicit lazy val jsonFormats: Formats = DefaultFormats + new OptionCellSerializer

  override val executor: ExecutionContext = ExecutionContext.global

  get("/startGame"){
    val advanced = params("advanced")
    val useAdvancedPlayer = advanced eq "true"
    contentType = formats("json")
    val game = new Game(Board, advanced = useAdvancedPlayer)
    game.grid.board
  }

  post("/makeMove"){
    val grid = parsedBody.extract[List[Option[Cell]]]
    val game = new Game(new Board(grid))
    val column = params("column").toInt
    val newGame = game.makeMove(column)

    if(!"".equals(newGame.winningPlayer)){
      val winningPlayer = newGame.winningPlayer
      Ok(newGame.grid.board, Map("Winning-Player" -> winningPlayer))
    }
    else {
      Ok(newGame.grid.board)
    }
  }
} 
开发者ID:neilshannon,项目名称:connect4,代码行数:42,代码来源:Connect4API.scala


示例12: OptionCellSerializerSpec

//设置package包名称以及导入依赖的类
package com.ntsdev.connect4.wire

import com.ntsdev.connect4.model.{BlackCell, RedCell}
import org.json4s.{DefaultFormats, Formats}
import org.specs2.mutable.Specification

class OptionCellSerializerSpec extends Specification {

  private implicit lazy val jsonFormats: Formats = DefaultFormats + new OptionCellSerializer
  private val serialization = org.json4s.jackson.Serialization

  "the option cell serializer" should {
    "serialize an Option[Cell]" in {
      val redCell = RedCell
      val listOfOptionCell = List(Some(redCell))
      val redJson = serialization.write(listOfOptionCell)
      redJson shouldEqual "[{\"cell\":\"[R]\"}]"

      val blackCell = BlackCell
      val listOfBlackOptionCell = List(Some(blackCell))
      val blackJson = serialization.write(listOfBlackOptionCell)
      blackJson shouldEqual "[{\"cell\":\"[B]\"}]"

      val listOfBlankOptionCell = List(None)
      val blankJson = serialization.write(listOfBlankOptionCell)
      blankJson shouldEqual "[{\"cell\":\"[-]\"}]"

    }
  }
} 
开发者ID:neilshannon,项目名称:connect4,代码行数:31,代码来源:OptionCellSerializerSpec.scala


示例13: Connect4APISpec

//设置package包名称以及导入依赖的类
package com.ntsdev.connect4.web

import org.json4s.{DefaultFormats, Formats}
import org.scalatra.test.specs2.MutableScalatraSpec

class Connect4APISpec extends MutableScalatraSpec {

  protected implicit lazy val jsonFormats: Formats = DefaultFormats

  addServlet(classOf[Connect4API], "/*")

  "GET /startGame" should {
    "begin a game and return the board" in {
        get("/startGame?advanced=true") {
          status must_== 200
        }
    }

    "make a move" in {
      val postBody =
        """
          |[{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},
          |{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},
          |{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},
          |{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},
          |{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},
          |{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"},{"cell":"[-]"}]
        """.stripMargin

      post("/makeMove?column=0", postBody, Map("Content-Type" -> "application/json")){
        status must_== 200
      }
    }
  }
} 
开发者ID:neilshannon,项目名称:connect4,代码行数:36,代码来源:Connect4APISpec.scala


示例14: Of

//设置package包名称以及导入依赖的类
package com.zhranklin.notice.script

import org.json4s.{DefaultFormats, ShortTypeHints, TypeHints}

trait MessageJsonFormats {
  implicit val format = new DefaultFormats {
    override val typeHintFieldName = "type"
    override val typeHints: TypeHints = ShortTypeHints(List(
      classOf[listsources],
      classOf[err],
      classOf[succ],
      classOf[getnews],
      classOf[fetch_test],
      classOf[getpictures],
      classOf[create_source],
      classOf[fetchnews]
    ))
  }
} 
开发者ID:zhranklin,项目名称:notice_crawler,代码行数:20,代码来源:MessageJsonFormats.scala


示例15: Person

//设置package包名称以及导入依赖的类
package com.sfxcode.nosql.mongo.model

import java.text.SimpleDateFormat
import java.util.Date

import org.json4s.DefaultFormats
import org.json4s.native.Serialization._
import org.mongodb.scala.bson.ObjectId

import scala.io.Source

case class Person(
  id: Long,
  guid: String,
  isActive: Boolean,
  balance: Double,
  picture: String,
  age: Int,
  name: String,
  gender: String,
  email: String,
  phone: String,
  address: String,
  about: String,
  registered: Date,
  tags: List[String],
  friends: List[Friend],
  greeting: String,
  favoriteFruit: String,
  _id: ObjectId = new ObjectId()
)

case class Friend(id: Long, name: String)

object Person {

  implicit val formats = new DefaultFormats {
    override def dateFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
  }

  val personList: List[Person] = read[List[Person]](fromJson("/test_data.json"))

  def fromJson(name: String): String = {
    val is = getClass.getResourceAsStream(name)
    Source.fromInputStream(is, "UTF-8").getLines().mkString
  }

} 
开发者ID:sfxcode,项目名称:simple-mongo,代码行数:49,代码来源:Person.scala


示例16: Metadata

//设置package包名称以及导入依赖的类
package io.hydrosphere.spark_ml_serving

case class Metadata(
  `class`: String,
  timestamp: Long,
  sparkVersion: String,
  uid: String,
  paramMap: Map[String, Any],
  numFeatures: Option[Int],
  numClasses: Option[Int],
  numTrees: Option[Int]
)

object Metadata {

  import org.json4s.DefaultFormats
  import org.json4s.jackson.JsonMethods._

  implicit val formats = DefaultFormats

  def fromJson(json: String): Metadata = {
    parse(json).extract[Metadata]
  }
} 
开发者ID:Hydrospheredata,项目名称:spark-ml-serving,代码行数:25,代码来源:Metadata.scala


示例17: SlackWebHookAppender

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

import ch.qos.logback.classic.spi.ILoggingEvent
import ch.qos.logback.core.Layout
import ch.qos.logback.core.LayoutBase
import ch.qos.logback.core.UnsynchronizedAppenderBase
import scalaj.http._
import org.json4s.DefaultFormats
import org.json4s.native.Serialization

class SlackWebHookAppender extends UnsynchronizedAppenderBase[ILoggingEvent]{
  implicit val formats = DefaultFormats

  private var channel: Option[String] = None
  private var webHookUrl: Option[String] = None
  private var username: Option[String] = None
  private var iconEmoji: Option[String] = None
  private var layout: Layout[ILoggingEvent]  = defaultLayout

  private def defaultLayout:Layout[ILoggingEvent] = new LayoutBase[ILoggingEvent]{
    def doLayout(event: ILoggingEvent) :String =
      s"-- [${event.getLevel}] - ${event.getFormattedMessage.replaceAll("\n", "\n\t")}"
  }

  override def append(evt: ILoggingEvent) = {
    val optResult = for {
      c <- channel
      w <- webHookUrl
    } yield {
      val attachment = Attachment(layout.doLayout(evt), "danger")
      val payload = Payload(c,
        username.getOrElse("Slack Logback Appender"),
        iconEmoji.getOrElse(":japanese_goblin:"),
        "Error detected!!",
        Some(Seq(attachment)))
      val res = Http(w).postForm(Seq("payload" -> Serialization.write(payload))).asString
      if(res.code == 200) Result.Success
      else Result.Failure(res.body.toString)
    }

    optResult.getOrElse(Result.Failure("channel or webHookUrl is not set")) match {
      case Result.Success => ()
      case Result.Failure(msg) =>
        val errorMessage = s"Error in Logback-Slack Web Hook Appender: $msg"
        new RuntimeException(errorMessage).printStackTrace
        addError(errorMessage)
    }

  }

  def setChannel(t: String) = { channel = Some(if(t.startsWith("#")) t else "#" + t) }
  def setWebHookUrl(w: String) = {webHookUrl = Some(w)}
  def setUsername(u: String) = {username = Some(u)}
  def setIconEmoji(i: String) = {
    val prefix = if(i.startsWith(":")) "" else ":"
    val suffix = if(i.endsWith(":")) "" else ":"
    iconEmoji = Some(prefix + i + suffix)
  }
  def setLayout(l: Layout[ILoggingEvent]) = {layout = l}
} 
开发者ID:yuki-mt,项目名称:logback-slack-webhook-appender,代码行数:61,代码来源:SlackWebhookAppender.scala


示例18: FunctionLink

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

import org.json4s.{ DefaultFormats, Formats, jackson, Serialization }
import org.json4s._

case class FunctionLink(order: Int, url: String, title: String)
  extends Ordered[FunctionLink]
{
  def compare(that: FunctionLink) = order.compare(that.order)
}

object CommonSerializer extends common.JsonSerializer {
	def identifier = 0xfeca

	implicit val formats = new DefaultFormats {
		override val typeHintFieldName = "_t"
		override val typeHints = ShortTypeHints(List(
			classOf[FunctionLink],
			classOf[Stat]
		))
	} ++ org.json4s.ext.JodaTimeSerializers.all
} 
开发者ID:enpassant,项目名称:rapids,代码行数:23,代码来源:CommonSerializer.scala


示例19: Companies

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

import authes.AuthConfigImpl
import authes.Role.{Administrator, NormalUser}
import com.github.tototoshi.play2.json4s.Json4s
import com.google.inject.Inject
import jp.t2v.lab.play2.auth.AuthElement
import models.{Company, Fare, TrainType, TrainTypeSerializer}
import org.json4s.{DefaultFormats, Extraction}
import play.api.mvc.Controller
import queries.{CreateCompany, CreateFares}
import scalikejdbc._

class Companies @Inject() (json4s: Json4s) extends Controller with AuthElement with AuthConfigImpl {
  import Responses._
  import json4s._
  implicit val formats = DefaultFormats + TrainTypeSerializer

  def list() = StackAction(AuthorityKey -> Administrator) { implicit req =>
    Ok(Extraction.decompose(Company.findAll(Seq(Company.defaultAlias.id))))
  }

  def create() = StackAction(json, AuthorityKey -> Administrator) { implicit req =>
    req.body.extractOpt[CreateCompany].fold(JSONParseError) { company =>
      DB localTx { implicit session =>
        val id = company.company.save()
        Ok(id.toString)
      }
    }
  }

  // Fare table?????????????????
  def existsFare() = StackAction(AuthorityKey -> NormalUser) { implicit req =>
    Ok(Extraction.decompose(Fare.existsFare()(AutoSession)))
  }

  def fares(companyId: Long, trainType: Int) = StackAction(AuthorityKey -> NormalUser) { implicit req =>
    import models.DefaultAliases.f
    TrainType.find(trainType).fold(notFound(s"train type: ${trainType}")) { tType =>
      val fares = Fare.findAllBy(sqls.eq(f.companyId, companyId).and.eq(f.trainType, tType.value))
      Ok(Extraction.decompose(fares))
    }
  }

  def createFares(companyId: Long, trainType: Int) = StackAction(json, AuthorityKey -> Administrator) { implicit req =>
    req.body.extractOpt[CreateFares].fold(JSONParseError) { fares =>
      TrainType.find(trainType).fold(notFound(s"train type: ${trainType}")) { tType =>
        DB localTx { implicit session =>
          val f = Fare.column
          Fare.deleteBy(sqls.eq(f.companyId, companyId).and.eq(f.trainType, trainType))
          fares.fares.map(_.fare(companyId, tType)).foreach(_.save)
        }
        Ok("Success")
      }
    }
  }
} 
开发者ID:ponkotuy,项目名称:train-stamp-rally,代码行数:58,代码来源:Companies.scala


示例20: Releases

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

import authes.AuthConfigImpl
import authes.Role.Administrator
import com.github.tototoshi.play2.json4s.Json4s
import com.google.inject.Inject
import jp.t2v.lab.play2.auth.AuthElement
import models.{Diagram, TrainTypeSerializer}
import org.json4s.{DefaultFormats, Extraction}
import scalikejdbc._
import play.api.mvc.Controller
import responses.{DiagramResponse, ReleaseResponse}

class Releases @Inject() (json4s: Json4s) extends Controller with AuthElement with AuthConfigImpl {
  import json4s._

  implicit val format = DefaultFormats + TrainTypeSerializer

  def list() = StackAction(AuthorityKey -> Administrator) { implicit req =>
    import models.DefaultAliases.d
    val diagrams = Diagram.joins(Diagram.stopStationRef).findAllBy(sqls.isNotNull(d.staging))
    val result = diagrams.groupBy(_.staging.get).map {
      case (staging, ds) =>
        ReleaseResponse(staging, ds.map(DiagramResponse.fromDiagram))
    }
    Ok(Extraction.decompose(result))
  }
} 
开发者ID:ponkotuy,项目名称:train-stamp-rally,代码行数:29,代码来源:Releases.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala ObjectMapper类代码示例发布时间:2022-05-23
下一篇:
Scala I18nSupport类代码示例发布时间: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