play.api.data.validation.ValidationError Scala Examples
The following examples show how to use play.api.data.validation.ValidationError.
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: ResidencyChoiceDto.scala From pertax-frontend with Apache License 2.0 | 7 votes |
package models.dto import controllers.bindable._ import play.api.data.Form import play.api.data.Forms._ import play.api.data.validation.ValidationError import play.api.libs.json._ case class ResidencyChoiceDto(residencyChoice: AddrType) object ResidencyChoiceDto { implicit val formats = { implicit val addrTypeReads: Reads[AddrType] = new Reads[AddrType] { override def reads(json: JsValue): JsResult[AddrType] = json match { case JsString("sole") => JsSuccess(SoleAddrType) case JsString("primary") => JsSuccess(PrimaryAddrType) case JsString("postal") => JsSuccess(PostalAddrType) case _ => JsError(Seq(JsPath() -> Seq(JsonValidationError("error.expected.jsString(addrType)")))) } } implicit val addrTypeWrites: Writes[AddrType] = new Writes[AddrType] { override def writes(o: AddrType): JsValue = o match { case SoleAddrType => JsString("sole") case PrimaryAddrType => JsString("primary") case PostalAddrType => JsString("postal") } } Json.format[ResidencyChoiceDto] } val form = Form( mapping( "residencyChoice" -> optional(text) .verifying("error.you_must_select_an_answer", e => e.flatMap(a => AddrType(a)).isDefined) .transform[AddrType](x => AddrType(x.fold("")(_.toString)).getOrElse(SoleAddrType), ad => Some(ad.toString)) //getOrElse here will never fall back to default because of isDefined above )(ResidencyChoiceDto.apply)(ResidencyChoiceDto.unapply) ) }
Example 2
Source File: InspectRequestSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class InspectRequestSpec extends FunSpec with Matchers { val inspectRequestJson: JsValue = Json.parse(""" { "code": "<STRING>", "cursor_pos": 999, "detail_level": 1 } """) val inspectRequest: InspectRequest = InspectRequest( "<STRING>", 999, 1 ) describe("InspectRequest") { describe("#toTypeString") { it("should return correct type") { InspectRequest.toTypeString should be ("inspect_request") } } describe("implicit conversions") { it("should implicitly convert from valid json to a InspectRequest instance") { // This is the least safe way to convert as an error is thrown if it fails inspectRequestJson.as[InspectRequest] should be (inspectRequest) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newInspectRequest = inspectRequestJson.asOpt[InspectRequest] newInspectRequest.get should be (inspectRequest) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val InspectRequestResults = inspectRequestJson.validate[InspectRequest] InspectRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: InspectRequest) => valid ) should be (inspectRequest) } it("should implicitly convert from a InspectRequest instance to valid json") { Json.toJson(inspectRequest) should be (inspectRequestJson) } } } }
Example 3
Source File: ExecuteReplyOkSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ import org.apache.toree.kernel.protocol.v5._ class ExecuteReplyOkSpec extends FunSpec with Matchers { val executeReplyOkJson: JsValue = Json.parse(""" { "status": "ok", "execution_count": 999, "payload": [], "user_expressions": {} } """) val executeReplyOk: ExecuteReplyOk = ExecuteReplyOk( 999, Some(Payloads()), Some(UserExpressions()) ) describe("ExecuteReplyOk") { describe("implicit conversions") { it("should implicitly convert from valid json to a executeReplyOk instance") { // This is the least safe way to convert as an error is thrown if it fails executeReplyOkJson.as[ExecuteReplyOk] should be (executeReplyOk) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newExecuteReplyOk = executeReplyOkJson.asOpt[ExecuteReplyOk] newExecuteReplyOk.get should be (executeReplyOk) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val executeReplyOkResults = executeReplyOkJson.validate[ExecuteReplyOk] executeReplyOkResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: ExecuteReplyOk) => valid ) should be (executeReplyOk) } it("should implicitly convert from a executeReplyOk instance to valid json") { Json.toJson(executeReplyOk) should be (executeReplyOkJson) } } } }
Example 4
Source File: CompleteReplySpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{Matchers, FunSpec} import play.api.data.validation.ValidationError import play.api.libs.json.{JsPath, JsValue, Json} class CompleteReplySpec extends FunSpec with Matchers { val completeReplyJson: JsValue = Json.parse(""" { "matches": [], "cursor_start": 1, "cursor_end": 5, "metadata": {}, "status": "<STRING>" } """) val completeReply: CompleteReply = CompleteReply( List(), 1, 5, Map(), "<STRING>", None, None, None ) describe("CompleteReply") { describe("#toTypeString") { it("should return correct type") { CompleteReply.toTypeString should be ("complete_reply") } } describe("implicit conversions") { it("should implicitly convert from valid json to a CompleteReply instance") { // This is the least safe way to convert as an error is thrown if it fails completeReplyJson.as[CompleteReply] should be (completeReply) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteReply = completeReplyJson.asOpt[CompleteReply] newCompleteReply.get should be (completeReply) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteReplyResults = completeReplyJson.validate[CompleteReply] CompleteReplyResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: CompleteReply) => valid ) should be (completeReply) } it("should implicitly convert from a CompleteReply instance to valid json") { Json.toJson(completeReply) should be (completeReplyJson) } } } }
Example 5
Source File: InspectReplyOkSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ import org.apache.toree.kernel.protocol.v5._ class InspectReplyOkSpec extends FunSpec with Matchers { val inspectReplyOkJson: JsValue = Json.parse(""" { "status": "ok", "data": {}, "metadata": {} } """) val inspectReplyOk: InspectReplyOk = InspectReplyOk( Data(), Metadata() ) describe("InspectReplyOk") { describe("implicit conversions") { it("should implicitly convert from valid json to a InspectReplyOk instance") { // This is the least safe way to convert as an error is thrown if it fails inspectReplyOkJson.as[InspectReplyOk] should be (inspectReplyOk) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newInspectReplyOk = inspectReplyOkJson.asOpt[InspectReplyOk] newInspectReplyOk.get should be (inspectReplyOk) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val InspectReplyOkResults = inspectReplyOkJson.validate[InspectReplyOk] InspectReplyOkResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: InspectReplyOk) => valid ) should be (inspectReplyOk) } it("should implicitly convert from a InspectReplyOk instance to valid json") { Json.toJson(inspectReplyOk) should be (inspectReplyOkJson) } } } }
Example 6
Source File: KernelInfoRequestSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class KernelInfoRequestSpec extends FunSpec with Matchers { val kernelInfoRequestJson: JsValue = Json.parse(""" {} """) val kernelInfoRequest: KernelInfoRequest = KernelInfoRequest() describe("KernelInfoRequest") { describe("#toTypeString") { it("should return correct type") { KernelInfoRequest.toTypeString should be ("kernel_info_request") } } describe("implicit conversions") { it("should implicitly convert from valid json to a KernelInfoRequest instance") { // This is the least safe way to convert as an error is thrown if it fails // This is the least safe way to convert as an error is thrown if it fails kernelInfoRequestJson.as[KernelInfoRequest] should be (kernelInfoRequest) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newKernelInfoRequest = kernelInfoRequestJson.asOpt[KernelInfoRequest] newKernelInfoRequest.get should be (kernelInfoRequest) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val KernelInfoRequestResults = kernelInfoRequestJson.validate[KernelInfoRequest] KernelInfoRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: KernelInfoRequest) => valid ) should be (kernelInfoRequest) } it("should implicitly convert from a KernelInfoRequest instance to valid json") { Json.toJson(kernelInfoRequest) should be (kernelInfoRequestJson) } } } }
Example 7
Source File: ConnectReplySpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json.{JsPath, JsValue, Json} class ConnectReplySpec extends FunSpec with Matchers { val connectReplyJson: JsValue = Json.parse(""" { "shell_port": 11111, "iopub_port": 22222, "stdin_port": 33333, "hb_port": 44444 } """) val connectReply: ConnectReply = ConnectReply(11111,22222,33333,44444) describe("ConnectReply") { describe("#toTypeString") { it("should return correct type") { ConnectReply.toTypeString should be ("connect_reply") } } describe("implicit conversions") { it("should implicitly convert from valid json to a ConnectReply instance") { // This is the least safe way to convert as an error is thrown if it fails connectReplyJson.as[ConnectReply] should be (connectReply) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newConnectReply = connectReplyJson.asOpt[ConnectReply] newConnectReply.get should be (connectReply) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val ConnectReplyResults = connectReplyJson.validate[ConnectReply] ConnectReplyResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: ConnectReply) => valid ) should be (connectReply) } it("should implicitly convert from a ConnectReply instance to valid json") { Json.toJson(connectReply) should be (connectReplyJson) } } } }
Example 8
Source File: InputRequestSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class InputRequestSpec extends FunSpec with Matchers { val inputRequestJson: JsValue = Json.parse(""" { "prompt": "<STRING>", "password": true } """) val inputRequest = InputRequest( "<STRING>", true ) describe("InputRequest") { describe("#toTypeString") { it("should return correct type") { InputRequest.toTypeString should be ("input_request") } } describe("implicit conversions") { it("should implicitly convert from valid json to a InputRequest instance") { // This is the least safe way to convert as an error is thrown if it fails inputRequestJson.as[InputRequest] should be (inputRequest) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteRequest = inputRequestJson.asOpt[InputRequest] newCompleteRequest.get should be (inputRequest) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteRequestResults = inputRequestJson.validate[InputRequest] CompleteRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: InputRequest) => valid ) should be (inputRequest) } it("should implicitly convert from a InputRequest instance to valid json") { Json.toJson(inputRequest) should be (inputRequestJson) } } } }
Example 9
Source File: ExecuteReplySpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.apache.toree.kernel.protocol.v5._ import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class ExecuteReplySpec extends FunSpec with Matchers { val executeReplyJson: JsValue = Json.parse(""" { "status": "<STRING>", "execution_count": 999 } """) val executeReply: ExecuteReply = ExecuteReply( "<STRING>", 999, None, None, None, None, None ) describe("ExecuteReply") { describe("#toTypeString") { it("should return correct type") { ExecuteReply.toTypeString should be ("execute_reply") } } describe("implicit conversions") { it("should implicitly convert from valid json to a executeReply instance") { // This is the least safe way to convert as an error is thrown if it fails executeReplyJson.as[ExecuteReply] should be (executeReply) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newExecuteReply = executeReplyJson.asOpt[ExecuteReply] newExecuteReply.get should be (executeReply) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val executeReplyResults = executeReplyJson.validate[ExecuteReply] executeReplyResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: ExecuteReply) => valid ) should be (executeReply) } it("should implicitly convert from a executeReply instance to valid json") { Json.toJson(executeReply) should be (executeReplyJson) } } } }
Example 10
Source File: InputReplySpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class InputReplySpec extends FunSpec with Matchers { val inputReplyJson: JsValue = Json.parse(""" { "value": "<STRING>" } """) val inputReply = InputReply( "<STRING>" ) describe("InputReply") { describe("#toTypeString") { it("should return correct type") { InputReply.toTypeString should be ("input_reply") } } describe("implicit conversions") { it("should implicitly convert from valid json to a InputReply instance") { // This is the least safe way to convert as an error is thrown if it fails inputReplyJson.as[InputReply] should be (inputReply) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteReply = inputReplyJson.asOpt[InputReply] newCompleteReply.get should be (inputReply) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteReplyResults = inputReplyJson.validate[InputReply] CompleteReplyResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: InputReply) => valid ) should be (inputReply) } it("should implicitly convert from a InputReply instance to valid json") { Json.toJson(inputReply) should be (inputReplyJson) } } } }
Example 11
Source File: CommCloseSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.apache.toree.kernel.protocol.v5._ import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class CommCloseSpec extends FunSpec with Matchers { val commCloseJson: JsValue = Json.parse(""" { "comm_id": "<UUID>", "data": {} } """) val commClose = CommClose( "<UUID>", MsgData.Empty ) describe("CommClose") { describe("#toTypeString") { it("should return correct type") { CommClose.toTypeString should be ("comm_close") } } describe("implicit conversions") { it("should implicitly convert from valid json to a CommClose instance") { // This is the least safe way to convert as an error is thrown if it fails commCloseJson.as[CommClose] should be (commClose) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteRequest = commCloseJson.asOpt[CommClose] newCompleteRequest.get should be (commClose) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteRequestResults = commCloseJson.validate[CommClose] CompleteRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: CommClose) => valid ) should be (commClose) } it("should implicitly convert from a CommClose instance to valid json") { Json.toJson(commClose) should be (commCloseJson) } } } }
Example 12
Source File: ExecuteResultSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ import org.apache.toree.kernel.protocol.v5._ class ExecuteResultSpec extends FunSpec with Matchers { val executeResultJson: JsValue = Json.parse(""" { "execution_count": 999, "data": {"text/plain": "resulty result"}, "metadata": {} } """) val executeResult = ExecuteResult( 999, Data("text/plain" -> "resulty result"), Metadata() ) describe("ExecuteResult") { describe("#toTypeString") { it("should return correct type") { ExecuteResult.toTypeString should be ("execute_result") } } describe("#hasContent") { it("should be true when data has a non-empty text/plain field") { executeResult.hasContent should be (true) } it("should be false if data is null") { val executeResultNoData = ExecuteResult( 999, null, Metadata() ) executeResultNoData.hasContent should be (false) } it("should be false when data does not have a text/plain field") { val executeResultEmptyData = ExecuteResult( 999, Data(), Metadata() ) executeResultEmptyData.hasContent should be (false) } it("should be false if text/plain field maps to an empty string") { val executeResultEmptyString = ExecuteResult( 999, Data("text/plain" -> ""), Metadata() ) executeResultEmptyString.hasContent should be (false) } it("should be false if text/plain maps to null") { val executeResultTextPlainNull = ExecuteResult( 999, Data("text/plain" -> null), Metadata() ) executeResultTextPlainNull.hasContent should be (false) } } describe("implicit conversions") { it("should implicitly convert from valid json to a ExecuteResult instance") { // This is the least safe way to convert as an error is thrown if it fails executeResultJson.as[ExecuteResult] should be (executeResult) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteRequest = executeResultJson.asOpt[ExecuteResult] newCompleteRequest.get should be (executeResult) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteRequestResults = executeResultJson.validate[ExecuteResult] CompleteRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: ExecuteResult) => valid ) should be (executeResult) } it("should implicitly convert from a ExecuteResult instance to valid json") { Json.toJson(executeResult) should be (executeResultJson) } } } }
Example 13
Source File: CommOpenSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ import org.apache.toree.kernel.protocol.v5.MsgData class CommOpenSpec extends FunSpec with Matchers { val commOpenJson: JsValue = Json.parse(""" { "comm_id": "<UUID>", "target_name": "<STRING>", "data": {} } """) val commOpen = CommOpen( "<UUID>", "<STRING>", MsgData.Empty ) describe("CommOpen") { describe("#toTypeString") { it("should return correct type") { CommOpen.toTypeString should be ("comm_open") } } describe("implicit conversions") { it("should implicitly convert from valid json to a CommOpen instance") { // This is the least safe way to convert as an error is thrown if it fails commOpenJson.as[CommOpen] should be (commOpen) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteRequest = commOpenJson.asOpt[CommOpen] newCompleteRequest.get should be (commOpen) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteRequestResults = commOpenJson.validate[CommOpen] CompleteRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: CommOpen) => valid ) should be (commOpen) } it("should implicitly convert from a CommOpen instance to valid json") { Json.toJson(commOpen) should be (commOpenJson) } } } }
Example 14
Source File: CompleteReplyErrorSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class CompleteReplyErrorSpec extends FunSpec with Matchers { val completeReplyErrorJson: JsValue = Json.parse(""" { "matches": [], "cursor_start": 1, "cursor_end": 5, "metadata": {}, "status": "error", "ename":"<STRING>", "evalue": "<STRING>", "traceback": [] } """) val completeReplyError: CompleteReplyError = CompleteReplyError( List(), 1, 5, Map(), Some("<STRING>"), Some("<STRING>"), Some(List()) ) describe("CompleteReplyError") { describe("implicit conversions") { it("should implicitly convert from valid json to a CompleteReplyError instance") { // This is the least safe way to convert as an error is thrown if it fails completeReplyErrorJson.as[CompleteReplyError] should be (completeReplyError) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteReplyOk = completeReplyErrorJson.asOpt[CompleteReplyError] newCompleteReplyOk.get should be (completeReplyError) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteReplyOkResults = completeReplyErrorJson.validate[CompleteReplyError] CompleteReplyOkResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: CompleteReplyError) => valid ) should be (completeReplyError) } it("should implicitly convert from a CompleteReplyError instance to valid json") { Json.toJson(completeReplyError) should be (completeReplyErrorJson) } } } }
Example 15
Source File: ExecuteReplyErrorSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ import org.apache.toree.kernel.protocol.v5._ class ExecuteReplyErrorSpec extends FunSpec with Matchers { val executeReplyErrorJson: JsValue = Json.parse(""" { "status": "error", "execution_count": 999, "ename": "<STRING>", "evalue": "<STRING>", "traceback": [] } """) val executeReplyError: ExecuteReplyError = ExecuteReplyError( 999, Some("<STRING>"), Some("<STRING>"), Some(List()) ) describe("ExecuteReplyError") { describe("implicit conversions") { it("should implicitly convert from valid json to a ExecuteReplyError instance") { // This is the least safe way to convert as an error is thrown if it fails executeReplyErrorJson.as[ExecuteReplyError] should be (executeReplyError) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newExecuteReplyError = executeReplyErrorJson.asOpt[ExecuteReplyError] newExecuteReplyError.get should be (executeReplyError) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val ExecuteReplyErrorResults = executeReplyErrorJson.validate[ExecuteReplyError] ExecuteReplyErrorResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: ExecuteReplyError) => valid ) should be (executeReplyError) } it("should implicitly convert from a ExecuteReplyError instance to valid json") { Json.toJson(executeReplyError) should be (executeReplyErrorJson) } } } }
Example 16
Source File: CommMsgSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ import org.apache.toree.kernel.protocol.v5._ class CommMsgSpec extends FunSpec with Matchers { val commMsgJson: JsValue = Json.parse(""" { "comm_id": "<UUID>", "data": {} } """) val commMsgJsonWithData: JsValue = Json.parse( """ { "comm_id": "<UUID>", "data": { "key" : { "foo" : "bar", "baz" : { "qux" : 3 } } } } """.stripMargin) val commMsg = CommMsg( "<UUID>", MsgData.Empty ) val commMsgWithData = CommMsg( "<UUID>", MsgData("key" -> Json.obj( "foo" -> "bar", "baz" -> Map("qux" -> 3) )) ) describe("CommMsg") { describe("#toTypeString") { it("should return correct type") { CommMsg.toTypeString should be ("comm_msg") } } describe("implicit conversions") { it("should implicitly convert from valid json to a CommMsg instance") { // This is the least safe way to convert as an error is thrown if it fails commMsgJson.as[CommMsg] should be (commMsg) } it("should implicitly convert json with a non-empty json data field " + "to a CommMsg instance") { commMsgJsonWithData.as[CommMsg] should be (commMsgWithData) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteRequest = commMsgJson.asOpt[CommMsg] newCompleteRequest.get should be (commMsg) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteRequestResults = commMsgJson.validate[CommMsg] CompleteRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: CommMsg) => valid ) should be (commMsg) } it("should implicitly convert from a CommMsg instance to valid json") { Json.toJson(commMsg) should be (commMsgJson) } it("should implicitly convert a CommMsg instance with non-empty json " + "data to valid json") { Json.toJson(commMsgWithData) should be (commMsgJsonWithData) } } } }
Example 17
Source File: ShutdownRequestSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class ShutdownRequestSpec extends FunSpec with Matchers { val shutdownRequestJson: JsValue = Json.parse(""" { "restart": true } """) val shutdownRequest: ShutdownRequest = ShutdownRequest( true ) describe("ShutdownRequest") { describe("#toTypeString") { it("should return correct type") { ShutdownRequest.toTypeString should be ("shutdown_request") } } describe("implicit conversions") { it("should implicitly convert from valid json to a ShutdownRequest instance") { // This is the least safe way to convert as an error is thrown if it fails shutdownRequestJson.as[ShutdownRequest] should be (shutdownRequest) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newShutdownRequest = shutdownRequestJson.asOpt[ShutdownRequest] newShutdownRequest.get should be (shutdownRequest) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val ShutdownRequestResults = shutdownRequestJson.validate[ShutdownRequest] ShutdownRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: ShutdownRequest) => valid ) should be (shutdownRequest) } it("should implicitly convert from a ShutdownRequest instance to valid json") { Json.toJson(shutdownRequest) should be (shutdownRequestJson) } } } }
Example 18
Source File: CompleteReplyOkSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class CompleteReplyOkSpec extends FunSpec with Matchers { val completeReplyOkJson: JsValue = Json.parse(""" { "matches": [], "cursor_start": 1, "cursor_end": 5, "metadata": {}, "status": "ok" } """) val completeReplyOk: CompleteReplyOk = CompleteReplyOk( List(), 1, 5, Map() ) describe("CompleteReplyOk") { describe("implicit conversions") { it("should implicitly convert from valid json to a CompleteReplyOk instance") { // This is the least safe way to convert as an error is thrown if it fails completeReplyOkJson.as[CompleteReplyOk] should be (completeReplyOk) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteReplyOk = completeReplyOkJson.asOpt[CompleteReplyOk] newCompleteReplyOk.get should be (completeReplyOk) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteReplyOkResults = completeReplyOkJson.validate[CompleteReplyOk] CompleteReplyOkResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: CompleteReplyOk) => valid ) should be (completeReplyOk) } it("should implicitly convert from a CompleteReplyOk instance to valid json") { Json.toJson(completeReplyOk) should be (completeReplyOkJson) } } } }
Example 19
Source File: ClearOutputSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class ClearOutputSpec extends FunSpec with Matchers { val clearOutputJson: JsValue = Json.parse(""" { "wait": true } """) val clearOutput = ClearOutput( true ) describe("ClearOutput") { describe("#toTypeString") { it("should return correct type") { ClearOutput.toTypeString should be ("clear_output") } } describe("implicit conversions") { it("should implicitly convert from valid json to a ClearOutput instance") { // This is the least safe way to convert as an error is thrown if it fails clearOutputJson.as[ClearOutput] should be (clearOutput) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteRequest = clearOutputJson.asOpt[ClearOutput] newCompleteRequest.get should be (clearOutput) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteRequestResults = clearOutputJson.validate[ClearOutput] CompleteRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: ClearOutput) => valid ) should be (clearOutput) } it("should implicitly convert from a ClearOutput instance to valid json") { Json.toJson(clearOutput) should be (clearOutputJson) } } } }
Example 20
Source File: KernelInfoReplySpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.apache.toree.kernel.protocol.v5.LanguageInfo import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class KernelInfoReplySpec extends FunSpec with Matchers { val kernelInfoReplyJson: JsValue = Json.parse(""" { "protocol_version": "x.y.z", "implementation": "<name>", "implementation_version": "z.y.x", "language_info": { "name": "<some language>", "version": "a.b.c", "file_extension": "<some extension>" }, "banner": "<some banner>" } """) val kernelInfoReply: KernelInfoReply = KernelInfoReply( "x.y.z", "<name>", "z.y.x", LanguageInfo("<some language>", "a.b.c", Some("<some extension>")), "<some banner>" ) describe("KernelInfoReply") { describe("#toTypeString") { it("should return correct type") { KernelInfoReply.toTypeString should be ("kernel_info_reply") } } describe("implicit conversions") { it("should implicitly convert from valid json to a kernelInfoReply instance") { // This is the least safe way to convert as an error is thrown if it fails kernelInfoReplyJson.as[KernelInfoReply] should be (kernelInfoReply) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newKernelInfoReply = kernelInfoReplyJson.asOpt[KernelInfoReply] newKernelInfoReply.get should be (kernelInfoReply) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val kernelInfoReplyResults = kernelInfoReplyJson.validate[KernelInfoReply] kernelInfoReplyResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: KernelInfoReply) => valid ) should be (kernelInfoReply) } it("should implicitly convert from a kernelInfoReply instance to valid json") { Json.toJson(kernelInfoReply) should be (kernelInfoReplyJson) } } } }
Example 21
Source File: HeaderSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5 import org.scalatest.{Matchers, FunSpec} import play.api.data.validation.ValidationError import play.api.libs.json.{JsPath, Json, JsValue} class HeaderSpec extends FunSpec with Matchers { val headerJson: JsValue = Json.parse(""" { "msg_id": "<UUID>", "username": "<STRING>", "session": "<UUID>", "msg_type": "<STRING>", "version": "<FLOAT>" } """) val header: Header = Header( "<UUID>", "<STRING>", "<UUID>", "<STRING>", "<FLOAT>" ) describe("Header") { describe("when null") { it("should implicitly convert to empty json") { val header: Header = null Json.toJson(header).toString() should be ("{}") } } describe("implicit conversions") { it("should implicitly convert from valid json to a header instance") { // This is the least safe way to convert as an error is thrown if it fails headerJson.as[Header] should be (header) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newHeader = headerJson.asOpt[Header] newHeader.get should be (header) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val headerResults = headerJson.validate[Header] headerResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: Header) => valid ) should be (header) } it("should implicitly convert from a header instance to valid json") { Json.toJson(header) should be (headerJson) } } } }
Example 22
Source File: StopOnFirstFail.scala From play-ui with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.play.mappers import play.api.data.validation.{Constraint, Invalid, Valid, ValidationError} object StopOnFirstFail { def apply[T](constraints: Constraint[T]*) = Constraint { field: T => constraints.toList dropWhile (_(field) == Valid) match { case Nil => Valid case constraint :: _ => constraint(field) } } def constraint[T](message: String, validator: (T) => Boolean) = Constraint((data: T) => if (validator(data)) Valid else Invalid(Seq(ValidationError(message)))) }
Example 23
Source File: SocketConfigSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.kernel.socket import com.typesafe.config.ConfigFactory import org.scalatest.{FunSpec, Matchers} import org.slf4j.LoggerFactory import play.api.data.validation.ValidationError import play.api.libs.json.{JsPath, JsValue, Json} class SocketConfigSpec extends FunSpec with Matchers { val logger = LoggerFactory.getLogger("jt4") //logger.error("WOOT!") private val jsonString: String = """ { "stdin_port": 10000, "control_port": 10001, "hb_port": 10002, "shell_port": 10003, "iopub_port": 10004, "ip": "1.2.3.4", "transport": "tcp", "signature_scheme": "hmac-sha256", "key": "" } """.stripMargin val socketConfigJson: JsValue = Json.parse(jsonString) val socketConfigFromConfig = SocketConfig.fromConfig(ConfigFactory.parseString(jsonString)) val socketConfig = SocketConfig( 10000, 10001, 10002, 10003, 10004, "1.2.3.4", "tcp", "hmac-sha256", "" ) describe("SocketConfig") { describe("implicit conversions") { it("should implicitly convert from valid json to a SocketConfig instance") { // This is the least safe way to convert as an error is thrown if it fails socketConfigJson.as[SocketConfig] should be (socketConfig) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteRequest = socketConfigJson.asOpt[SocketConfig] newCompleteRequest.get should be (socketConfig) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteRequestResults = socketConfigJson.validate[SocketConfig] CompleteRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: SocketConfig) => valid ) should be (socketConfig) } it("should implicitly convert from a SocketConfig instance to valid json") { Json.toJson(socketConfig) should be (socketConfigJson) } } describe("#toConfig") { it("should implicitly convert from valid json to a SocketConfig instance") { // This is the least safe way to convert as an error is thrown if it fails socketConfigFromConfig should be (socketConfig) } it("should convert json file to SocketConfig object") { socketConfigFromConfig.stdin_port should be (10000) } } } }
Example 24
Source File: Utilities.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.kernel import java.nio.charset.Charset import akka.util.{ByteString, Timeout} import org.apache.toree.communication.ZMQMessage import org.apache.toree.kernel.protocol.v5._ import org.apache.toree.utils.LogLike import play.api.data.validation.ValidationError import play.api.libs.json.{JsPath, Json, Reads} import scala.concurrent.duration._ object Utilities extends LogLike { // // NOTE: This is brought in to remove feature warnings regarding the use of // implicit conversions regarding the following: // // 1. ByteStringToString // 2. ZMQMessageToKernelMessage // import scala.language.implicitConversions implicit val timeout = Timeout(21474835.seconds) implicit def ByteStringToString(byteString : ByteString) : String = { new String(byteString.toArray, Charset.forName("UTF-8")) } implicit def StringToByteString(string : String) : ByteString = { ByteString(string.getBytes) } implicit def ZMQMessageToKernelMessage(message: ZMQMessage): KernelMessage = { val delimiterIndex: Int = message.frames.indexOf(ByteString("<IDS|MSG>".getBytes)) // TODO Handle the case where there is no delimiter val ids: Seq[Array[Byte]] = message.frames.take(delimiterIndex).map( (byteString : ByteString) => { byteString.toArray } ) val header = Json.parse(message.frames(delimiterIndex + 2)).as[Header] // TODO: Investigate better solution than setting parentHeader to null for {} val parentHeader = parseAndHandle(message.frames(delimiterIndex + 3), ParentHeader.headerReads, handler = (valid: ParentHeader) => valid, errHandler = _ => null ) val metadata = Json.parse(message.frames(delimiterIndex + 4)).as[Metadata] KMBuilder().withIds(ids.toList) .withSignature(message.frame(delimiterIndex + 1)) .withHeader(header) .withParentHeader(parentHeader) .withMetadata(metadata) .withContentString(message.frame(delimiterIndex + 5)).build(false) } implicit def KernelMessageToZMQMessage(kernelMessage : KernelMessage) : ZMQMessage = { val frames: scala.collection.mutable.ListBuffer[ByteString] = scala.collection.mutable.ListBuffer() kernelMessage.ids.map((id : Array[Byte]) => frames += ByteString.apply(id) ) frames += "<IDS|MSG>" frames += kernelMessage.signature frames += Json.toJson(kernelMessage.header).toString() frames += Json.toJson(kernelMessage.parentHeader).toString() frames += Json.toJson(kernelMessage.metadata).toString frames += kernelMessage.contentString ZMQMessage(frames : _*) } def parseAndHandle[T, U](json: String, reads: Reads[T], handler: T => U) : U = { parseAndHandle(json, reads, handler, (invalid: Seq[(JsPath, Seq[ValidationError])]) => { logger.error(s"Could not parse JSON, ${json}") throw new Throwable(s"Could not parse JSON, ${json}") } ) } def parseAndHandle[T, U](json: String, reads: Reads[T], handler: T => U, errHandler: Seq[(JsPath, Seq[ValidationError])] => U) : U = { Json.parse(json).validate[T](reads).fold( errHandler, (content: T) => handler(content) ) } }
Example 25
Source File: CommCloseHandler.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.handler import org.apache.toree.comm.{KernelCommWriter, CommRegistrar, CommWriter, CommStorage} import org.apache.toree.global.ExecuteRequestState import org.apache.toree.kernel.protocol.v5.content.CommClose import org.apache.toree.kernel.protocol.v5.kernel.{Utilities, ActorLoader} import org.apache.toree.kernel.protocol.v5.{KMBuilder, KernelMessage} import org.apache.toree.utils.MessageLogSupport import play.api.data.validation.ValidationError import play.api.libs.json.JsPath import scala.concurrent.Future import scala.concurrent.ExecutionContext.Implicits.global class CommCloseHandler( actorLoader: ActorLoader, commRegistrar: CommRegistrar, commStorage: CommStorage ) extends BaseHandler(actorLoader) with MessageLogSupport { override def process(kernelMessage: KernelMessage): Future[_] = Future { logKernelMessageAction("Initiating Comm Close for", kernelMessage) ExecuteRequestState.processIncomingKernelMessage(kernelMessage) val kmBuilder = KMBuilder().withParent(kernelMessage) Utilities.parseAndHandle( kernelMessage.contentString, CommClose.commCloseReads, handler = handleCommClose(kmBuilder), errHandler = handleParseError ) } private def handleCommClose(kmBuilder: KMBuilder)(commClose: CommClose) = { val commId = commClose.comm_id val data = commClose.data logger.debug(s"Received comm_close with id '$commId'") val commWriter = new KernelCommWriter(actorLoader, kmBuilder, commId) commStorage.getCommIdCallbacks(commId) match { case None => logger.warn(s"Received invalid id for Comm Close: $commId") case Some(callbacks) => logger.debug(s"Executing close callbacks for id '$commId'") // TODO: Should we be checking the return values? Probably not. callbacks.executeCloseCallbacks(commWriter, commId, data) .filter(_.isFailure).map(_.failed).foreach(throwable => { logger.error("Comm close callback encountered an error!", throwable) }) } } private def handleParseError(invalid: Seq[(JsPath, Seq[ValidationError])]) = { // TODO: Determine proper response for a parse failure logger.warn("Parse error for Comm Close! Not responding!") } }
Example 26
Source File: HistoryReplySpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ import org.apache.toree.kernel.protocol.v5._ class HistoryReplySpec extends FunSpec with Matchers { val historyReplyJson: JsValue = Json.parse(""" { "history": ["<STRING>", "<STRING2>", "<STRING3>"] } """) val historyReply = HistoryReply( List("<STRING>", "<STRING2>", "<STRING3>") ) describe("HistoryReply") { describe("#toTypeString") { it("should return correct type") { HistoryReply.toTypeString should be ("history_reply") } } describe("implicit conversions") { it("should implicitly convert from valid json to a HistoryReply instance") { // This is the least safe way to convert as an error is thrown if it fails historyReplyJson.as[HistoryReply] should be (historyReply) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteRequest = historyReplyJson.asOpt[HistoryReply] newCompleteRequest.get should be (historyReply) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteRequestResults = historyReplyJson.validate[HistoryReply] CompleteRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: HistoryReply) => valid ) should be (historyReply) } it("should implicitly convert from a HistoryReply instance to valid json") { Json.toJson(historyReply) should be (historyReplyJson) } } } }
Example 27
Source File: SocketConfigSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.kernel.socket import com.typesafe.config.ConfigFactory import org.scalatest.{FunSpec, Matchers} import org.slf4j.LoggerFactory import play.api.data.validation.ValidationError import play.api.libs.json.{JsPath, JsValue, Json} class SocketConfigSpec extends FunSpec with Matchers { val logger = LoggerFactory.getLogger("jt4") //logger.error("WOOT!") private val jsonString: String = """ { "stdin_port": 10000, "control_port": 10001, "hb_port": 10002, "shell_port": 10003, "iopub_port": 10004, "ip": "1.2.3.4", "transport": "tcp", "signature_scheme": "hmac-sha256", "key": "" } """.stripMargin val socketConfigJson: JsValue = Json.parse(jsonString) val socketConfigFromConfig = SocketConfig.fromConfig(ConfigFactory.parseString(jsonString)) val socketConfig = SocketConfig( 10000, 10001, 10002, 10003, 10004, "1.2.3.4", "tcp", "hmac-sha256", "" ) describe("SocketConfig") { describe("implicit conversions") { it("should implicitly convert from valid json to a SocketConfig instance") { // This is the least safe way to convert as an error is thrown if it fails socketConfigJson.as[SocketConfig] should be (socketConfig) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteRequest = socketConfigJson.asOpt[SocketConfig] newCompleteRequest.get should be (socketConfig) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteRequestResults = socketConfigJson.validate[SocketConfig] CompleteRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: SocketConfig) => valid ) should be (socketConfig) } it("should implicitly convert from a SocketConfig instance to valid json") { Json.toJson(socketConfig) should be (socketConfigJson) } } describe("#toConfig") { it("should implicitly convert from valid json to a SocketConfig instance") { // This is the least safe way to convert as an error is thrown if it fails socketConfigFromConfig should be (socketConfig) } it("should convert json file to SocketConfig object") { socketConfigFromConfig.stdin_port should be (10000) } } } }
Example 28
Source File: Utilities.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.kernel import java.nio.charset.Charset import akka.util.{ByteString, Timeout} import org.apache.toree.communication.ZMQMessage import org.apache.toree.kernel.protocol.v5._ import org.apache.toree.utils.LogLike import play.api.data.validation.ValidationError import play.api.libs.json.{JsPath, Json, Reads} import scala.concurrent.duration._ object Utilities extends LogLike { // // NOTE: This is brought in to remove feature warnings regarding the use of // implicit conversions regarding the following: // // 1. ByteStringToString // 2. ZMQMessageToKernelMessage // import scala.language.implicitConversions implicit val timeout = Timeout(21474835.seconds) implicit def ByteStringToString(byteString : ByteString) : String = { new String(byteString.toArray, Charset.forName("UTF-8")) } implicit def StringToByteString(string : String) : ByteString = { ByteString(string.getBytes) } implicit def ZMQMessageToKernelMessage(message: ZMQMessage): KernelMessage = { val delimiterIndex: Int = message.frames.indexOf(ByteString("<IDS|MSG>".getBytes)) // TODO Handle the case where there is no delimiter val ids: Seq[Array[Byte]] = message.frames.take(delimiterIndex).map( (byteString : ByteString) => { byteString.toArray } ) val header = Json.parse(message.frames(delimiterIndex + 2)).as[Header] // TODO: Investigate better solution than setting parentHeader to null for {} val parentHeader = parseAndHandle(message.frames(delimiterIndex + 3), ParentHeader.headerReads, handler = (valid: ParentHeader) => valid, errHandler = _ => null ) val metadata = Json.parse(message.frames(delimiterIndex + 4)).as[Metadata] KMBuilder().withIds(ids.toList) .withSignature(message.frame(delimiterIndex + 1)) .withHeader(header) .withParentHeader(parentHeader) .withMetadata(metadata) .withContentString(message.frame(delimiterIndex + 5)).build(false) } implicit def KernelMessageToZMQMessage(kernelMessage : KernelMessage) : ZMQMessage = { val frames: scala.collection.mutable.ListBuffer[ByteString] = scala.collection.mutable.ListBuffer() kernelMessage.ids.map((id : Array[Byte]) => frames += ByteString.apply(id) ) frames += "<IDS|MSG>" frames += kernelMessage.signature frames += Json.toJson(kernelMessage.header).toString() frames += Json.toJson(kernelMessage.parentHeader).toString() frames += Json.toJson(kernelMessage.metadata).toString frames += kernelMessage.contentString ZMQMessage(frames : _*) } def parseAndHandle[T, U](json: String, reads: Reads[T], handler: T => U) : U = { parseAndHandle(json, reads, handler, (invalid: Seq[(JsPath, Seq[ValidationError])]) => { logger.error(s"Could not parse JSON, ${json}") throw new Throwable(s"Could not parse JSON, ${json}") } ) } def parseAndHandle[T, U](json: String, reads: Reads[T], handler: T => U, errHandler: Seq[(JsPath, Seq[ValidationError])] => U) : U = { Json.parse(json).validate[T](reads).fold( errHandler, (content: T) => handler(content) ) } }
Example 29
Source File: CommCloseHandler.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.handler import org.apache.toree.comm.{KernelCommWriter, CommRegistrar, CommWriter, CommStorage} import org.apache.toree.global.ExecuteRequestState import org.apache.toree.kernel.protocol.v5.content.CommClose import org.apache.toree.kernel.protocol.v5.kernel.{Utilities, ActorLoader} import org.apache.toree.kernel.protocol.v5.{KMBuilder, KernelMessage} import org.apache.toree.utils.MessageLogSupport import play.api.data.validation.ValidationError import play.api.libs.json.JsPath import scala.concurrent.Future import scala.concurrent.ExecutionContext.Implicits.global class CommCloseHandler( actorLoader: ActorLoader, commRegistrar: CommRegistrar, commStorage: CommStorage ) extends BaseHandler(actorLoader) with MessageLogSupport { override def process(kernelMessage: KernelMessage): Future[_] = Future { logKernelMessageAction("Initiating Comm Close for", kernelMessage) ExecuteRequestState.processIncomingKernelMessage(kernelMessage) val kmBuilder = KMBuilder().withParent(kernelMessage) Utilities.parseAndHandle( kernelMessage.contentString, CommClose.commCloseReads, handler = handleCommClose(kmBuilder), errHandler = handleParseError ) } private def handleCommClose(kmBuilder: KMBuilder)(commClose: CommClose) = { val commId = commClose.comm_id val data = commClose.data logger.debug(s"Received comm_close with id '$commId'") val commWriter = new KernelCommWriter(actorLoader, kmBuilder, commId) commStorage.getCommIdCallbacks(commId) match { case None => logger.warn(s"Received invalid id for Comm Close: $commId") case Some(callbacks) => logger.debug(s"Executing close callbacks for id '$commId'") // TODO: Should we be checking the return values? Probably not. callbacks.executeCloseCallbacks(commWriter, commId, data) .filter(_.isFailure).map(_.failed).foreach(throwable => { logger.error("Comm close callback encountered an error!", throwable) }) } } private def handleParseError(invalid: Seq[(JsPath, Seq[ValidationError])]) = { // TODO: Determine proper response for a parse failure logger.warn("Parse error for Comm Close! Not responding!") } }
Example 30
Source File: CommOpenHandler.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.handler import org.apache.toree.comm.{KernelCommWriter, CommStorage, CommRegistrar, CommWriter} import org.apache.toree.global.ExecuteRequestState import org.apache.toree.kernel.protocol.v5.content.CommOpen import org.apache.toree.kernel.protocol.v5.kernel.{Utilities, ActorLoader} import org.apache.toree.kernel.protocol.v5.{KMBuilder, KernelMessage} import org.apache.toree.utils.MessageLogSupport import play.api.data.validation.ValidationError import play.api.libs.json.JsPath import scala.concurrent.Future import scala.concurrent.ExecutionContext.Implicits.global class CommOpenHandler( actorLoader: ActorLoader, commRegistrar: CommRegistrar, commStorage: CommStorage ) extends BaseHandler(actorLoader) with MessageLogSupport { override def process(kernelMessage: KernelMessage): Future[_] = Future { logKernelMessageAction("Initiating Comm Open for", kernelMessage) ExecuteRequestState.processIncomingKernelMessage(kernelMessage) val kmBuilder = KMBuilder().withParent(kernelMessage) Utilities.parseAndHandle( kernelMessage.contentString, CommOpen.commOpenReads, handler = handleCommOpen(kmBuilder), errHandler = handleParseError ) } private def handleCommOpen(kmBuilder: KMBuilder)(commOpen: CommOpen) = { val commId = commOpen.comm_id val targetName = commOpen.target_name val data = commOpen.data logger.debug( s"Received comm_open for target '$targetName' with id '$commId'") val commWriter = new KernelCommWriter(actorLoader, kmBuilder, commId) commStorage.getTargetCallbacks(targetName) match { case None => logger.warn(s"Received invalid target for Comm Open: $targetName") commWriter.close() case Some(callbacks) => logger.debug(s"Executing open callbacks for id '$commId'") // TODO: Should we be checking the return values? Probably not. callbacks.executeOpenCallbacks(commWriter, commId, targetName, data) .filter(_.isFailure).map(_.failed).foreach(throwable => { logger.error("Comm open callback encountered an error!", throwable) }) } } private def handleParseError(invalid: Seq[(JsPath, Seq[ValidationError])]) = { // TODO: Determine proper response for a parse failure logger.warn("Parse error for Comm Open! Not responding!") } }
Example 31
Source File: ShutdownHandler.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.handler import org.apache.toree.comm.{CommRegistrar, CommStorage, KernelCommWriter} import org.apache.toree.kernel.protocol.v5.content.{ShutdownReply, ShutdownRequest, CommOpen} import org.apache.toree.kernel.protocol.v5.kernel.{ActorLoader, Utilities} import org.apache.toree.kernel.protocol.v5._ import org.apache.toree.security.KernelSecurityManager import org.apache.toree.utils.MessageLogSupport import play.api.data.validation.ValidationError import play.api.libs.json.JsPath import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future class ShutdownHandler( actorLoader: ActorLoader ) extends BaseHandler(actorLoader) with MessageLogSupport { override def process(kernelMessage: KernelMessage): Future[_] = Future { logKernelMessageAction("Initiating Shutdown request for", kernelMessage) val shutdownReply = ShutdownReply(false) val replyHeader = Header( java.util.UUID.randomUUID.toString, "", java.util.UUID.randomUUID.toString, ShutdownReply.toTypeString, "") val kernelResponseMessage = KMBuilder() .withIds(kernelMessage.ids) .withSignature("") .withHeader(replyHeader) .withParent(kernelMessage) .withContentString(shutdownReply).build logger.debug("Attempting graceful shutdown.") actorLoader.load(SystemActorType.KernelMessageRelay) ! kernelResponseMessage // Instruct security manager that exit should be allowed KernelSecurityManager.enableRestrictedExit() System.exit(0) } }
Example 32
Source File: CommMsgHandler.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.handler import org.apache.toree.comm.{KernelCommWriter, CommRegistrar, CommWriter, CommStorage} import org.apache.toree.global.ExecuteRequestState import org.apache.toree.kernel.protocol.v5.content.CommMsg import org.apache.toree.kernel.protocol.v5.kernel.{Utilities, ActorLoader} import org.apache.toree.kernel.protocol.v5.{KMBuilder, KernelMessage} import org.apache.toree.utils.MessageLogSupport import play.api.data.validation.ValidationError import play.api.libs.json.JsPath import scala.concurrent.Future import scala.concurrent.ExecutionContext.Implicits.global class CommMsgHandler( actorLoader: ActorLoader, commRegistrar: CommRegistrar, commStorage: CommStorage ) extends BaseHandler(actorLoader) with MessageLogSupport { override def process(kernelMessage: KernelMessage): Future[_] = Future { logKernelMessageAction("Initiating Comm Msg for", kernelMessage) ExecuteRequestState.processIncomingKernelMessage(kernelMessage) val kmBuilder = KMBuilder().withParent(kernelMessage) Utilities.parseAndHandle( kernelMessage.contentString, CommMsg.commMsgReads, handler = handleCommMsg(kmBuilder), errHandler = handleParseError ) } private def handleCommMsg(kmBuilder: KMBuilder)(commMsg: CommMsg) = { val commId = commMsg.comm_id val data = commMsg.data logger.debug(s"Received comm_msg with id '$commId'") val commWriter = new KernelCommWriter(actorLoader, kmBuilder, commId) commStorage.getCommIdCallbacks(commId) match { case None => logger.warn(s"Received invalid id for Comm Msg: $commId") case Some(callbacks) => logger.debug(s"Executing msg callbacks for id '$commId'") // TODO: Should we be checking the return values? Probably not. callbacks.executeMsgCallbacks(commWriter, commId, data) .filter(_.isFailure).map(_.failed).foreach(throwable => { logger.error("Comm msg callback encountered an error!", throwable) }) } } private def handleParseError(invalid: Seq[(JsPath, Seq[ValidationError])]) = { // TODO: Determine proper response for a parse failure logger.warn("Parse error for Comm Msg! Not responding!") } }
Example 33
Source File: IsCompleteHandler.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.handler import akka.pattern.ask import org.apache.toree.kernel.protocol.v5._ import org.apache.toree.kernel.protocol.v5.content._ import org.apache.toree.kernel.protocol.v5.kernel.{ActorLoader, Utilities} import Utilities._ import org.apache.toree.utils.{MessageLogSupport, LogLike} import play.api.data.validation.ValidationError import play.api.libs.json.{JsPath, Json} import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future import scala.util.Success class IsCompleteHandler(actorLoader: ActorLoader) extends BaseHandler(actorLoader) with MessageLogSupport { override def process(kernelMessage: KernelMessage): Future[_] = { logKernelMessageAction("Determining if code is complete for", kernelMessage) Utilities.parseAndHandle( kernelMessage.contentString, IsCompleteRequest.isCompleteRequestReads, isCompleteRequest(kernelMessage, _ : IsCompleteRequest) ) } private def isCompleteRequest(km: KernelMessage, cr: IsCompleteRequest): Future[(String, String)] = { val interpreterActor = actorLoader.load(SystemActorType.Interpreter) val codeCompleteFuture = ask(interpreterActor, cr).mapTo[(String, String)] codeCompleteFuture.onComplete { case Success(tuple) => val reply = IsCompleteReply(tuple._1, tuple._2) val isCompleteReplyType = MessageType.Outgoing.IsCompleteReply.toString logKernelMessageAction("Sending is complete reply for", km) actorLoader.load(SystemActorType.KernelMessageRelay) ! km.copy( header = HeaderBuilder.create(isCompleteReplyType), parentHeader = km.header, contentString = Json.toJson(reply).toString ) case _ => new Exception("Parse error in CodeCompleteHandler") } codeCompleteFuture } }
Example 34
Source File: CodeCompleteHandler.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.handler import akka.pattern.ask import org.apache.toree.kernel.protocol.v5._ import org.apache.toree.kernel.protocol.v5.content._ import org.apache.toree.kernel.protocol.v5.kernel.{ActorLoader, Utilities} import Utilities._ import org.apache.toree.utils.{MessageLogSupport, LogLike} import play.api.data.validation.ValidationError import play.api.libs.json.{JsPath, Json} import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future import scala.util.Success class CodeCompleteHandler(actorLoader: ActorLoader) extends BaseHandler(actorLoader) with MessageLogSupport { override def process(kernelMessage: KernelMessage): Future[_] = { logKernelMessageAction("Generating code completion for", kernelMessage) Utilities.parseAndHandle( kernelMessage.contentString, CompleteRequest.completeRequestReads, completeRequest(kernelMessage, _ : CompleteRequest) ) } private def completeRequest(km: KernelMessage, cr: CompleteRequest): Future[(Int, List[String])] = { val interpreterActor = actorLoader.load(SystemActorType.Interpreter) val codeCompleteFuture = ask(interpreterActor, cr).mapTo[(Int, List[String])] codeCompleteFuture.onComplete { case Success(tuple) => val reply = CompleteReplyOk(tuple._2, tuple._1, cr.cursor_pos, Metadata()) val completeReplyType = MessageType.Outgoing.CompleteReply.toString logKernelMessageAction("Sending code complete reply for", km) actorLoader.load(SystemActorType.KernelMessageRelay) ! km.copy( header = HeaderBuilder.create(completeReplyType), parentHeader = km.header, contentString = Json.toJson(reply).toString ) case _ => new Exception("Parse error in CodeCompleteHandler") } codeCompleteFuture } }
Example 35
Source File: Utilities.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.client import java.nio.charset.Charset import akka.util.{ByteString, Timeout} import org.apache.toree.communication.ZMQMessage import org.apache.toree.kernel.protocol.v5._ import org.apache.toree.kernel.protocol.v5.content.ExecuteRequest import org.apache.toree.utils.LogLike import play.api.data.validation.ValidationError import play.api.libs.json.{JsPath, Json, Reads} import scala.concurrent.duration._ object Utilities extends LogLike { // // NOTE: This is brought in to remove feature warnings regarding the use of // implicit conversions regarding the following: // // 1. ByteStringToString // 2. ZMQMessageToKernelMessage // import scala.language.implicitConversions private val sessionId: UUID = java.util.UUID.randomUUID().toString implicit val timeout = Timeout(21474835.seconds) // Maximum delay implicit def ByteStringToString(byteString : ByteString) : String = { new String(byteString.toArray, Charset.forName("UTF-8")) } implicit def StringToByteString(string : String) : ByteString = { ByteString(string.getBytes) } implicit def ZMQMessageToKernelMessage(message: ZMQMessage): KernelMessage = { val delimiterIndex: Int = message.frames.indexOf(ByteString("<IDS|MSG>".getBytes)) // TODO Handle the case where there is no delimiter val ids: Seq[Array[Byte]] = message.frames.take(delimiterIndex).map( (byteString : ByteString) => { byteString.toArray } ) val header = Json.parse(message.frames(delimiterIndex + 2)).as[Header] val parentHeader = Json.parse(message.frames(delimiterIndex + 3)).validate[ParentHeader].fold[ParentHeader]( // TODO: Investigate better solution than setting parentHeader to null for {} (invalid: Seq[(JsPath, Seq[ValidationError])]) => null, //HeaderBuilder.empty, (valid: ParentHeader) => valid ) val metadata = Json.parse(message.frames(delimiterIndex + 4)).as[Metadata] KMBuilder().withIds(ids.toList) .withSignature(message.frame(delimiterIndex + 1)) .withHeader(header) .withParentHeader(parentHeader) .withMetadata(metadata) .withContentString(message.frame(delimiterIndex + 5)).build(false) } implicit def KernelMessageToZMQMessage(kernelMessage : KernelMessage) : ZMQMessage = { val frames: scala.collection.mutable.ListBuffer[ByteString] = scala.collection.mutable.ListBuffer() kernelMessage.ids.map((id : Array[Byte]) => frames += ByteString.apply(id) ) frames += "<IDS|MSG>" frames += kernelMessage.signature frames += Json.toJson(kernelMessage.header).toString() frames += Json.toJson(kernelMessage.parentHeader).toString() frames += Json.toJson(kernelMessage.metadata).toString frames += kernelMessage.contentString ZMQMessage(frames : _*) } def parseAndHandle[T](json: String, reads: Reads[T], handler: T => Unit) : Unit = { Json.parse(json).validate[T](reads).fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => logger.error(s"Could not parse JSON, ${json}"), (content: T) => handler(content) ) } def getSessionId = sessionId def toKernelMessage(message: ExecuteRequest): KernelMessage = { // construct a kernel message whose content is an ExecuteRequest val id = java.util.UUID.randomUUID().toString val header = Header( id, "spark", sessionId, MessageType.Incoming.ExecuteRequest.toString, "5.0") KMBuilder().withIds(Seq[Array[Byte]]()).withSignature("").withHeader(header) .withParentHeader(HeaderBuilder.empty).withContentString(message).build } }
Example 36
Source File: InspectReplyErrorSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.apache.toree.kernel.protocol.v5._ import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class InspectReplyErrorSpec extends FunSpec with Matchers { val inspectReplyErrorJson: JsValue = Json.parse(""" { "status": "error", "data": {}, "metadata": {}, "ename": "<STRING>", "evalue": "<STRING>", "traceback": [] } """) val inspectReplyError: InspectReplyError = InspectReplyError( Data(), Metadata(), Some("<STRING>"), Some("<STRING>"), Some(List()) ) describe("InspectReplyError") { describe("implicit conversions") { it("should implicitly convert from valid json to a InspectReplyError instance") { // This is the least safe way to convert as an error is thrown if it fails inspectReplyErrorJson.as[InspectReplyError] should be (inspectReplyError) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newInspectReplyError = inspectReplyErrorJson.asOpt[InspectReplyError] newInspectReplyError.get should be (inspectReplyError) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val InspectReplyErrorResults = inspectReplyErrorJson.validate[InspectReplyError] InspectReplyErrorResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: InspectReplyError) => valid ) should be (inspectReplyError) } it("should implicitly convert from a InspectReplyError instance to valid json") { Json.toJson(inspectReplyError) should be (inspectReplyErrorJson) } } } }
Example 37
Source File: KernelStatusSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json.{JsPath, JsValue, Json} class KernelStatusSpec extends FunSpec with Matchers { val kernelStatusJson: JsValue = Json.parse(""" { "execution_state": "<STRING>" } """) val kernelStatus: KernelStatus = KernelStatus("<STRING>") describe("KernelStatus") { describe("#toTypeString") { it("should return correct type") { KernelStatus.toTypeString should be ("status") } } describe("implicit conversions") { it("should implicitly convert from valid json to a kernelStatus instance") { // This is the least safe way to convert as an error is thrown if it fails kernelStatusJson.as[KernelStatus] should be (kernelStatus) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newKernelStatus = kernelStatusJson.asOpt[KernelStatus] newKernelStatus.get should be (kernelStatus) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val kernelStatusResults = kernelStatusJson.validate[KernelStatus] kernelStatusResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: KernelStatus) => valid ) should be (kernelStatus) } it("should implicitly convert from a kernelStatus instance to valid json") { Json.toJson(kernelStatus) should be (kernelStatusJson) } } } }
Example 38
Source File: CommOpenHandler.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.handler import org.apache.toree.comm.{KernelCommWriter, CommStorage, CommRegistrar, CommWriter} import org.apache.toree.global.ExecuteRequestState import org.apache.toree.kernel.protocol.v5.content.CommOpen import org.apache.toree.kernel.protocol.v5.kernel.{Utilities, ActorLoader} import org.apache.toree.kernel.protocol.v5.{KMBuilder, KernelMessage} import org.apache.toree.utils.MessageLogSupport import play.api.data.validation.ValidationError import play.api.libs.json.JsPath import scala.concurrent.Future import scala.concurrent.ExecutionContext.Implicits.global class CommOpenHandler( actorLoader: ActorLoader, commRegistrar: CommRegistrar, commStorage: CommStorage ) extends BaseHandler(actorLoader) with MessageLogSupport { override def process(kernelMessage: KernelMessage): Future[_] = Future { logKernelMessageAction("Initiating Comm Open for", kernelMessage) ExecuteRequestState.processIncomingKernelMessage(kernelMessage) val kmBuilder = KMBuilder().withParent(kernelMessage) Utilities.parseAndHandle( kernelMessage.contentString, CommOpen.commOpenReads, handler = handleCommOpen(kmBuilder), errHandler = handleParseError ) } private def handleCommOpen(kmBuilder: KMBuilder)(commOpen: CommOpen) = { val commId = commOpen.comm_id val targetName = commOpen.target_name val data = commOpen.data logger.debug( s"Received comm_open for target '$targetName' with id '$commId'") val commWriter = new KernelCommWriter(actorLoader, kmBuilder, commId) commStorage.getTargetCallbacks(targetName) match { case None => logger.warn(s"Received invalid target for Comm Open: $targetName") commWriter.close() case Some(callbacks) => logger.debug(s"Executing open callbacks for id '$commId'") // TODO: Should we be checking the return values? Probably not. callbacks.executeOpenCallbacks(commWriter, commId, targetName, data) .filter(_.isFailure).map(_.failed).foreach(throwable => { logger.error("Comm open callback encountered an error!", throwable) }) } } private def handleParseError(invalid: Seq[(JsPath, Seq[ValidationError])]) = { // TODO: Determine proper response for a parse failure logger.warn("Parse error for Comm Open! Not responding!") } }
Example 39
Source File: ExecuteInputSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class ExecuteInputSpec extends FunSpec with Matchers { val executeInputJson: JsValue = Json.parse(""" { "code": "<STRING>", "execution_count": 42 } """) val executeInput: ExecuteInput = ExecuteInput( "<STRING>", 42 ) describe("ExecuteInput") { describe("#toTypeString") { it("should return correct type") { ExecuteInput.toTypeString should be ("execute_input") } } describe("implicit conversions") { it("should implicitly convert from valid json to a executeInput instance") { // This is the least safe way to convert as an error is thrown if it fails executeInputJson.as[ExecuteInput] should be (executeInput) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newExecuteInput = executeInputJson.asOpt[ExecuteInput] newExecuteInput.get should be (executeInput) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val executeInputResults = executeInputJson.validate[ExecuteInput] executeInputResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: ExecuteInput) => valid ) should be (executeInput) } it("should implicitly convert from a executeInput instance to valid json") { Json.toJson(executeInput) should be (executeInputJson) } } } }
Example 40
Source File: DisplayDataSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.FunSuite import org.scalatest.{Matchers, FunSpec} import play.api.data.validation.ValidationError import play.api.libs.json._ import org.apache.toree.kernel.protocol.v5._ class DisplayDataSpec extends FunSpec with Matchers { val displayDataJson: JsValue = Json.parse(""" { "source": "<STRING>", "data": {}, "metadata": {} } """) val displayData: DisplayData = DisplayData( "<STRING>", Map(), Map() ) describe("DisplayData") { describe("#toTypeString") { it("should return correct type") { DisplayData.toTypeString should be ("display_data") } } describe("implicit conversions") { it("should implicitly convert from valid json to a displayData instance") { // This is the least safe way to convert as an error is thrown if it fails displayDataJson.as[DisplayData] should be (displayData) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newDisplayData = displayDataJson.asOpt[DisplayData] newDisplayData.get should be (displayData) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val displayDataResults = displayDataJson.validate[DisplayData] displayDataResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: DisplayData) => valid ) should be (displayData) } it("should implicitly convert from a displayData instance to valid json") { Json.toJson(displayData) should be (displayDataJson) } } } }
Example 41
Source File: ShutdownReplySpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class ShutdownReplySpec extends FunSpec with Matchers { val shutdownReplyJson: JsValue = Json.parse(""" { "restart": true } """) val shutdownReply: ShutdownReply = ShutdownReply( true ) describe("ShutdownReply") { describe("#toTypeString") { it("should return correct type") { ShutdownReply.toTypeString should be ("shutdown_reply") } } describe("implicit conversions") { it("should implicitly convert from valid json to a ShutdownReply instance") { // This is the least safe way to convert as an error is thrown if it fails shutdownReplyJson.as[ShutdownReply] should be (shutdownReply) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newShutdownReply = shutdownReplyJson.asOpt[ShutdownReply] newShutdownReply.get should be (shutdownReply) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val ShutdownReplyResults = shutdownReplyJson.validate[ShutdownReply] ShutdownReplyResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: ShutdownReply) => valid ) should be (shutdownReply) } it("should implicitly convert from a ShutdownReply instance to valid json") { Json.toJson(shutdownReply) should be (shutdownReplyJson) } } } }
Example 42
Source File: HistoryRequestSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class HistoryRequestSpec extends FunSpec with Matchers { val historyRequestJson: JsValue = Json.parse(""" { "output": true, "ras": true, "hist_access_type": "<STRING>", "session": 1, "start": 0, "stop": 5, "n": 1, "pattern": "<STRING>", "unique": true } """) val historyRequest = HistoryRequest( true, true, "<STRING>", 1, 0, 5, 1, "<STRING>", true ) describe("HistoryRequest") { describe("#toTypeString") { it("should return correct type") { HistoryRequest.toTypeString should be ("history_request") } } describe("implicit conversions") { it("should implicitly convert from valid json to a HistoryRequest instance") { // This is the least safe way to convert as an error is thrown if it fails historyRequestJson.as[HistoryRequest] should be (historyRequest) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteRequest = historyRequestJson.asOpt[HistoryRequest] newCompleteRequest.get should be (historyRequest) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteRequestResults = historyRequestJson.validate[HistoryRequest] CompleteRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: HistoryRequest) => valid ) should be (historyRequest) } it("should implicitly convert from a HistoryRequest instance to valid json") { Json.toJson(historyRequest) should be (historyRequestJson) } } } }
Example 43
Source File: StreamContentSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class StreamContentSpec extends FunSpec with Matchers { val streamJson: JsValue = Json.parse(""" { "text": "<STRING>", "name": "<STRING>" } """) val stream = StreamContent("<STRING>", "<STRING>") describe("StreamContent") { describe("#toTypeString") { it("should return correct type") { StreamContent.toTypeString should be ("stream") } } describe("implicit conversions") { it("should implicitly convert from valid json to a StreamContent instance") { // This is the least safe way to convert as an error is thrown if it fails streamJson.as[StreamContent] should be (stream) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteRequest = streamJson.asOpt[StreamContent] newCompleteRequest.get should be (stream) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteRequestResults = streamJson.validate[StreamContent] CompleteRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: StreamContent) => valid ) should be (stream) } it("should implicitly convert from a StreamContent instance to valid json") { Json.toJson(stream) should be (streamJson) } } } }
Example 44
Source File: ConnectRequestSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class ConnectRequestSpec extends FunSpec with Matchers { val connectRequestJson: JsValue = Json.parse(""" {} """) val connectRequest: ConnectRequest = ConnectRequest() describe("ConnectRequest") { describe("#toTypeString") { it("should return correct type") { ConnectRequest.toTypeString should be ("connect_request") } } describe("implicit conversions") { it("should implicitly convert from valid json to a ConnectRequest instance") { // This is the least safe way to convert as an error is thrown if it fails connectRequestJson.as[ConnectRequest] should be (connectRequest) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newConnectRequest = connectRequestJson.asOpt[ConnectRequest] newConnectRequest.get should be (connectRequest) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val ConnectRequestResults = connectRequestJson.validate[ConnectRequest] ConnectRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: ConnectRequest) => valid ) should be (connectRequest) } it("should implicitly convert from a ConnectRequest instance to valid json") { Json.toJson(connectRequest) should be (connectRequestJson) } } } }
Example 45
Source File: ExecuteRequestSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{Matchers, FunSpec} import play.api.data.validation.ValidationError import play.api.libs.json._ import org.apache.toree.kernel.protocol.v5._ class ExecuteRequestSpec extends FunSpec with Matchers { val executeRequestJson: JsValue = Json.parse(""" { "code": "<STRING>", "silent": false, "store_history": false, "user_expressions": {}, "allow_stdin": false } """) val executeRequest: ExecuteRequest = ExecuteRequest( "<STRING>", false, false, UserExpressions(), false ) describe("ExecuteRequest") { describe("#toTypeString") { it("should return correct type") { ExecuteRequest.toTypeString should be ("execute_request") } } describe("implicit conversions") { it("should implicitly convert from valid json to a executeRequest instance") { // This is the least safe way to convert as an error is thrown if it fails executeRequestJson.as[ExecuteRequest] should be (executeRequest) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newExecuteRequest = executeRequestJson.asOpt[ExecuteRequest] newExecuteRequest.get should be (executeRequest) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val executeRequestResults = executeRequestJson.validate[ExecuteRequest] executeRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: ExecuteRequest) => valid ) should be (executeRequest) } it("should implicitly convert from a executeRequest instance to valid json") { Json.toJson(executeRequest) should be (executeRequestJson) } } } }
Example 46
Source File: ExecuteReplyAbortSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.apache.toree.kernel.protocol.v5._ import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class ExecuteReplyAbortSpec extends FunSpec with Matchers { val executeReplyAbortJson: JsValue = Json.parse(""" { "status": "abort", "execution_count": 999 } """) val executeReplyAbort: ExecuteReplyAbort = ExecuteReplyAbort( 999 ) describe("ExecuteReplyAbort") { describe("implicit conversions") { it("should implicitly convert from valid json to a ExecuteReplyAbort instance") { // This is the least safe way to convert as an error is thrown if it fails executeReplyAbortJson.as[ExecuteReplyAbort] should be (executeReplyAbort) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newExecuteReplyAbort = executeReplyAbortJson.asOpt[ExecuteReplyAbort] newExecuteReplyAbort.get should be (executeReplyAbort) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val ExecuteReplyAbortResults = executeReplyAbortJson.validate[ExecuteReplyAbort] ExecuteReplyAbortResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: ExecuteReplyAbort) => valid ) should be (executeReplyAbort) } it("should implicitly convert from a ExecuteReplyAbort instance to valid json") { Json.toJson(executeReplyAbort) should be (executeReplyAbortJson) } } } }
Example 47
Source File: InspectReplySpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class InspectReplySpec extends FunSpec with Matchers { val inspectReplyJson: JsValue = Json.parse(""" { "status": "<STRING>", "data": {}, "metadata": {} } """) val inspectReply: InspectReply = InspectReply( "<STRING>", Map(), Map(), None, None, None ) describe("InspectReply") { describe("#toTypeString") { it("should return correct type") { InspectReply.toTypeString should be ("inspect_reply") } } describe("implicit conversions") { it("should implicitly convert from valid json to a InspectReply instance") { // This is the least safe way to convert as an error is thrown if it fails inspectReplyJson.as[InspectReply] should be (inspectReply) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newInspectReply = inspectReplyJson.asOpt[InspectReply] newInspectReply.get should be (inspectReply) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val InspectReplyResults = inspectReplyJson.validate[InspectReply] InspectReplyResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: InspectReply) => valid ) should be (inspectReply) } it("should implicitly convert from a InspectReply instance to valid json") { Json.toJson(inspectReply) should be (inspectReplyJson) } } } }
Example 48
Source File: ErrorContentSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{Matchers, FunSpec} import play.api.data.validation.ValidationError import play.api.libs.json._ class ErrorContentSpec extends FunSpec with Matchers { val errorJson: JsValue = Json.parse(""" { "ename": "<STRING>", "evalue": "<STRING>", "traceback": ["<STRING>"] } """) val error = ErrorContent("<STRING>", "<STRING>", List("<STRING>")) describe("ErrorContent") { describe("#toTypeString") { it("should return correct type") { ErrorContent.toTypeString should be ("error") } } describe("implicit conversions") { it("should implicitly convert from valid json to a ErrorContent instance") { // This is the least safe way to convert as an error is thrown if it fails errorJson.as[ErrorContent] should be (error) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteRequest = errorJson.asOpt[ErrorContent] newCompleteRequest.get should be (error) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteRequestResults = errorJson.validate[ErrorContent] CompleteRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: ErrorContent) => valid ) should be (error) } it("should implicitly convert from a ErrorContent instance to valid json") { Json.toJson(error) should be (errorJson) } } } }
Example 49
Source File: CompleteRequestSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class CompleteRequestSpec extends FunSpec with Matchers { val completeRequestJson: JsValue = Json.parse(""" { "code": "<STRING>", "cursor_pos": 999 } """) val completeRequest: CompleteRequest = CompleteRequest( "<STRING>", 999 ) describe("CompleteRequest") { describe("#toTypeString") { it("should return correct type") { CompleteRequest.toTypeString should be ("complete_request") } } describe("implicit conversions") { it("should implicitly convert from valid json to a CompleteRequest instance") { // This is the least safe way to convert as an error is thrown if it fails completeRequestJson.as[CompleteRequest] should be (completeRequest) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteRequest = completeRequestJson.asOpt[CompleteRequest] newCompleteRequest.get should be (completeRequest) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteRequestResults = completeRequestJson.validate[CompleteRequest] CompleteRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: CompleteRequest) => valid ) should be (completeRequest) } it("should implicitly convert from a CompleteRequest instance to valid json") { Json.toJson(completeRequest) should be (completeRequestJson) } } } }
Example 50
Source File: CompleteReplyOkSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class CompleteReplyOkSpec extends FunSpec with Matchers { val completeReplyOkJson: JsValue = Json.parse(""" { "matches": [], "cursor_start": 1, "cursor_end": 5, "metadata": {}, "status": "ok" } """) val completeReplyOk: CompleteReplyOk = CompleteReplyOk( List(), 1, 5, Map() ) describe("CompleteReplyOk") { describe("implicit conversions") { it("should implicitly convert from valid json to a CompleteReplyOk instance") { // This is the least safe way to convert as an error is thrown if it fails completeReplyOkJson.as[CompleteReplyOk] should be (completeReplyOk) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteReplyOk = completeReplyOkJson.asOpt[CompleteReplyOk] newCompleteReplyOk.get should be (completeReplyOk) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteReplyOkResults = completeReplyOkJson.validate[CompleteReplyOk] CompleteReplyOkResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: CompleteReplyOk) => valid ) should be (completeReplyOk) } it("should implicitly convert from a CompleteReplyOk instance to valid json") { Json.toJson(completeReplyOk) should be (completeReplyOkJson) } } } }
Example 51
Source File: ConnectReplySpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json.{JsPath, JsValue, Json} class ConnectReplySpec extends FunSpec with Matchers { val connectReplyJson: JsValue = Json.parse(""" { "shell_port": 11111, "iopub_port": 22222, "stdin_port": 33333, "hb_port": 44444 } """) val connectReply: ConnectReply = ConnectReply(11111,22222,33333,44444) describe("ConnectReply") { describe("#toTypeString") { it("should return correct type") { ConnectReply.toTypeString should be ("connect_reply") } } describe("implicit conversions") { it("should implicitly convert from valid json to a ConnectReply instance") { // This is the least safe way to convert as an error is thrown if it fails connectReplyJson.as[ConnectReply] should be (connectReply) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newConnectReply = connectReplyJson.asOpt[ConnectReply] newConnectReply.get should be (connectReply) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val ConnectReplyResults = connectReplyJson.validate[ConnectReply] ConnectReplyResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: ConnectReply) => valid ) should be (connectReply) } it("should implicitly convert from a ConnectReply instance to valid json") { Json.toJson(connectReply) should be (connectReplyJson) } } } }
Example 52
Source File: InputRequestSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class InputRequestSpec extends FunSpec with Matchers { val inputRequestJson: JsValue = Json.parse(""" { "prompt": "<STRING>", "password": true } """) val inputRequest = InputRequest( "<STRING>", true ) describe("InputRequest") { describe("#toTypeString") { it("should return correct type") { InputRequest.toTypeString should be ("input_request") } } describe("implicit conversions") { it("should implicitly convert from valid json to a InputRequest instance") { // This is the least safe way to convert as an error is thrown if it fails inputRequestJson.as[InputRequest] should be (inputRequest) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteRequest = inputRequestJson.asOpt[InputRequest] newCompleteRequest.get should be (inputRequest) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteRequestResults = inputRequestJson.validate[InputRequest] CompleteRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: InputRequest) => valid ) should be (inputRequest) } it("should implicitly convert from a InputRequest instance to valid json") { Json.toJson(inputRequest) should be (inputRequestJson) } } } }
Example 53
Source File: ExecuteReplySpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.apache.toree.kernel.protocol.v5._ import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class ExecuteReplySpec extends FunSpec with Matchers { val executeReplyJson: JsValue = Json.parse(""" { "status": "<STRING>", "execution_count": 999 } """) val executeReply: ExecuteReply = ExecuteReply( "<STRING>", 999, None, None, None, None, None ) describe("ExecuteReply") { describe("#toTypeString") { it("should return correct type") { ExecuteReply.toTypeString should be ("execute_reply") } } describe("implicit conversions") { it("should implicitly convert from valid json to a executeReply instance") { // This is the least safe way to convert as an error is thrown if it fails executeReplyJson.as[ExecuteReply] should be (executeReply) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newExecuteReply = executeReplyJson.asOpt[ExecuteReply] newExecuteReply.get should be (executeReply) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val executeReplyResults = executeReplyJson.validate[ExecuteReply] executeReplyResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: ExecuteReply) => valid ) should be (executeReply) } it("should implicitly convert from a executeReply instance to valid json") { Json.toJson(executeReply) should be (executeReplyJson) } } } }
Example 54
Source File: InputReplySpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class InputReplySpec extends FunSpec with Matchers { val inputReplyJson: JsValue = Json.parse(""" { "value": "<STRING>" } """) val inputReply = InputReply( "<STRING>" ) describe("InputReply") { describe("#toTypeString") { it("should return correct type") { InputReply.toTypeString should be ("input_reply") } } describe("implicit conversions") { it("should implicitly convert from valid json to a InputReply instance") { // This is the least safe way to convert as an error is thrown if it fails inputReplyJson.as[InputReply] should be (inputReply) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteReply = inputReplyJson.asOpt[InputReply] newCompleteReply.get should be (inputReply) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteReplyResults = inputReplyJson.validate[InputReply] CompleteReplyResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: InputReply) => valid ) should be (inputReply) } it("should implicitly convert from a InputReply instance to valid json") { Json.toJson(inputReply) should be (inputReplyJson) } } } }
Example 55
Source File: CommCloseSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.apache.toree.kernel.protocol.v5._ import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class CommCloseSpec extends FunSpec with Matchers { val commCloseJson: JsValue = Json.parse(""" { "comm_id": "<UUID>", "data": {} } """) val commClose = CommClose( "<UUID>", MsgData.Empty ) describe("CommClose") { describe("#toTypeString") { it("should return correct type") { CommClose.toTypeString should be ("comm_close") } } describe("implicit conversions") { it("should implicitly convert from valid json to a CommClose instance") { // This is the least safe way to convert as an error is thrown if it fails commCloseJson.as[CommClose] should be (commClose) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteRequest = commCloseJson.asOpt[CommClose] newCompleteRequest.get should be (commClose) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteRequestResults = commCloseJson.validate[CommClose] CompleteRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: CommClose) => valid ) should be (commClose) } it("should implicitly convert from a CommClose instance to valid json") { Json.toJson(commClose) should be (commCloseJson) } } } }
Example 56
Source File: ExecuteResultSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ import org.apache.toree.kernel.protocol.v5._ class ExecuteResultSpec extends FunSpec with Matchers { val executeResultJson: JsValue = Json.parse(""" { "execution_count": 999, "data": {"text/plain": "resulty result"}, "metadata": {} } """) val executeResult = ExecuteResult( 999, Data("text/plain" -> "resulty result"), Metadata() ) describe("ExecuteResult") { describe("#toTypeString") { it("should return correct type") { ExecuteResult.toTypeString should be ("execute_result") } } describe("#hasContent") { it("should be true when data has a non-empty text/plain field") { executeResult.hasContent should be (true) } it("should be false if data is null") { val executeResultNoData = ExecuteResult( 999, null, Metadata() ) executeResultNoData.hasContent should be (false) } it("should be false when data does not have a text/plain field") { val executeResultEmptyData = ExecuteResult( 999, Data(), Metadata() ) executeResultEmptyData.hasContent should be (false) } it("should be false if text/plain field maps to an empty string") { val executeResultEmptyString = ExecuteResult( 999, Data("text/plain" -> ""), Metadata() ) executeResultEmptyString.hasContent should be (false) } it("should be false if text/plain maps to null") { val executeResultTextPlainNull = ExecuteResult( 999, Data("text/plain" -> null), Metadata() ) executeResultTextPlainNull.hasContent should be (false) } } describe("implicit conversions") { it("should implicitly convert from valid json to a ExecuteResult instance") { // This is the least safe way to convert as an error is thrown if it fails executeResultJson.as[ExecuteResult] should be (executeResult) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteRequest = executeResultJson.asOpt[ExecuteResult] newCompleteRequest.get should be (executeResult) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteRequestResults = executeResultJson.validate[ExecuteResult] CompleteRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: ExecuteResult) => valid ) should be (executeResult) } it("should implicitly convert from a ExecuteResult instance to valid json") { Json.toJson(executeResult) should be (executeResultJson) } } } }
Example 57
Source File: CommOpenSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ import org.apache.toree.kernel.protocol.v5.MsgData class CommOpenSpec extends FunSpec with Matchers { val commOpenJson: JsValue = Json.parse(""" { "comm_id": "<UUID>", "target_name": "<STRING>", "data": {} } """) val commOpen = CommOpen( "<UUID>", "<STRING>", MsgData.Empty ) describe("CommOpen") { describe("#toTypeString") { it("should return correct type") { CommOpen.toTypeString should be ("comm_open") } } describe("implicit conversions") { it("should implicitly convert from valid json to a CommOpen instance") { // This is the least safe way to convert as an error is thrown if it fails commOpenJson.as[CommOpen] should be (commOpen) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteRequest = commOpenJson.asOpt[CommOpen] newCompleteRequest.get should be (commOpen) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteRequestResults = commOpenJson.validate[CommOpen] CompleteRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: CommOpen) => valid ) should be (commOpen) } it("should implicitly convert from a CommOpen instance to valid json") { Json.toJson(commOpen) should be (commOpenJson) } } } }
Example 58
Source File: CompleteReplyErrorSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class CompleteReplyErrorSpec extends FunSpec with Matchers { val completeReplyErrorJson: JsValue = Json.parse(""" { "matches": [], "cursor_start": 1, "cursor_end": 5, "metadata": {}, "status": "error", "ename":"<STRING>", "evalue": "<STRING>", "traceback": [] } """) val completeReplyError: CompleteReplyError = CompleteReplyError( List(), 1, 5, Map(), Some("<STRING>"), Some("<STRING>"), Some(List()) ) describe("CompleteReplyError") { describe("implicit conversions") { it("should implicitly convert from valid json to a CompleteReplyError instance") { // This is the least safe way to convert as an error is thrown if it fails completeReplyErrorJson.as[CompleteReplyError] should be (completeReplyError) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteReplyOk = completeReplyErrorJson.asOpt[CompleteReplyError] newCompleteReplyOk.get should be (completeReplyError) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteReplyOkResults = completeReplyErrorJson.validate[CompleteReplyError] CompleteReplyOkResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: CompleteReplyError) => valid ) should be (completeReplyError) } it("should implicitly convert from a CompleteReplyError instance to valid json") { Json.toJson(completeReplyError) should be (completeReplyErrorJson) } } } }
Example 59
Source File: ExecuteReplyErrorSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ import org.apache.toree.kernel.protocol.v5._ class ExecuteReplyErrorSpec extends FunSpec with Matchers { val executeReplyErrorJson: JsValue = Json.parse(""" { "status": "error", "execution_count": 999, "ename": "<STRING>", "evalue": "<STRING>", "traceback": [] } """) val executeReplyError: ExecuteReplyError = ExecuteReplyError( 999, Some("<STRING>"), Some("<STRING>"), Some(List()) ) describe("ExecuteReplyError") { describe("implicit conversions") { it("should implicitly convert from valid json to a ExecuteReplyError instance") { // This is the least safe way to convert as an error is thrown if it fails executeReplyErrorJson.as[ExecuteReplyError] should be (executeReplyError) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newExecuteReplyError = executeReplyErrorJson.asOpt[ExecuteReplyError] newExecuteReplyError.get should be (executeReplyError) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val ExecuteReplyErrorResults = executeReplyErrorJson.validate[ExecuteReplyError] ExecuteReplyErrorResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: ExecuteReplyError) => valid ) should be (executeReplyError) } it("should implicitly convert from a ExecuteReplyError instance to valid json") { Json.toJson(executeReplyError) should be (executeReplyErrorJson) } } } }
Example 60
Source File: CommMsgSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ import org.apache.toree.kernel.protocol.v5._ class CommMsgSpec extends FunSpec with Matchers { val commMsgJson: JsValue = Json.parse(""" { "comm_id": "<UUID>", "data": {} } """) val commMsgJsonWithData: JsValue = Json.parse( """ { "comm_id": "<UUID>", "data": { "key" : { "foo" : "bar", "baz" : { "qux" : 3 } } } } """.stripMargin) val commMsg = CommMsg( "<UUID>", MsgData.Empty ) val commMsgWithData = CommMsg( "<UUID>", MsgData("key" -> Json.obj( "foo" -> "bar", "baz" -> Map("qux" -> 3) )) ) describe("CommMsg") { describe("#toTypeString") { it("should return correct type") { CommMsg.toTypeString should be ("comm_msg") } } describe("implicit conversions") { it("should implicitly convert from valid json to a CommMsg instance") { // This is the least safe way to convert as an error is thrown if it fails commMsgJson.as[CommMsg] should be (commMsg) } it("should implicitly convert json with a non-empty json data field " + "to a CommMsg instance") { commMsgJsonWithData.as[CommMsg] should be (commMsgWithData) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteRequest = commMsgJson.asOpt[CommMsg] newCompleteRequest.get should be (commMsg) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteRequestResults = commMsgJson.validate[CommMsg] CompleteRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: CommMsg) => valid ) should be (commMsg) } it("should implicitly convert from a CommMsg instance to valid json") { Json.toJson(commMsg) should be (commMsgJson) } it("should implicitly convert a CommMsg instance with non-empty json " + "data to valid json") { Json.toJson(commMsgWithData) should be (commMsgJsonWithData) } } } }
Example 61
Source File: ShutdownRequestSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class ShutdownRequestSpec extends FunSpec with Matchers { val shutdownRequestJson: JsValue = Json.parse(""" { "restart": true } """) val shutdownRequest: ShutdownRequest = ShutdownRequest( true ) describe("ShutdownRequest") { describe("#toTypeString") { it("should return correct type") { ShutdownRequest.toTypeString should be ("shutdown_request") } } describe("implicit conversions") { it("should implicitly convert from valid json to a ShutdownRequest instance") { // This is the least safe way to convert as an error is thrown if it fails shutdownRequestJson.as[ShutdownRequest] should be (shutdownRequest) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newShutdownRequest = shutdownRequestJson.asOpt[ShutdownRequest] newShutdownRequest.get should be (shutdownRequest) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val ShutdownRequestResults = shutdownRequestJson.validate[ShutdownRequest] ShutdownRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: ShutdownRequest) => valid ) should be (shutdownRequest) } it("should implicitly convert from a ShutdownRequest instance to valid json") { Json.toJson(shutdownRequest) should be (shutdownRequestJson) } } } }
Example 62
Source File: KernelInfoRequestSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class KernelInfoRequestSpec extends FunSpec with Matchers { val kernelInfoRequestJson: JsValue = Json.parse(""" {} """) val kernelInfoRequest: KernelInfoRequest = KernelInfoRequest() describe("KernelInfoRequest") { describe("#toTypeString") { it("should return correct type") { KernelInfoRequest.toTypeString should be ("kernel_info_request") } } describe("implicit conversions") { it("should implicitly convert from valid json to a KernelInfoRequest instance") { // This is the least safe way to convert as an error is thrown if it fails // This is the least safe way to convert as an error is thrown if it fails kernelInfoRequestJson.as[KernelInfoRequest] should be (kernelInfoRequest) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newKernelInfoRequest = kernelInfoRequestJson.asOpt[KernelInfoRequest] newKernelInfoRequest.get should be (kernelInfoRequest) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val KernelInfoRequestResults = kernelInfoRequestJson.validate[KernelInfoRequest] KernelInfoRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: KernelInfoRequest) => valid ) should be (kernelInfoRequest) } it("should implicitly convert from a KernelInfoRequest instance to valid json") { Json.toJson(kernelInfoRequest) should be (kernelInfoRequestJson) } } } }
Example 63
Source File: ClearOutputSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class ClearOutputSpec extends FunSpec with Matchers { val clearOutputJson: JsValue = Json.parse(""" { "wait": true } """) val clearOutput = ClearOutput( true ) describe("ClearOutput") { describe("#toTypeString") { it("should return correct type") { ClearOutput.toTypeString should be ("clear_output") } } describe("implicit conversions") { it("should implicitly convert from valid json to a ClearOutput instance") { // This is the least safe way to convert as an error is thrown if it fails clearOutputJson.as[ClearOutput] should be (clearOutput) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteRequest = clearOutputJson.asOpt[ClearOutput] newCompleteRequest.get should be (clearOutput) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteRequestResults = clearOutputJson.validate[ClearOutput] CompleteRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: ClearOutput) => valid ) should be (clearOutput) } it("should implicitly convert from a ClearOutput instance to valid json") { Json.toJson(clearOutput) should be (clearOutputJson) } } } }
Example 64
Source File: KernelInfoReplySpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.apache.toree.kernel.protocol.v5.LanguageInfo import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class KernelInfoReplySpec extends FunSpec with Matchers { val kernelInfoReplyJson: JsValue = Json.parse(""" { "protocol_version": "x.y.z", "implementation": "<name>", "implementation_version": "z.y.x", "language_info": { "name": "<some language>", "version": "a.b.c", "file_extension": "<some extension>" }, "banner": "<some banner>" } """) val kernelInfoReply: KernelInfoReply = KernelInfoReply( "x.y.z", "<name>", "z.y.x", LanguageInfo("<some language>", "a.b.c", Some("<some extension>")), "<some banner>" ) describe("KernelInfoReply") { describe("#toTypeString") { it("should return correct type") { KernelInfoReply.toTypeString should be ("kernel_info_reply") } } describe("implicit conversions") { it("should implicitly convert from valid json to a kernelInfoReply instance") { // This is the least safe way to convert as an error is thrown if it fails kernelInfoReplyJson.as[KernelInfoReply] should be (kernelInfoReply) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newKernelInfoReply = kernelInfoReplyJson.asOpt[KernelInfoReply] newKernelInfoReply.get should be (kernelInfoReply) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val kernelInfoReplyResults = kernelInfoReplyJson.validate[KernelInfoReply] kernelInfoReplyResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: KernelInfoReply) => valid ) should be (kernelInfoReply) } it("should implicitly convert from a kernelInfoReply instance to valid json") { Json.toJson(kernelInfoReply) should be (kernelInfoReplyJson) } } } }
Example 65
Source File: HeaderSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5 import org.scalatest.{Matchers, FunSpec} import play.api.data.validation.ValidationError import play.api.libs.json.{JsPath, Json, JsValue} class HeaderSpec extends FunSpec with Matchers { val headerJson: JsValue = Json.parse(""" { "msg_id": "<UUID>", "username": "<STRING>", "session": "<UUID>", "msg_type": "<STRING>", "version": "<FLOAT>" } """) val header: Header = Header( "<UUID>", "<STRING>", "<UUID>", "<STRING>", "<FLOAT>" ) describe("Header") { describe("when null") { it("should implicitly convert to empty json") { val header: Header = null Json.toJson(header).toString() should be ("{}") } } describe("implicit conversions") { it("should implicitly convert from valid json to a header instance") { // This is the least safe way to convert as an error is thrown if it fails headerJson.as[Header] should be (header) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newHeader = headerJson.asOpt[Header] newHeader.get should be (header) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val headerResults = headerJson.validate[Header] headerResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: Header) => valid ) should be (header) } it("should implicitly convert from a header instance to valid json") { Json.toJson(header) should be (headerJson) } } } }
Example 66
Source File: ResultMessage.scala From Aton with GNU General Public License v3.0 | 5 votes |
package model.json import play.api.data.validation.ValidationError import play.api.libs.json.JsPath case class ResultMessage( result: String, extras: Seq[ResultMessageExtra] ){ def this(result: String) = this(result, Seq.empty) } object ResultMessage { val inputWasNotAJson: ResultMessage = new ResultMessage("Input was not a JSON") def wrongJsonFormat(errors: Seq[(JsPath, Seq[ValidationError])]): ResultMessage = { val mapped = errors.map(singleError=>{ val error = singleError._2.map(y => y.message match { case "error.path.missing" => "Missing" case "error.expected.jsnumber" => "Number expected" case otherError => otherError }).mkString(", ") ResultMessageExtra(singleError._1.toString().drop(1),error) }) ResultMessage("Wrong json format", mapped) } }
Example 67
Source File: package.scala From prometheus-opentsdb-exporter with Apache License 2.0 | 5 votes |
import scala.concurrent.Future import play.api.mvc.Results._ import play.api.libs.json._ import play.api.libs.json.Reads._ import play.api.libs.functional.syntax._ import play.api.data.validation.ValidationError package object models { type Tag = Map[String, String] implicit val JsPathWrites = Writes[JsPath](p => JsString(p.toString)) implicit val ValidationErrorWrites = Writes[ValidationError] { e => JsString(s"${e.message}(${e.args.mkString(",")})") } implicit val jsonValidateErrorWrites = ( (JsPath \ "path").write[JsPath] and (JsPath \ "errors").write[Seq[ValidationError]] tupled ) def oneOf[M](values: Set[M])(implicit reads: Reads[M]) = filter[M](ValidationError("error.oneOf",values))(values.contains) def respondWithErrors(errors: Seq[(JsPath, Seq[ValidationError])]) = { Future.successful(BadRequest(Json.toJson(errors))) } }
Example 68
Source File: JsonSpec.scala From vat-api with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.vatapi.resources import play.api.data.validation.ValidationError import play.api.libs.json._ import uk.gov.hmrc.vatapi.UnitSpec import uk.gov.hmrc.vatapi.models.ErrorCode.ErrorCode trait JsonSpec extends UnitSpec { def roundTripJson[T](json: T)(implicit format: Format[T]): Unit = { val write = Json.toJson(json) val read = write.validate[T] read.asOpt shouldEqual Some(json) } def assertJsonIs[T](input: T, expectedOutput: T)( implicit format: Format[T]): Unit = { val write = Json.toJson(input) val read = write.validate[T] read.asOpt shouldEqual Some(expectedOutput) } def assertValidationPasses[T](o: T)(implicit format: Format[T]): Unit = { val json = Json.toJson(o) json .validate[T] .fold( invalid => fail(invalid.seq.mkString(", ")), valid => valid shouldEqual o ) } def assertJsonValidationPasses[T: Format](json: JsValue): Unit = { json .validate[T] .fold( invalid => fail(invalid.seq.mkString(", ")), _ => succeed ) } def assertValidationErrorWithCode[T: Format](obj: T, path: String, error: ErrorCode): Unit = assertValidationErrorsWithCode[T](Json.toJson(obj), Map(path -> Seq(error))) def assertValidationErrorWithMessage[T: Format](obj: T, path: String, message: String): Unit = assertValidationErrorsWithMessage[T](Json.toJson(obj), Map(path -> Seq(message))) def assertValidationErrorsWithCode[T: Format]( value: JsValue, pathAndCode: Map[String, Seq[ErrorCode]]): Unit = { value.validate[T].asEither match { case Left(errs) => errs.groupBy(_._1).toSeq.map { case (p, e) => p.toString -> e .flatMap(_._2) .map(_.args.head.asInstanceOf[ErrorCode]) .reverse } should contain theSameElementsAs pathAndCode.toSeq case Right(_) => fail( s"Provided object passed json validation. Was expected to fail for the paths: ${pathAndCode.toSeq}") } } def assertValidationErrorsWithMessage[T: Format]( value: JsValue, pathAndMessage: Map[String, Seq[String]]): Unit = { val expectedError = pathAndMessage.map { case (path, msg) => path -> Seq(ValidationError(msg)) }.toSeq value.validate[T].asEither match { case Left(errs) => errs.map { case (p, e) => p.toString -> e.map(x => ValidationError(x.message)) } should contain theSameElementsAs expectedError case Right(_) => fail( s"Provided object passed json validation. Was expected to fail for the paths: ${expectedError .map(_._1)}") } } }
Example 69
Source File: ReadsRecoverOpsSpec.scala From play-json-ops with MIT License | 5 votes |
package play.api.libs.json.ops.v4 import org.scalatest.FreeSpec import org.scalatest.Matchers._ import play.api.data.validation.ValidationError import play.api.libs.json._ class ReadsRecoverOpsSpec extends FreeSpec { private val it = classOf[ReadsRecoverOps[_]].getSimpleName s"$it.recoverJsError should recover from exceptions with a JsError" in { val readStringAsInt = Reads.of[String].map(_.toInt).recoverJsError readStringAsInt.reads(JsString("not a number")) match { case JsError(Seq((JsPath, Seq(ValidationError(Seq(message), ex))))) => assertResult("error.expected.int")(message) ex shouldBe a[NumberFormatException] case o => fail(s"Expected a single error message with a single exception, not $o") } } s"$it.recoverWith should throw any exception not caught by the partial function" in { val readStringAsIntInverted = Reads.of[String].map(1 / _.toInt).recoverWith { case ex: NumberFormatException => RecoverOps.expectedTypeError(classOf[Int], ex) } // it should catch format exceptions assert(readStringAsIntInverted.reads(JsString("not a number")).isError) // but math exceptions are uncaught an[ArithmeticException] shouldBe thrownBy { readStringAsIntInverted.reads(JsString("0")) } } s"$it.recoverTotal should call the recover function" in { val readStringAsIntInverted = Reads.of[String].map(_.toInt.abs).recoverTotal(_ => -1) assertResult(JsSuccess(-1))(readStringAsIntInverted.reads(JsString("not a number"))) } }
Example 70
Source File: RecoverOps.scala From play-json-ops with MIT License | 5 votes |
package play.api.libs.json.ops.v4 import play.api.data.validation.ValidationError import play.api.libs.json._ import scala.language.higherKinds import scala.reflect.ClassTag import scala.util.control.NonFatal trait RecoverOps[F[x] <: Reads[x], A] extends Any { def unsafeReader: Reads[A] def expectedTypeError(cls: Class[_], args: Any*): JsError = { expectedTypeError(safeSimpleClassName(cls), args: _*) } } class ReadsRecoverOps[A](override val unsafeReader: Reads[A]) extends AnyVal with RecoverOps[Reads, A] { final override protected def build(safeReader: Reads[A]): Reads[A] = safeReader } class FormatRecoverOps[A](val unsafeFormat: Format[A]) extends AnyVal with RecoverOps[Format, A] { final override def unsafeReader: Reads[A] = unsafeFormat final override protected def build(safeReader: Reads[A]): Format[A] = Format(safeReader, unsafeFormat) } class OFormatRecoverOps[A](val unsafeFormat: OFormat[A]) extends AnyVal with RecoverOps[OFormat, A] { final override def unsafeReader: Reads[A] = unsafeFormat final override protected def build(safeReader: Reads[A]): OFormat[A] = OFormat(safeReader, unsafeFormat) }
Example 71
Source File: QueryFormats.scala From daf with BSD 3-Clause "New" or "Revised" License | 5 votes |
package daf.dataset.query.json import daf.dataset.query._ import daf.web.json.JsonReadsSyntax import play.api.data.validation.ValidationError import play.api.libs.json.Reads object QueryFormats { private val havingWithoutGroupBy = ValidationError { "Query with [having] clause is missing [groupBy]" } implicit val reader: Reads[Query] = for { select <- SelectClauseFormats.reader.optional("select") where <- WhereClauseFormats.reader.optional("where") groupBy <- GroupByClauseFormats.reader.optional("groupBy") having <- HavingClauseFormats.reader.optional("having").filterNot(havingWithoutGroupBy) { clause => clause.nonEmpty && groupBy.isEmpty } limit <- LimitClauseFormats.reader.optional("limit") } yield Query( select = select getOrElse SelectClause.*, where = where, groupBy = groupBy, having = having, limit = limit ) }
Example 72
Source File: BackendConnector.scala From nisp-frontend with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.nisp.connectors import play.api.data.validation.ValidationError import play.api.libs.json.{Format, JsObject, JsPath} import uk.gov.hmrc.http.cache.client.SessionCache import uk.gov.hmrc.nisp.models.enums.APIType._ import uk.gov.hmrc.nisp.services.MetricsService import uk.gov.hmrc.nisp.utils.JsonDepersonaliser import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future import scala.util.{Failure, Success} import uk.gov.hmrc.http.{ HeaderCarrier, HttpGet, HttpResponse } trait BackendConnector { def http: HttpGet def serviceUrl: String def sessionCache: SessionCache val metricsService: MetricsService protected def retrieveFromCache[A](api: APIType, url: String)(implicit hc: HeaderCarrier, formats: Format[A]): Future[A] = { val keystoreTimerContext = metricsService.keystoreReadTimer.time() val sessionCacheF = sessionCache.fetchAndGetEntry[A](api.toString) sessionCacheF.onFailure { case _ => metricsService.keystoreReadFailed.inc() } sessionCacheF.flatMap { keystoreResult => keystoreTimerContext.stop() keystoreResult match { case Some(data) => metricsService.keystoreHitCounter.inc() Future.successful(data) case None => metricsService.keystoreMissCounter.inc() connectToMicroservice[A](url, api) map { data: A => cacheResult(data, api.toString) } } } } private def connectToMicroservice[A](urlToRead: String, apiType: APIType)(implicit hc: HeaderCarrier, formats: Format[A]): Future[A] = { val timerContext = metricsService.startTimer(apiType) val httpResponseF = http.GET[HttpResponse](urlToRead) httpResponseF onSuccess { case _ => timerContext.stop() } httpResponseF onFailure { case _ => metricsService.incrementFailedCounter(apiType) } httpResponseF.map { httpResponse => httpResponse.json.validate[A].fold( errs => { val json = JsonDepersonaliser.depersonalise(httpResponse.json) match { case Success(s) => s"Depersonalised JSON\n$s" case Failure(e) => s"JSON could not be depersonalised\n${e.toString()}" } throw new JsonValidationException(s"Unable to deserialise $apiType: ${formatJsonErrors(errs)}\n$json") }, valid => valid ) } } private def cacheResult[A](a:A,name: String)(implicit hc: HeaderCarrier, formats: Format[A]): A = { val timerContext = metricsService.keystoreWriteTimer.time() val cacheF = sessionCache.cache[A](name, a) cacheF.onSuccess { case _ => timerContext.stop() } cacheF.onFailure { case _ => metricsService.keystoreWriteFailed.inc() } a } private def formatJsonErrors(errors: Seq[(JsPath, Seq[ValidationError])]): String = { errors.map(p => p._1 + " - " + p._2.map(e => removeJson(e.message)).mkString(",")).mkString(" | ") } private def removeJson(message: String): String = { message.indexOf("{") match { case i if i != -1 => message.substring(0, i - 1) + " [JSON removed]" case _ => message } } private[connectors] class JsonValidationException(message: String) extends Exception(message) }
Example 73
Source File: NpsDate.scala From nisp-frontend with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.nisp.models import org.joda.time.LocalDate import org.joda.time.format.DateTimeFormat import play.api.data.validation.ValidationError import play.api.libs.json._ import uk.gov.hmrc.nisp.utils.Constants case class NpsDate (localDate: LocalDate) { val toNpsString: String = NpsDate.dateFormat.print(localDate) val taxYear: Int = { val year = localDate.year.get if (localDate.isBefore(new LocalDate(year, Constants.taxYearsStartEndMonth, Constants.taxYearStartDay))) year - 1 else year } } object NpsDate { private val dateFormat = DateTimeFormat.forPattern("dd/MM/yyyy") private val npsDateRegex = """^(\d\d)/(\d\d)/(\d\d\d\d)$""".r implicit val reads = new Reads[NpsDate] { override def reads(json:JsValue): JsResult[NpsDate] = { json match { case JsString(npsDateRegex(d,m,y)) => JsSuccess(NpsDate(new LocalDate(y.toInt, m.toInt, d.toInt))) case JsNull => JsError(ValidationError("Null date cannot convert to NpsDate")) } } } implicit val writes = new Writes[NpsDate] { override def writes(date: NpsDate): JsValue = JsString(date.toNpsString) } def taxYearEndDate(taxYear: Int): NpsDate = NpsDate(taxYear + 1, Constants.taxYearsStartEndMonth, Constants.taxYearEndDay) def taxYearStartDate(taxYear: Int): NpsDate = NpsDate(taxYear, Constants.taxYearsStartEndMonth, Constants.taxYearStartDay) def apply(year: Int, month: Int, day: Int): NpsDate = NpsDate(new LocalDate(year,month,day)) }
Example 74
Source File: StreamContentSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class StreamContentSpec extends FunSpec with Matchers { val streamJson: JsValue = Json.parse(""" { "text": "<STRING>", "name": "<STRING>" } """) val stream = StreamContent("<STRING>", "<STRING>") describe("StreamContent") { describe("#toTypeString") { it("should return correct type") { StreamContent.toTypeString should be ("stream") } } describe("implicit conversions") { it("should implicitly convert from valid json to a StreamContent instance") { // This is the least safe way to convert as an error is thrown if it fails streamJson.as[StreamContent] should be (stream) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteRequest = streamJson.asOpt[StreamContent] newCompleteRequest.get should be (stream) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteRequestResults = streamJson.validate[StreamContent] CompleteRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: StreamContent) => valid ) should be (stream) } it("should implicitly convert from a StreamContent instance to valid json") { Json.toJson(stream) should be (streamJson) } } } }
Example 75
Source File: CommMsgHandler.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.handler import org.apache.toree.comm.{KernelCommWriter, CommRegistrar, CommWriter, CommStorage} import org.apache.toree.global.ExecuteRequestState import org.apache.toree.kernel.protocol.v5.content.CommMsg import org.apache.toree.kernel.protocol.v5.kernel.{Utilities, ActorLoader} import org.apache.toree.kernel.protocol.v5.{KMBuilder, KernelMessage} import org.apache.toree.utils.MessageLogSupport import play.api.data.validation.ValidationError import play.api.libs.json.JsPath import scala.concurrent.Future import scala.concurrent.ExecutionContext.Implicits.global class CommMsgHandler( actorLoader: ActorLoader, commRegistrar: CommRegistrar, commStorage: CommStorage ) extends BaseHandler(actorLoader) with MessageLogSupport { override def process(kernelMessage: KernelMessage): Future[_] = Future { logKernelMessageAction("Initiating Comm Msg for", kernelMessage) ExecuteRequestState.processIncomingKernelMessage(kernelMessage) val kmBuilder = KMBuilder().withParent(kernelMessage) Utilities.parseAndHandle( kernelMessage.contentString, CommMsg.commMsgReads, handler = handleCommMsg(kmBuilder), errHandler = handleParseError ) } private def handleCommMsg(kmBuilder: KMBuilder)(commMsg: CommMsg) = { val commId = commMsg.comm_id val data = commMsg.data logger.debug(s"Received comm_msg with id '$commId'") val commWriter = new KernelCommWriter(actorLoader, kmBuilder, commId) commStorage.getCommIdCallbacks(commId) match { case None => logger.warn(s"Received invalid id for Comm Msg: $commId") case Some(callbacks) => logger.debug(s"Executing msg callbacks for id '$commId'") // TODO: Should we be checking the return values? Probably not. callbacks.executeMsgCallbacks(commWriter, commId, data) .filter(_.isFailure).map(_.failed).foreach(throwable => { logger.error("Comm msg callback encountered an error!", throwable) }) } } private def handleParseError(invalid: Seq[(JsPath, Seq[ValidationError])]) = { // TODO: Determine proper response for a parse failure logger.warn("Parse error for Comm Msg! Not responding!") } }
Example 76
Source File: IsCompleteHandler.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.handler import akka.pattern.ask import org.apache.toree.kernel.protocol.v5._ import org.apache.toree.kernel.protocol.v5.content._ import org.apache.toree.kernel.protocol.v5.kernel.{ActorLoader, Utilities} import Utilities._ import org.apache.toree.utils.{MessageLogSupport, LogLike} import play.api.data.validation.ValidationError import play.api.libs.json.{JsPath, Json} import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future import scala.util.Success class IsCompleteHandler(actorLoader: ActorLoader) extends BaseHandler(actorLoader) with MessageLogSupport { override def process(kernelMessage: KernelMessage): Future[_] = { logKernelMessageAction("Determining if code is complete for", kernelMessage) Utilities.parseAndHandle( kernelMessage.contentString, IsCompleteRequest.isCompleteRequestReads, isCompleteRequest(kernelMessage, _ : IsCompleteRequest) ) } private def isCompleteRequest(km: KernelMessage, cr: IsCompleteRequest): Future[(String, String)] = { val interpreterActor = actorLoader.load(SystemActorType.Interpreter) val codeCompleteFuture = ask(interpreterActor, cr).mapTo[(String, String)] codeCompleteFuture.onComplete { case Success(tuple) => val reply = IsCompleteReply(tuple._1, tuple._2) val isCompleteReplyType = MessageType.Outgoing.IsCompleteReply.toString logKernelMessageAction("Sending is complete reply for", km) actorLoader.load(SystemActorType.KernelMessageRelay) ! km.copy( header = HeaderBuilder.create(isCompleteReplyType), parentHeader = km.header, contentString = Json.toJson(reply).toString ) case _ => new Exception("Parse error in CodeCompleteHandler") } codeCompleteFuture } }
Example 77
Source File: CodeCompleteHandler.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.handler import akka.pattern.ask import org.apache.toree.kernel.protocol.v5._ import org.apache.toree.kernel.protocol.v5.content._ import org.apache.toree.kernel.protocol.v5.kernel.{ActorLoader, Utilities} import Utilities._ import org.apache.toree.utils.{MessageLogSupport, LogLike} import play.api.data.validation.ValidationError import play.api.libs.json.{JsPath, Json} import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future import scala.util.Success class CodeCompleteHandler(actorLoader: ActorLoader) extends BaseHandler(actorLoader) with MessageLogSupport { override def process(kernelMessage: KernelMessage): Future[_] = { logKernelMessageAction("Generating code completion for", kernelMessage) Utilities.parseAndHandle( kernelMessage.contentString, CompleteRequest.completeRequestReads, completeRequest(kernelMessage, _ : CompleteRequest) ) } private def completeRequest(km: KernelMessage, cr: CompleteRequest): Future[(Int, List[String])] = { val interpreterActor = actorLoader.load(SystemActorType.Interpreter) val codeCompleteFuture = ask(interpreterActor, cr).mapTo[(Int, List[String])] codeCompleteFuture.onComplete { case Success(tuple) => val reply = CompleteReplyOk(tuple._2, tuple._1, cr.cursor_pos, Metadata()) val completeReplyType = MessageType.Outgoing.CompleteReply.toString logKernelMessageAction("Sending code complete reply for", km) actorLoader.load(SystemActorType.KernelMessageRelay) ! km.copy( header = HeaderBuilder.create(completeReplyType), parentHeader = km.header, contentString = Json.toJson(reply).toString ) case _ => new Exception("Parse error in CodeCompleteHandler") } codeCompleteFuture } }
Example 78
Source File: Utilities.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.client import java.nio.charset.Charset import akka.util.{ByteString, Timeout} import org.apache.toree.communication.ZMQMessage import org.apache.toree.kernel.protocol.v5._ import org.apache.toree.kernel.protocol.v5.content.ExecuteRequest import org.apache.toree.utils.LogLike import play.api.data.validation.ValidationError import play.api.libs.json.{JsPath, Json, Reads} import scala.concurrent.duration._ object Utilities extends LogLike { // // NOTE: This is brought in to remove feature warnings regarding the use of // implicit conversions regarding the following: // // 1. ByteStringToString // 2. ZMQMessageToKernelMessage // import scala.language.implicitConversions private val sessionId: UUID = java.util.UUID.randomUUID().toString implicit val timeout = Timeout(21474835.seconds) // Maximum delay implicit def ByteStringToString(byteString : ByteString) : String = { new String(byteString.toArray, Charset.forName("UTF-8")) } implicit def StringToByteString(string : String) : ByteString = { ByteString(string.getBytes) } implicit def ZMQMessageToKernelMessage(message: ZMQMessage): KernelMessage = { val delimiterIndex: Int = message.frames.indexOf(ByteString("<IDS|MSG>".getBytes)) // TODO Handle the case where there is no delimiter val ids: Seq[Array[Byte]] = message.frames.take(delimiterIndex).map( (byteString : ByteString) => { byteString.toArray } ) val header = Json.parse(message.frames(delimiterIndex + 2)).as[Header] val parentHeader = Json.parse(message.frames(delimiterIndex + 3)).validate[ParentHeader].fold[ParentHeader]( // TODO: Investigate better solution than setting parentHeader to null for {} (invalid: Seq[(JsPath, Seq[ValidationError])]) => null, //HeaderBuilder.empty, (valid: ParentHeader) => valid ) val metadata = Json.parse(message.frames(delimiterIndex + 4)).as[Metadata] KMBuilder().withIds(ids.toList) .withSignature(message.frame(delimiterIndex + 1)) .withHeader(header) .withParentHeader(parentHeader) .withMetadata(metadata) .withContentString(message.frame(delimiterIndex + 5)).build(false) } implicit def KernelMessageToZMQMessage(kernelMessage : KernelMessage) : ZMQMessage = { val frames: scala.collection.mutable.ListBuffer[ByteString] = scala.collection.mutable.ListBuffer() kernelMessage.ids.map((id : Array[Byte]) => frames += ByteString.apply(id) ) frames += "<IDS|MSG>" frames += kernelMessage.signature frames += Json.toJson(kernelMessage.header).toString() frames += Json.toJson(kernelMessage.parentHeader).toString() frames += Json.toJson(kernelMessage.metadata).toString frames += kernelMessage.contentString ZMQMessage(frames : _*) } def parseAndHandle[T](json: String, reads: Reads[T], handler: T => Unit) : Unit = { Json.parse(json).validate[T](reads).fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => logger.error(s"Could not parse JSON, ${json}"), (content: T) => handler(content) ) } def getSessionId = sessionId def toKernelMessage(message: ExecuteRequest): KernelMessage = { // construct a kernel message whose content is an ExecuteRequest val id = java.util.UUID.randomUUID().toString val header = Header( id, "spark", sessionId, MessageType.Incoming.ExecuteRequest.toString, "5.0") KMBuilder().withIds(Seq[Array[Byte]]()).withSignature("").withHeader(header) .withParentHeader(HeaderBuilder.empty).withContentString(message).build } }
Example 79
Source File: InspectReplyErrorSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.apache.toree.kernel.protocol.v5._ import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class InspectReplyErrorSpec extends FunSpec with Matchers { val inspectReplyErrorJson: JsValue = Json.parse(""" { "status": "error", "data": {}, "metadata": {}, "ename": "<STRING>", "evalue": "<STRING>", "traceback": [] } """) val inspectReplyError: InspectReplyError = InspectReplyError( Data(), Metadata(), Some("<STRING>"), Some("<STRING>"), Some(List()) ) describe("InspectReplyError") { describe("implicit conversions") { it("should implicitly convert from valid json to a InspectReplyError instance") { // This is the least safe way to convert as an error is thrown if it fails inspectReplyErrorJson.as[InspectReplyError] should be (inspectReplyError) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newInspectReplyError = inspectReplyErrorJson.asOpt[InspectReplyError] newInspectReplyError.get should be (inspectReplyError) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val InspectReplyErrorResults = inspectReplyErrorJson.validate[InspectReplyError] InspectReplyErrorResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: InspectReplyError) => valid ) should be (inspectReplyError) } it("should implicitly convert from a InspectReplyError instance to valid json") { Json.toJson(inspectReplyError) should be (inspectReplyErrorJson) } } } }
Example 80
Source File: KernelStatusSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json.{JsPath, JsValue, Json} class KernelStatusSpec extends FunSpec with Matchers { val kernelStatusJson: JsValue = Json.parse(""" { "execution_state": "<STRING>" } """) val kernelStatus: KernelStatus = KernelStatus("<STRING>") describe("KernelStatus") { describe("#toTypeString") { it("should return correct type") { KernelStatus.toTypeString should be ("status") } } describe("implicit conversions") { it("should implicitly convert from valid json to a kernelStatus instance") { // This is the least safe way to convert as an error is thrown if it fails kernelStatusJson.as[KernelStatus] should be (kernelStatus) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newKernelStatus = kernelStatusJson.asOpt[KernelStatus] newKernelStatus.get should be (kernelStatus) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val kernelStatusResults = kernelStatusJson.validate[KernelStatus] kernelStatusResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: KernelStatus) => valid ) should be (kernelStatus) } it("should implicitly convert from a kernelStatus instance to valid json") { Json.toJson(kernelStatus) should be (kernelStatusJson) } } } }
Example 81
Source File: HistoryReplySpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ import org.apache.toree.kernel.protocol.v5._ class HistoryReplySpec extends FunSpec with Matchers { val historyReplyJson: JsValue = Json.parse(""" { "history": ["<STRING>", "<STRING2>", "<STRING3>"] } """) val historyReply = HistoryReply( List("<STRING>", "<STRING2>", "<STRING3>") ) describe("HistoryReply") { describe("#toTypeString") { it("should return correct type") { HistoryReply.toTypeString should be ("history_reply") } } describe("implicit conversions") { it("should implicitly convert from valid json to a HistoryReply instance") { // This is the least safe way to convert as an error is thrown if it fails historyReplyJson.as[HistoryReply] should be (historyReply) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteRequest = historyReplyJson.asOpt[HistoryReply] newCompleteRequest.get should be (historyReply) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteRequestResults = historyReplyJson.validate[HistoryReply] CompleteRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: HistoryReply) => valid ) should be (historyReply) } it("should implicitly convert from a HistoryReply instance to valid json") { Json.toJson(historyReply) should be (historyReplyJson) } } } }
Example 82
Source File: ExecuteInputSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class ExecuteInputSpec extends FunSpec with Matchers { val executeInputJson: JsValue = Json.parse(""" { "code": "<STRING>", "execution_count": 42 } """) val executeInput: ExecuteInput = ExecuteInput( "<STRING>", 42 ) describe("ExecuteInput") { describe("#toTypeString") { it("should return correct type") { ExecuteInput.toTypeString should be ("execute_input") } } describe("implicit conversions") { it("should implicitly convert from valid json to a executeInput instance") { // This is the least safe way to convert as an error is thrown if it fails executeInputJson.as[ExecuteInput] should be (executeInput) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newExecuteInput = executeInputJson.asOpt[ExecuteInput] newExecuteInput.get should be (executeInput) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val executeInputResults = executeInputJson.validate[ExecuteInput] executeInputResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: ExecuteInput) => valid ) should be (executeInput) } it("should implicitly convert from a executeInput instance to valid json") { Json.toJson(executeInput) should be (executeInputJson) } } } }
Example 83
Source File: DisplayDataSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.FunSuite import org.scalatest.{Matchers, FunSpec} import play.api.data.validation.ValidationError import play.api.libs.json._ import org.apache.toree.kernel.protocol.v5._ class DisplayDataSpec extends FunSpec with Matchers { val displayDataJson: JsValue = Json.parse(""" { "source": "<STRING>", "data": {}, "metadata": {} } """) val displayData: DisplayData = DisplayData( "<STRING>", Map(), Map() ) describe("DisplayData") { describe("#toTypeString") { it("should return correct type") { DisplayData.toTypeString should be ("display_data") } } describe("implicit conversions") { it("should implicitly convert from valid json to a displayData instance") { // This is the least safe way to convert as an error is thrown if it fails displayDataJson.as[DisplayData] should be (displayData) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newDisplayData = displayDataJson.asOpt[DisplayData] newDisplayData.get should be (displayData) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val displayDataResults = displayDataJson.validate[DisplayData] displayDataResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: DisplayData) => valid ) should be (displayData) } it("should implicitly convert from a displayData instance to valid json") { Json.toJson(displayData) should be (displayDataJson) } } } }
Example 84
Source File: ShutdownReplySpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class ShutdownReplySpec extends FunSpec with Matchers { val shutdownReplyJson: JsValue = Json.parse(""" { "restart": true } """) val shutdownReply: ShutdownReply = ShutdownReply( true ) describe("ShutdownReply") { describe("#toTypeString") { it("should return correct type") { ShutdownReply.toTypeString should be ("shutdown_reply") } } describe("implicit conversions") { it("should implicitly convert from valid json to a ShutdownReply instance") { // This is the least safe way to convert as an error is thrown if it fails shutdownReplyJson.as[ShutdownReply] should be (shutdownReply) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newShutdownReply = shutdownReplyJson.asOpt[ShutdownReply] newShutdownReply.get should be (shutdownReply) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val ShutdownReplyResults = shutdownReplyJson.validate[ShutdownReply] ShutdownReplyResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: ShutdownReply) => valid ) should be (shutdownReply) } it("should implicitly convert from a ShutdownReply instance to valid json") { Json.toJson(shutdownReply) should be (shutdownReplyJson) } } } }
Example 85
Source File: HistoryRequestSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class HistoryRequestSpec extends FunSpec with Matchers { val historyRequestJson: JsValue = Json.parse(""" { "output": true, "ras": true, "hist_access_type": "<STRING>", "session": 1, "start": 0, "stop": 5, "n": 1, "pattern": "<STRING>", "unique": true } """) val historyRequest = HistoryRequest( true, true, "<STRING>", 1, 0, 5, 1, "<STRING>", true ) describe("HistoryRequest") { describe("#toTypeString") { it("should return correct type") { HistoryRequest.toTypeString should be ("history_request") } } describe("implicit conversions") { it("should implicitly convert from valid json to a HistoryRequest instance") { // This is the least safe way to convert as an error is thrown if it fails historyRequestJson.as[HistoryRequest] should be (historyRequest) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteRequest = historyRequestJson.asOpt[HistoryRequest] newCompleteRequest.get should be (historyRequest) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteRequestResults = historyRequestJson.validate[HistoryRequest] CompleteRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: HistoryRequest) => valid ) should be (historyRequest) } it("should implicitly convert from a HistoryRequest instance to valid json") { Json.toJson(historyRequest) should be (historyRequestJson) } } } }
Example 86
Source File: ShutdownHandler.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.handler import org.apache.toree.comm.{CommRegistrar, CommStorage, KernelCommWriter} import org.apache.toree.kernel.protocol.v5.content.{ShutdownReply, ShutdownRequest, CommOpen} import org.apache.toree.kernel.protocol.v5.kernel.{ActorLoader, Utilities} import org.apache.toree.kernel.protocol.v5._ import org.apache.toree.security.KernelSecurityManager import org.apache.toree.utils.MessageLogSupport import play.api.data.validation.ValidationError import play.api.libs.json.JsPath import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future class ShutdownHandler( actorLoader: ActorLoader ) extends BaseHandler(actorLoader) with MessageLogSupport { override def process(kernelMessage: KernelMessage): Future[_] = Future { logKernelMessageAction("Initiating Shutdown request for", kernelMessage) val kernelInfo = SparkKernelInfo val shutdownReply = ShutdownReply(false) val replyHeader = Header( java.util.UUID.randomUUID.toString, "", java.util.UUID.randomUUID.toString, ShutdownReply.toTypeString, kernelInfo.protocolVersion) val kernelResponseMessage = KMBuilder() .withIds(kernelMessage.ids) .withSignature("") .withHeader(replyHeader) .withParent(kernelMessage) .withContentString(shutdownReply).build logger.debug("Attempting graceful shutdown.") actorLoader.load(SystemActorType.KernelMessageRelay) ! kernelResponseMessage // Instruct security manager that exit should be allowed KernelSecurityManager.enableRestrictedExit() System.exit(0) } }
Example 87
Source File: ConnectRequestSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class ConnectRequestSpec extends FunSpec with Matchers { val connectRequestJson: JsValue = Json.parse(""" {} """) val connectRequest: ConnectRequest = ConnectRequest() describe("ConnectRequest") { describe("#toTypeString") { it("should return correct type") { ConnectRequest.toTypeString should be ("connect_request") } } describe("implicit conversions") { it("should implicitly convert from valid json to a ConnectRequest instance") { // This is the least safe way to convert as an error is thrown if it fails connectRequestJson.as[ConnectRequest] should be (connectRequest) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newConnectRequest = connectRequestJson.asOpt[ConnectRequest] newConnectRequest.get should be (connectRequest) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val ConnectRequestResults = connectRequestJson.validate[ConnectRequest] ConnectRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: ConnectRequest) => valid ) should be (connectRequest) } it("should implicitly convert from a ConnectRequest instance to valid json") { Json.toJson(connectRequest) should be (connectRequestJson) } } } }
Example 88
Source File: ExecuteRequestSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{Matchers, FunSpec} import play.api.data.validation.ValidationError import play.api.libs.json._ import org.apache.toree.kernel.protocol.v5._ class ExecuteRequestSpec extends FunSpec with Matchers { val executeRequestJson: JsValue = Json.parse(""" { "code": "<STRING>", "silent": false, "store_history": false, "user_expressions": {}, "allow_stdin": false } """) val executeRequest: ExecuteRequest = ExecuteRequest( "<STRING>", false, false, UserExpressions(), false ) describe("ExecuteRequest") { describe("#toTypeString") { it("should return correct type") { ExecuteRequest.toTypeString should be ("execute_request") } } describe("implicit conversions") { it("should implicitly convert from valid json to a executeRequest instance") { // This is the least safe way to convert as an error is thrown if it fails executeRequestJson.as[ExecuteRequest] should be (executeRequest) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newExecuteRequest = executeRequestJson.asOpt[ExecuteRequest] newExecuteRequest.get should be (executeRequest) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val executeRequestResults = executeRequestJson.validate[ExecuteRequest] executeRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: ExecuteRequest) => valid ) should be (executeRequest) } it("should implicitly convert from a executeRequest instance to valid json") { Json.toJson(executeRequest) should be (executeRequestJson) } } } }
Example 89
Source File: ExecuteReplyAbortSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.apache.toree.kernel.protocol.v5._ import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class ExecuteReplyAbortSpec extends FunSpec with Matchers { val executeReplyAbortJson: JsValue = Json.parse(""" { "status": "abort", "execution_count": 999 } """) val executeReplyAbort: ExecuteReplyAbort = ExecuteReplyAbort( 999 ) describe("ExecuteReplyAbort") { describe("implicit conversions") { it("should implicitly convert from valid json to a ExecuteReplyAbort instance") { // This is the least safe way to convert as an error is thrown if it fails executeReplyAbortJson.as[ExecuteReplyAbort] should be (executeReplyAbort) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newExecuteReplyAbort = executeReplyAbortJson.asOpt[ExecuteReplyAbort] newExecuteReplyAbort.get should be (executeReplyAbort) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val ExecuteReplyAbortResults = executeReplyAbortJson.validate[ExecuteReplyAbort] ExecuteReplyAbortResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: ExecuteReplyAbort) => valid ) should be (executeReplyAbort) } it("should implicitly convert from a ExecuteReplyAbort instance to valid json") { Json.toJson(executeReplyAbort) should be (executeReplyAbortJson) } } } }
Example 90
Source File: InspectReplySpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class InspectReplySpec extends FunSpec with Matchers { val inspectReplyJson: JsValue = Json.parse(""" { "status": "<STRING>", "data": {}, "metadata": {} } """) val inspectReply: InspectReply = InspectReply( "<STRING>", Map(), Map(), None, None, None ) describe("InspectReply") { describe("#toTypeString") { it("should return correct type") { InspectReply.toTypeString should be ("inspect_reply") } } describe("implicit conversions") { it("should implicitly convert from valid json to a InspectReply instance") { // This is the least safe way to convert as an error is thrown if it fails inspectReplyJson.as[InspectReply] should be (inspectReply) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newInspectReply = inspectReplyJson.asOpt[InspectReply] newInspectReply.get should be (inspectReply) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val InspectReplyResults = inspectReplyJson.validate[InspectReply] InspectReplyResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: InspectReply) => valid ) should be (inspectReply) } it("should implicitly convert from a InspectReply instance to valid json") { Json.toJson(inspectReply) should be (inspectReplyJson) } } } }
Example 91
Source File: ErrorContentSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{Matchers, FunSpec} import play.api.data.validation.ValidationError import play.api.libs.json._ class ErrorContentSpec extends FunSpec with Matchers { val errorJson: JsValue = Json.parse(""" { "ename": "<STRING>", "evalue": "<STRING>", "traceback": ["<STRING>"] } """) val error = ErrorContent("<STRING>", "<STRING>", List("<STRING>")) describe("ErrorContent") { describe("#toTypeString") { it("should return correct type") { ErrorContent.toTypeString should be ("error") } } describe("implicit conversions") { it("should implicitly convert from valid json to a ErrorContent instance") { // This is the least safe way to convert as an error is thrown if it fails errorJson.as[ErrorContent] should be (error) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteRequest = errorJson.asOpt[ErrorContent] newCompleteRequest.get should be (error) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteRequestResults = errorJson.validate[ErrorContent] CompleteRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: ErrorContent) => valid ) should be (error) } it("should implicitly convert from a ErrorContent instance to valid json") { Json.toJson(error) should be (errorJson) } } } }
Example 92
Source File: CompleteRequestSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class CompleteRequestSpec extends FunSpec with Matchers { val completeRequestJson: JsValue = Json.parse(""" { "code": "<STRING>", "cursor_pos": 999 } """) val completeRequest: CompleteRequest = CompleteRequest( "<STRING>", 999 ) describe("CompleteRequest") { describe("#toTypeString") { it("should return correct type") { CompleteRequest.toTypeString should be ("complete_request") } } describe("implicit conversions") { it("should implicitly convert from valid json to a CompleteRequest instance") { // This is the least safe way to convert as an error is thrown if it fails completeRequestJson.as[CompleteRequest] should be (completeRequest) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteRequest = completeRequestJson.asOpt[CompleteRequest] newCompleteRequest.get should be (completeRequest) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteRequestResults = completeRequestJson.validate[CompleteRequest] CompleteRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: CompleteRequest) => valid ) should be (completeRequest) } it("should implicitly convert from a CompleteRequest instance to valid json") { Json.toJson(completeRequest) should be (completeRequestJson) } } } }
Example 93
Source File: ExecuteReplyOkSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ import org.apache.toree.kernel.protocol.v5._ class ExecuteReplyOkSpec extends FunSpec with Matchers { val executeReplyOkJson: JsValue = Json.parse(""" { "status": "ok", "execution_count": 999, "payload": [], "user_expressions": {} } """) val executeReplyOk: ExecuteReplyOk = ExecuteReplyOk( 999, Some(Payloads()), Some(UserExpressions()) ) describe("ExecuteReplyOk") { describe("implicit conversions") { it("should implicitly convert from valid json to a executeReplyOk instance") { // This is the least safe way to convert as an error is thrown if it fails executeReplyOkJson.as[ExecuteReplyOk] should be (executeReplyOk) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newExecuteReplyOk = executeReplyOkJson.asOpt[ExecuteReplyOk] newExecuteReplyOk.get should be (executeReplyOk) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val executeReplyOkResults = executeReplyOkJson.validate[ExecuteReplyOk] executeReplyOkResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: ExecuteReplyOk) => valid ) should be (executeReplyOk) } it("should implicitly convert from a executeReplyOk instance to valid json") { Json.toJson(executeReplyOk) should be (executeReplyOkJson) } } } }
Example 94
Source File: InspectRequestSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ class InspectRequestSpec extends FunSpec with Matchers { val inspectRequestJson: JsValue = Json.parse(""" { "code": "<STRING>", "cursor_pos": 999, "detail_level": 1 } """) val inspectRequest: InspectRequest = InspectRequest( "<STRING>", 999, 1 ) describe("InspectRequest") { describe("#toTypeString") { it("should return correct type") { InspectRequest.toTypeString should be ("inspect_request") } } describe("implicit conversions") { it("should implicitly convert from valid json to a InspectRequest instance") { // This is the least safe way to convert as an error is thrown if it fails inspectRequestJson.as[InspectRequest] should be (inspectRequest) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newInspectRequest = inspectRequestJson.asOpt[InspectRequest] newInspectRequest.get should be (inspectRequest) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val InspectRequestResults = inspectRequestJson.validate[InspectRequest] InspectRequestResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: InspectRequest) => valid ) should be (inspectRequest) } it("should implicitly convert from a InspectRequest instance to valid json") { Json.toJson(inspectRequest) should be (inspectRequestJson) } } } }
Example 95
Source File: CompleteReplySpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{Matchers, FunSpec} import play.api.data.validation.ValidationError import play.api.libs.json.{JsPath, JsValue, Json} class CompleteReplySpec extends FunSpec with Matchers { val completeReplyJson: JsValue = Json.parse(""" { "matches": [], "cursor_start": 1, "cursor_end": 5, "metadata": {}, "status": "<STRING>" } """) val completeReply: CompleteReply = CompleteReply( List(), 1, 5, Map(), "<STRING>", None, None, None ) describe("CompleteReply") { describe("#toTypeString") { it("should return correct type") { CompleteReply.toTypeString should be ("complete_reply") } } describe("implicit conversions") { it("should implicitly convert from valid json to a CompleteReply instance") { // This is the least safe way to convert as an error is thrown if it fails completeReplyJson.as[CompleteReply] should be (completeReply) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newCompleteReply = completeReplyJson.asOpt[CompleteReply] newCompleteReply.get should be (completeReply) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val CompleteReplyResults = completeReplyJson.validate[CompleteReply] CompleteReplyResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: CompleteReply) => valid ) should be (completeReply) } it("should implicitly convert from a CompleteReply instance to valid json") { Json.toJson(completeReply) should be (completeReplyJson) } } } }
Example 96
Source File: InspectReplyOkSpec.scala From incubator-toree with Apache License 2.0 | 5 votes |
package org.apache.toree.kernel.protocol.v5.content import org.scalatest.{FunSpec, Matchers} import play.api.data.validation.ValidationError import play.api.libs.json._ import org.apache.toree.kernel.protocol.v5._ class InspectReplyOkSpec extends FunSpec with Matchers { val inspectReplyOkJson: JsValue = Json.parse(""" { "status": "ok", "data": {}, "metadata": {} } """) val inspectReplyOk: InspectReplyOk = InspectReplyOk( Data(), Metadata() ) describe("InspectReplyOk") { describe("implicit conversions") { it("should implicitly convert from valid json to a InspectReplyOk instance") { // This is the least safe way to convert as an error is thrown if it fails inspectReplyOkJson.as[InspectReplyOk] should be (inspectReplyOk) } it("should also work with asOpt") { // This is safer, but we lose the error information as it returns // None if the conversion fails val newInspectReplyOk = inspectReplyOkJson.asOpt[InspectReplyOk] newInspectReplyOk.get should be (inspectReplyOk) } it("should also work with validate") { // This is the safest as it collects all error information (not just first error) and reports it val InspectReplyOkResults = inspectReplyOkJson.validate[InspectReplyOk] InspectReplyOkResults.fold( (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"), (valid: InspectReplyOk) => valid ) should be (inspectReplyOk) } it("should implicitly convert from a InspectReplyOk instance to valid json") { Json.toJson(inspectReplyOk) should be (inspectReplyOkJson) } } } }