当前位置: 首页>>代码示例>>Scala>>正文


Scala DeserializationFeature类代码示例

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


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

示例1: JsonUtil

//设置package包名称以及导入依赖的类
import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper}
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule



object JsonUtil {
  val mapper = new ObjectMapper() with ScalaObjectMapper
  mapper.registerModule(DefaultScalaModule)
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

  def toJson(value: Map[Symbol, Any]): String = {
    toJson(value map { case (k,v) => k.name -> v})
  }

  def toJson(value: Any): String = {
    mapper.writeValueAsString(value)
  }

  def toMap[V](json:String)(implicit m: Manifest[V]) = fromJson[Map[String,V]](json)

  def fromJson[T](json: String)(implicit m : Manifest[T]): T = {
    mapper.readValue[T](json)
  }
}

object MarshallableImplicits {

  implicit class Unmarshallable(unMarshallMe: String) {
    def toMap: Map[String,Any] = JsonUtil.toMap(unMarshallMe)
    //def toMapOf[V]()(implicit m: Manifest[V]): Map[String,V] = JsonUtil.toMapOf[V](unMarshallMe)
    def fromJson[T]()(implicit m: Manifest[T]): T =  JsonUtil.fromJson[T](unMarshallMe)
  }

  implicit class Marshallable[T](marshallMe: T) {
    def toJson: String = JsonUtil.toJson(marshallMe)
  }
} 
开发者ID:hoover,项目名称:language,代码行数:39,代码来源:JsonUtil.scala

示例2: JsonObjectMapper

//设置package包名称以及导入依赖的类
package de.stema.util

import javax.inject.Singleton

import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper, SerializationFeature}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import de.stema.pullrequests.dto.PullRequestDTO

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

@Singleton
class JsonObjectMapper {
  private lazy val mapper = new ObjectMapper with ScalaObjectMapper
  mapper.registerModule(DefaultScalaModule)
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
  mapper.configure(SerializationFeature.INDENT_OUTPUT, true)
  mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
  mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)

  def getInstance[T](json: String)(implicit ct: ClassTag[T]): T =
    Try {
      mapper.readValue(json, ct.runtimeClass).asInstanceOf[T]
    } match {
      case Success(instance) => instance
      case Failure(e) => throw new IllegalStateException(s"Error during parsing of '$json'", e)
    }

  def getInstances[T](json: String)(implicit ct: ClassTag[T]): Seq[PullRequestDTO] =
    Try {
      mapper.readValue[Seq[PullRequestDTO]](json)
    } match {
      case Success(instances) => instances
      case Failure(e) => throw new IllegalStateException(s"Error during parsing of '$json'", e)
    }
} 
开发者ID:callidustaurus,项目名称:github-api,代码行数:39,代码来源:JsonObjectMapper.scala

示例3: JsonUtil

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

import java.io.StringWriter

import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper

import scala.reflect.{ClassTag, Manifest}

object JsonUtil {

  val mapper = new ObjectMapper() with ScalaObjectMapper
  mapper.registerModule(DefaultScalaModule)
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

  def toJson[T](data: T): String = {
    val out = new StringWriter()
    mapper.writeValue(out, data)
    out.toString
  }

  def fromJson[T: ClassTag](json: String)(implicit m: Manifest[T]): T =
    mapper.readValue[T](json)
} 
开发者ID:SarathChandran,项目名称:InventoryTracker,代码行数:26,代码来源:JsonUtil.scala

示例4: jsonUnmarshaller

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

import _root_.akka.http.scaladsl.marshalling.Marshaller
import _root_.akka.http.scaladsl.marshalling._
import _root_.akka.http.scaladsl.model.ContentType
import _root_.akka.http.scaladsl.model.HttpCharsets
import _root_.akka.http.scaladsl.model.HttpEntity
import _root_.akka.http.scaladsl.model.MediaType
import _root_.akka.http.scaladsl.unmarshalling.Unmarshaller
import _root_.akka.http.scaladsl.unmarshalling._
import _root_.akka.stream.Materializer
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.SerializationFeature
import org.json4s.DefaultFormats
import org.json4s.ext.JavaTypesSerializers
import org.json4s.jackson.Serialization


  protected implicit def jsonUnmarshaller[A: Manifest](implicit mat: Materializer): FromEntityUnmarshaller[A] =
    Unmarshaller.byteStringUnmarshaller
      .forContentTypes(jsonMediaType)
      .mapWithCharset { (data, charset) =>
        val input = if(charset == HttpCharsets.`UTF-8`) data.utf8String else data.decodeString(charset.nioCharset.name)
        jsonSerilaization.read(input)
      }

  org.json4s.jackson.JsonMethods.mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true)
    .configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false)
    .configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true)
    .configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false)
    .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
    .configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false)
    .configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true)
    .configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true)
    .configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true)
    .configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true)

} 
开发者ID:Chumper,项目名称:addda,代码行数:39,代码来源:JsonSerialization.scala

示例5: JsonMarshaller

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

import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper

object JsonMarshaller {
  val mapper = new ObjectMapper with ScalaObjectMapper
  mapper.registerModule(DefaultScalaModule)
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

  def toJson(value: Any): String = {
    mapper.writeValueAsString(value)
  }

  def toMap[V](json:String)(implicit m: Manifest[V]) = fromJson[Map[String,V]](json)

  def fromJson[T](json: String)(implicit m : Manifest[T]): T = {
    mapper.readValue[T](json)
  }
}

object MarshallableImplicits {

  implicit class Unmarshallable(unMarshallMe: String) {
    def toMapOf[V]()(implicit m: Manifest[V]): Map[String,V] = JsonMarshaller.toMap[V](unMarshallMe)
    def fromJson[T]()(implicit m: Manifest[T]): T =  JsonMarshaller.fromJson[T](unMarshallMe)
  }

  implicit class Marshallable[T](marshallMe: T) {
    def toJson: String = JsonMarshaller.toJson(marshallMe)
  }
} 
开发者ID:jeroenr,项目名称:reactive-mongo-demo,代码行数:34,代码来源:JsonMarshaller.scala

示例6: JacksonMapper

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

import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper}
import com.fasterxml.jackson.dataformat.javaprop.JavaPropsMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule

object JacksonMapper extends ObjectMapper {
  configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true)
  registerModule(DefaultScalaModule)
  setSerializationInclusion(JsonInclude.Include.NON_ABSENT)
}


// Instead of converting to/from JSON, this converts to/from nested key/value properties.
object JacksonPropertyMapper extends JavaPropsMapper {
  configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true)
  registerModule(DefaultScalaModule)
  setSerializationInclusion(JsonInclude.Include.NON_ABSENT)

  def productToKeyVals(p: Product): List[(String, String)] = {
    // This is a naive two-stage algorithm that works simply. Maybe it could be improved later.
    val props = writeValueAsString(p)
    val lines = props.split('\n')
    val keyVals =
      for (line <- lines
           if line.length > 1) yield {
        divide(line, '=')
      }
    keyVals.toList
  }

  
  private def divide(s: String, c: Char): (String, String) = {
    val i = s.indexOf(c)
    if (i < 0) s -> ""
    else {
      val w1 = s.substring(0, i)
      val rest = s.substring(i + 1)
      w1 -> rest
    }
  }
} 
开发者ID:hmrc,项目名称:bank-account-reputation-frontend,代码行数:44,代码来源:JacksonMapper.scala

示例7: GenericJsonSupport

//设置package包名称以及导入依赖的类
package com.flipkart.connekt.receptors.wire

import akka.http.scaladsl.marshalling.{PredefinedToEntityMarshallers, ToEntityMarshaller}
import akka.http.scaladsl.model.MediaTypes
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, PredefinedFromEntityUnmarshallers}
import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import com.flipkart.connekt.receptors.wire.GenericJsonSupport._
import scala.collection.mutable
import scala.reflect.ClassTag


object GenericJsonSupport {

  val jacksonModules = Seq(DefaultScalaModule)

  val mapper = new ObjectMapper() with ScalaObjectMapper
  mapper.registerModules(jacksonModules: _*)
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

  val m: mutable.Map[Class[_], ToEntityMarshaller[_]] = mutable.Map.empty[Class[_], ToEntityMarshaller[_]]
  val um: mutable.Map[Class[_], FromEntityUnmarshaller[_]] = mutable.Map.empty[Class[_], FromEntityUnmarshaller[_]]
}

trait JsonToEntityMarshaller extends PredefinedToEntityMarshallers {

  implicit def findMarshaller[T](implicit cTag: ClassTag[T]): ToEntityMarshaller[T] =
    m.getOrElseUpdate(cTag.runtimeClass, genericMarshaller[T]).asInstanceOf[ToEntityMarshaller[T]]

  def genericMarshaller[T]: ToEntityMarshaller[T] =
    stringMarshaller(MediaTypes.`application/json`)
      .compose[T](mapper.writeValueAsString)
}

trait JsonFromEntityUnmarshaller extends PredefinedFromEntityUnmarshallers {

  implicit def findUnmarshaller[T](implicit cTag: ClassTag[T]): FromEntityUnmarshaller[T] =
    um.getOrElseUpdate(cTag.runtimeClass, genericUnmarshaller[T](cTag)).asInstanceOf[FromEntityUnmarshaller[T]]

  def genericUnmarshaller[T](cTag: ClassTag[T]): FromEntityUnmarshaller[T] =
    stringUnmarshaller.forContentTypes(MediaTypes.`application/json`)
      .map(mapper.readValue(_, cTag.runtimeClass).asInstanceOf[T])
} 
开发者ID:ayush03agarwal,项目名称:connekt,代码行数:45,代码来源:JsonToEntityMarshaller.scala

示例8: JsonUtil

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

import java.text.SimpleDateFormat

import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter
import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper, PropertyNamingStrategy}
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper

object JsonUtil {
  private val dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZ"
  private val filter = SimpleBeanPropertyFilter.serializeAllExcept()
  private val javaTimeModule = new JavaTimeModule()

  val CamelCaseMapper = new ObjectMapper() with ScalaObjectMapper
  CamelCaseMapper.registerModules(DefaultScalaModule, javaTimeModule)
    .setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE)
    .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
    .configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false)
    .configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true)
    .setDateFormat(new SimpleDateFormat(dateFormat))

  val SnakeCaseMapper = new ObjectMapper() with ScalaObjectMapper
  SnakeCaseMapper.registerModules(DefaultScalaModule, javaTimeModule)
    .setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE)
    .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
    .configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false)
    .configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true)
    .setDateFormat(new SimpleDateFormat(dateFormat))

} 
开发者ID:crocker,项目名称:json-util,代码行数:33,代码来源:JsonUtil.scala

示例9: Serializer

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

import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper}
import com.fasterxml.jackson.module.scala.DefaultScalaModule

import scala.reflect.ClassTag


object Serializer {
    val mapper = new ObjectMapper()
      .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
    mapper.registerModule(DefaultScalaModule)
    val jsonWriter = mapper.writer()

    def toObject[T : ClassTag](jsonString: String, clazz: Class[T]) : T = {
        mapper.readValue(jsonString, clazz)
    }

    def toString(data : AnyRef) : String = {
        jsonWriter.writeValueAsString(data)
    }
} 
开发者ID:liuhb86,项目名称:splendor-ai,代码行数:23,代码来源:Serializer.scala

示例10: ELBSSLCertificateLambdaSpec

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

import com.amazonaws.services.lambda.runtime.events.SNSEvent
import com.amazonaws.services.lambda.runtime.events.SNSEvent.{SNS, SNSRecord}
import com.fasterxml.jackson.databind.{DeserializationFeature, JsonNode, ObjectMapper}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import org.scalatest.{FlatSpec, Matchers}

import scala.collection.JavaConversions._
import scala.collection.JavaConverters._
import scala.io.Source



class ELBSSLCertificateLambdaSpec extends FlatSpec with Matchers {
  val mapper = new ObjectMapper() with ScalaObjectMapper
  mapper.registerModule(DefaultScalaModule).configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

  def produceS3Event: JsonNode =
    mapper.readValue(Source.fromInputStream(getClass.getResourceAsStream("/sns_s3_event.json")).getLines.mkString, classOf[JsonNode])

  def toEvent: SNSEvent = {
    val event = new SNSEvent()
    val record = new SNSRecord()
    val sns = new SNS()
    val map = produceS3Event
    sns.setMessage(map.path("Records").get(0).path("Sns").path("Message").asText())
    record.setSns(sns)
    event.setRecords(List[SNSRecord](record))
    event
  }

  "An S3 event" should "run lambda successfully" in {
    val mainObj = new ELBSSLCertificateLambda
    val something = mainObj.configureELBCert(toEvent)
    something.asScala.head shouldBe "Status code for setting arn:aws:iam::my_acct:server-certificate/ocelotconsulting-demo.com ELB certificate for myelb is 200."
  }
} 
开发者ID:ocelotconsulting,项目名称:elb-ssl-cert-lambda,代码行数:40,代码来源:ELBSSLCertificateLambdaSpec.scala

示例11: Mapper

//设置package包名称以及导入依赖的类
package org.akka.templates

import akka.http.scaladsl.marshalling.Marshaller.withFixedContentType
import akka.http.scaladsl.marshalling.ToEntityMarshaller
import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpRequest}
import akka.http.scaladsl.unmarshalling.{FromRequestUnmarshaller, Unmarshal, Unmarshaller}
import akka.stream.Materializer
import com.fasterxml.jackson.annotation.JsonInclude.Include
import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper, PropertyNamingStrategy}
import com.fasterxml.jackson.module.scala.DefaultScalaModule

import scala.concurrent.ExecutionContext


package object json {
  val objectMapper = new ObjectMapper()
    .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
    .setSerializationInclusion(Include.NON_EMPTY)
    .setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE)
    .registerModule(DefaultScalaModule)

  implicit class ObjAsJsonUsingJackson(obj: Any) {
    def asJson: String = objectMapper.writeValueAsString(obj)
  }

  implicit class StringJsonAsCaseClass(json: String) {
    def asObject[T](implicit m: Manifest[T]): T = objectMapper.readValue(json, m.runtimeClass).asInstanceOf[T]
  }

  implicit def jsonMarshaller[T]: ToEntityMarshaller[T] =
    withFixedContentType(ContentTypes.`application/json`) { any =>
      HttpEntity(ContentTypes.`application/json`, any.asJson)
    }

  implicit def jsonUnmarshaller[T](implicit m: Manifest[T], materializer: Materializer): FromRequestUnmarshaller[T] =
    Unmarshaller[HttpRequest, T] {
      implicit ec: ExecutionContext => r => Unmarshal(r.entity).to[String].map(_.asObject[T])
    }
} 
开发者ID:gabfssilva,项目名称:akka-http-microservice-templates,代码行数:40,代码来源:json.scala

示例12: Main

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

import java.io.{ InputStream, OutputStream }
import java.net.URLDecoder

import com.fasterxml.jackson.databind.{ DeserializationFeature, ObjectMapper }
import com.fasterxml.jackson.module.scala.DefaultScalaModule

class Main {
  val scalaMapper = new ObjectMapper().registerModule(new DefaultScalaModule).configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

  def handler(input: InputStream, output: OutputStream): Unit = {
    val params = scalaMapper.readValue(input, classOf[SlackOutgoingData])
    println(params)
    val result = params.decodedText match {
      case "?????" => Some(s"?????, ${params.user_name}")
      case "Scala"      => Some("?????")
      case _            => None
    }

    result.foreach { r =>
      output.write( s"""{ "text": "$r" }""".getBytes("UTF-8"))
    }
  }
}

case class SlackOutgoingData(
  token: String,
  team_id: String,
  team_domain: String,
  service_id: String,
  channel_id: String,
  channel_name: String,
  timestamp: String,
  user_id: String,
  user_name: String,
  text: String,
  trigger_word: String) {

  val decodedText = URLDecoder.decode(text, "UTF-8")

} 
开发者ID:SAMMY7th,项目名称:aws-lambda-scala,代码行数:43,代码来源:Main.scala

示例13: JacksonSupport

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

import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper

object JacksonSupport {

  val mapper: ObjectMapper with ScalaObjectMapper = new ObjectMapper with ScalaObjectMapper
  mapper.registerModule(DefaultScalaModule)

  mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL)
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
  mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false)
  mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
  mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true)
  mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true)
} 
开发者ID:51zero,项目名称:eel-sdk,代码行数:21,代码来源:JacksonSupport.scala

示例14: JsonUtil

//设置package包名称以及导入依赖的类
package uk.ac.wellcome.utils

import com.fasterxml.jackson.databind.annotation.JsonSerialize
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper}
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule

import scala.util.Try

object JsonUtil {
  val mapper = new ObjectMapper() with ScalaObjectMapper

  mapper.registerModule(DefaultScalaModule)
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
  mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY)

  def toJson(value: Any): Try[String] =
    Try(mapper.writeValueAsString(value))

  def toMap[V](json: String)(implicit m: Manifest[V]) =
    fromJson[Map[String, V]](json)

  def fromJson[T](json: String)(implicit m: Manifest[T]): Try[T] =
    Try(mapper.readValue[T](json))
} 
开发者ID:wellcometrust,项目名称:platform-api,代码行数:27,代码来源:JsonUtil.scala

示例15: IAMServerCertificateLambda

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

import scala.collection.JavaConversions._
import com.amazonaws.services.identitymanagement.model.{NoSuchEntityException, UploadServerCertificateResult}
import com.amazonaws.services.lambda.runtime.events.SNSEvent
import com.amazonaws.services.s3.event.S3EventNotification
import com.amazonaws.services.s3.event.S3EventNotification.S3Entity
import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import com.ocelotconsulting.ssl.aws.iam.{DeleteCertificate, UploadCertificate}
import com.ocelotconsulting.ssl.aws.s3.ReadFileToString

import scala.language.postfixOps



class IAMServerCertificateLambda {

  val mapper = new ObjectMapper() with ScalaObjectMapper
  mapper.registerModule(DefaultScalaModule).configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

  private def upload(s3Entity: S3Entity, cert: CertificateFile): UploadServerCertificateResult = {
    val certName = IAMServerCertificateLambdaConfig.certMap(s"${decodeS3Key(s3Entity.getBucket.getName)}/${decodeS3Key(s3Entity.getObject.getKey)}")
    try {
      DeleteCertificate(certName)
    } catch {
      case e: NoSuchEntityException =>
        println("Didn't find cert to delete, no prob.")
    }
    UploadCertificate(certName, s"${cert.cert}${cert.issuerCert}", cert.key.privateKeyPem)
  }

  protected def getCertFileAsString(s3Entity: S3Entity): String = ReadFileToString(decodeS3Key(s3Entity.getBucket.getName), decodeS3Key(s3Entity.getObject.getKey))

  private def retrieveCert(s3Entity: S3Entity): CertificateFile = mapper.readValue(getCertFileAsString(s3Entity), classOf[CertificateFile])

  private def transformResult(result: UploadServerCertificateResult) : String = s"Successfully uploaded certificate for ${result.getServerCertificateMetadata.getServerCertificateName}."

  private def extractS3Event(snsRecord: SNSEvent.SNSRecord): S3EventNotification = S3EventNotification.parseJson(snsRecord.getSNS.getMessage)

  private def updateCert(s3Event: S3EventNotification): java.util.List[String] =
    s3Event.getRecords.map(_.getS3).map { s3Object => transformResult(upload(s3Object, retrieveCert(s3Object)))}

  // Actual lambda function
  def configureIAMCert(event: SNSEvent): java.util.List[String] = event.getRecords.map { extractS3Event } flatMap updateCert
} 
开发者ID:ocelotconsulting,项目名称:iam-server-cert-lambda,代码行数:48,代码来源:IAMServerCertificateLambda.scala


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