本文整理汇总了Scala中cats.data.NonEmptyList类的典型用法代码示例。如果您正苦于以下问题:Scala NonEmptyList类的具体用法?Scala NonEmptyList怎么用?Scala NonEmptyList使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了NonEmptyList类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: AssetProcessing
//设置package包名称以及导入依赖的类
package templates
import aws.Interpreter.ErrorsOr
import cats.data.Validated.{Invalid, Valid}
import cats.data.{NonEmptyList, Validated, ValidatedNel}
import com.amazonaws.regions.{Region, Regions}
import com.ovoenergy.comms.model.{Channel, CommManifest}
object AssetProcessing {
private val assetTemplateReferenceRegex = "(?:'|\")(?: *)(assets)(?:/[^(\"')]+)(?: *)(?:'|\")".r
case class ProcessedFiles(templateFiles: List[UploadedTemplateFile], assetFiles: List[UploadedTemplateFile])
def processAssets(region: Regions,
assetsS3Bucket: String,
commManifest: CommManifest,
uploadedFiles: List[UploadedTemplateFile]): ErrorsOr[ProcessedFiles] = {
import cats.syntax.traverse._
import cats.instances.list._
val (assetFiles, nonAssetFiles) = uploadedFiles.partition(_.fileType == Asset)
val processedTemplateFiles: Validated[NonEmptyList[String], List[UploadedTemplateFile]] = nonAssetFiles
.traverseU(templateFile => {
replaceAssetReferences(region, assetsS3Bucket, templateFile.channel, commManifest, templateFile.contents)
.map(contents => templateFile.copy(contents = contents))
})
processedTemplateFiles.map(ProcessedFiles(_, assetFiles)).toEither
}
private def replaceAssetReferences(region: Regions,
assetsS3Bucket: String,
channel: Channel,
commManifest: CommManifest,
contents: Array[Byte]): ValidatedNel[String, Array[Byte]] = {
def replaceReferences(s3Endpoint: String, contentsString: String) = {
val replacementAssetsPath = s"$s3Endpoint/assets"
assetTemplateReferenceRegex
.replaceAllIn(contentsString, m => m.group(0).replaceFirst(m.group(1), replacementAssetsPath))
.getBytes
}
determineS3Endpoint(region, assetsS3Bucket, channel, commManifest).map(replaceReferences(_, new String(contents)))
}
private def determineS3Endpoint(region: Regions,
assetsS3Bucket: String,
channel: Channel,
commManifest: CommManifest): ValidatedNel[String, String] = {
if (!Region.getRegion(region).isServiceSupported("s3")) {
Invalid(NonEmptyList.of("S3 not supported in region selected"))
} else if (!Region.getRegion(region).hasHttpsEndpoint("s3")) {
Invalid(NonEmptyList.of("No https support for s3 in region selected"))
} else {
val s3ServiceEndpoint = Region.getRegion(region).getServiceEndpoint("s3")
Valid(
s"https://$s3ServiceEndpoint/$assetsS3Bucket/${commManifest.commType.toString.toLowerCase}/${commManifest.name}/${commManifest.version}/${channel.toString.toLowerCase}")
}
}
}
开发者ID:ovotech,项目名称:comms-template-manager,代码行数:59,代码来源:AssetProcessing.scala
示例2: DualTest
//设置package包名称以及导入依赖的类
package newts
import cats.data.NonEmptyList
import cats.kernel.laws.{GroupLaws, OrderLaws}
import cats.laws.discipline.{MonadTests, TraverseTests}
import cats.laws.discipline.arbitrary._
import fixtures.ShowTestClass
class DualTest extends NewtsSuite {
checkAll("Dual[NonEmptyList[Int]]", GroupLaws[Dual[NonEmptyList[Int]]].semigroup)
checkAll("Dual[List[Int]]" , GroupLaws[Dual[List[Int]]].monoid)
checkAll("Dual[Int]" , OrderLaws[Dual[Int]].eqv)
checkAll("Dual[Int]" , MonadTests[Dual].monad[Int, Int, Int])
checkAll("Dual[Int]" , TraverseTests[Dual].traverse[Int, Int, Int, Int, Option, Option])
test("combine"){
val xs = NonEmptyList.of(1,2)
val ys = NonEmptyList.of(3,4)
xs.asDual |+| ys.asDual shouldEqual (ys |+| xs).asDual
}
test("show") {
Dual("aString").show shouldEqual "Dual(aString)"
Dual(42).show shouldEqual "Dual(42)"
Dual(new ShowTestClass).show shouldEqual s"Dual(${ShowTestClass.show})"
}
test("dual of first is last"){
val xs = NonEmptyList(1, List(2,3,4,5))
xs.reduceMap(_.asFirst.asDual).getDual.getFirst shouldEqual 5
}
}
开发者ID:julien-truffaut,项目名称:newts,代码行数:36,代码来源:DualTest.scala
示例3: NelOps
//设置package包名称以及导入依赖的类
package tryp
import cats.data.NonEmptyList
final class NelOps[A](val self: NonEmptyList[A])
extends AnyVal
{
def length = 1 + self.tail.length
def lift(index: Int): Option[A] = {
if (index == 0) Some(self.head)
else self.tail.lift(index - 1)
}
def isDefinedAt(index: Int): Boolean = {
(index == 0) || self.tail.isDefinedAt(index - 1)
}
def minBy[B: Ordering](f: A => B) = {
if (self.tail.isEmpty) self.head
else self.tail.minBy(f)
}
def groupBy[B](f: A => B): NonEmptyList[NonEmptyList[A]] = {
val res = self.tail.groupBy(f)
.flatMap {
case (k, v) => v match {
case head :: tail => Some(NonEmptyList(head, tail))
case _ => None
}
}
res match {
case head :: tail => NonEmptyList(head, tail)
case _ => NonEmptyList.of(NonEmptyList.of(self.head))
}
}
def last = self.tail.lastOption | self.head
def reverse =
NonEmptyList.fromList(self.tail.reverse :+ self.head) | NonEmptyList.of(self.head)
def contains[A](a: A) =
self.exists(_ == a)
}
trait ToNelOps
{
implicit def ToNelOps[A](self: NonEmptyList[A]): NelOps[A] =
new NelOps[A](self)
}
开发者ID:tek,项目名称:pulsar,代码行数:52,代码来源:nonemptylist.scala
示例4: PartitionValidatedNelSpec
//设置package包名称以及导入依赖的类
package eu.svez.akka.stream.cats
import akka.NotUsed
import akka.stream.SinkShape
import akka.stream.scaladsl.{GraphDSL, Sink, Source}
import akka.stream.testkit.TestSubscriber
import cats.data.NonEmptyList
import cats.implicits._
import eu.svez.akka.stream.cats.Stages._
class PartitionValidatedNelSpec extends StageSpec {
"PartitionValidatedNel" should "partition a flow of Validation[E, A] in two flows of E and A" in new Test {
val src = Source(List(
1.valid[NonEmptyList[String]],
2.valid[NonEmptyList[String]],
NonEmptyList.of("BOOM!", "KABOOM!").invalid[Int],
3.valid[NonEmptyList[String]],
NonEmptyList.of("BOOM 2!").invalid[Int]
))
src.runWith(testSink)
successProbe.request(3)
failureProbe.request(3)
successProbe.expectNext(1)
successProbe.expectNext(2)
successProbe.expectNext(3)
failureProbe.expectNext("BOOM!")
failureProbe.expectNext("KABOOM!")
failureProbe.expectNext("BOOM 2!")
successProbe.expectComplete()
failureProbe.expectComplete()
}
trait Test {
val failureProbe = TestSubscriber.probe[String]()
val successProbe = TestSubscriber.probe[Int]()
val testSink = Sink.fromGraph(GraphDSL.create() { implicit builder: GraphDSL.Builder[NotUsed] =>
import GraphDSL.Implicits._
val valStage = builder.add(PartitionValidatedNel[String, Int]())
valStage.invalid ~> Sink.fromSubscriber(failureProbe)
valStage.valid ~> Sink.fromSubscriber(successProbe)
SinkShape(valStage.in)
})
}
}
开发者ID:svezfaz,项目名称:akka-stream-fp,代码行数:53,代码来源:PartitionValidatedNelSpec.scala
示例5: S3Operations
//设置package包名称以及导入依赖的类
package aws.s3
import java.io._
import java.util.zip.{ZipEntry, ZipOutputStream}
import aws.Interpreter.ErrorsOr
import cats.data.NonEmptyList
import cats.instances.either._
import cats.instances.list._
import cats.syntax.traverse._
import com.ovoenergy.comms.model.CommManifest
import logic.TemplateOp._
object S3Operations {
def downloadTemplateFiles(s3ClientWrapper: AmazonS3ClientWrapper,
commManifest: CommManifest,
bucketName: String): Either[String, TemplateFiles] = {
val prefix = buildPrefix(commManifest)
val fileKeys = s3ClientWrapper.listFiles(bucketName, prefix).right
fileKeys.flatMap { keys =>
val result = keys.toList.traverseU { absKey =>
val file = s3ClientWrapper.downloadFile(bucketName, absKey).right
val pair: Either[String, (String, Array[Byte])] = file map { f =>
val strippedKey = absKey.stripPrefix(prefix).dropWhile(_ == '/')
(strippedKey, f)
}
pair
}
result.right.map(_.toMap)
}
}
private def buildPrefix(commManifest: CommManifest) = {
s"${commManifest.commType.toString.toLowerCase}/${commManifest.name}/${commManifest.version}"
}
type ByteArray = Array[Byte]
def compressFiles(templateFiles: TemplateFiles): ErrorsOr[ByteArray] = {
val baos = new ByteArrayOutputStream()
try {
val zip = new ZipOutputStream(baos)
try {
templateFiles.foreach {
case (fileName, file) =>
zip.putNextEntry(new ZipEntry(fileName))
zip.write(file)
zip.closeEntry()
}
} finally {
zip.close()
}
val result = baos.toByteArray
Right(result)
} catch {
case e: Throwable => Left(NonEmptyList.of(s"Failed to compress template files: ${e.getMessage}"))
}
}
}
开发者ID:ovotech,项目名称:comms-template-manager,代码行数:62,代码来源:S3Operations.scala
示例6: CommTemplate
//设置package包名称以及导入依赖的类
package com.ovoenergy.comms.templates.model.template.processed
import cats.data.NonEmptyList
import cats.data.Validated.{Invalid, Valid}
import cats.instances.option._
import cats.syntax.traverse._
import cats.{Applicative, Apply, Id}
import com.ovoenergy.comms.templates._
import com.ovoenergy.comms.templates.model.RequiredTemplateData
import com.ovoenergy.comms.templates.model.template.processed.email.EmailTemplate
import com.ovoenergy.comms.templates.model.template.processed.sms.SMSTemplate
import scala.language.higherKinds
case class CommTemplate[M[_]: Applicative](
email: Option[M[EmailTemplate[Id]]],
sms: Option[M[SMSTemplate[Id]]]
) {
def checkAtLeastOneChannelDefined: ErrorsOr[Unit] = {
if (email.isEmpty && sms.isEmpty) Invalid(NonEmptyList.of("Template has no channels defined"))
else Valid(())
}
def aggregate: M[CommTemplate[Id]] =
Apply[M].map2(email.sequenceU, sms.sequenceU) { case (e, s) => CommTemplate[Id](e, s) }
def requiredData: M[ErrorsOr[RequiredTemplateData.obj]] = {
Apply[M].map2(email.sequenceU, sms.sequenceU) {
case (Some(e), Some(s)) =>
Apply[ErrorsOr].map2(e.requiredData, s.requiredData)(List(_, _)) andThen RequiredTemplateData.combine
case (Some(e), None) => e.requiredData
case (None, Some(s)) => s.requiredData
case (None, None) => Invalid(NonEmptyList.of("No templates to combine"))
}
}
}
开发者ID:ovotech,项目名称:comms-templates,代码行数:40,代码来源:CommTemplate.scala
示例7: matchesEmail
//设置package包名称以及导入依赖的类
package im.actor.server.api.rpc.service.auth
import cats.MonadCombine
import cats.data.{ NonEmptyList, Xor }
import cats.syntax.all._
import im.actor.api.rpc._
import im.actor.util.misc.StringUtils
import org.apache.commons.validator.routines.EmailValidator
private[auth] trait Helpers extends PublicKeyHelpers {
private def matchesEmail(s: String): NonEmptyList[String] Xor String =
if (EmailValidator.getInstance().isValid(s)) s.right else NonEmptyList.of("Should be valid email address").left
def validEmail(email: String): NonEmptyList[String] Xor String =
StringUtils.nonEmptyString(email).flatMap(e ? matchesEmail(e.toLowerCase))
private implicit val listMonadCombine = new MonadCombine[List] {
def pure[A](x: A): List[A] = List(x)
def flatMap[A, B](fa: List[A])(f: (A) ? List[B]): List[B] = fa flatMap f
def empty[A]: List[A] = List.empty[A]
def combineK[A](x: List[A], y: List[A]): List[A] = x ::: y
def tailRecM[A, B](a: A)(f: (A) ? List[Either[A, B]]): List[B] = defaultTailRecM(a)(f)
}
def validationFailed(errorName: String, errors: NonEmptyList[String]): RpcError =
RpcError(400, errorName, errors.toList.mkString(", "), false, None)
}
开发者ID:wex5,项目名称:dangchat-server,代码行数:29,代码来源:Helpers.scala
示例8: message
//设置package包名称以及导入依赖的类
package freecli
package argument
package parser
import cats.data.NonEmptyList
import api.ArgumentField
import core.api.StringDecoderError
import core.formatting._
import freecli.parser.DisplayErrors
sealed trait ArgumentParsingError {
def message: String
}
object ArgumentParsingError {
implicit object displayErrorsInstance extends DisplayErrors[NonEmptyList[ArgumentParsingError]] {
def display(errors: NonEmptyList[ArgumentParsingError]): String = {
errors.map(_.message).toList.mkString("\n")
}
}
}
case class AdditionalArgumentsFound(args: Seq[String])
extends ArgumentParsingError {
def message = s"Additional arguments found: ${args.mkString(", ")}"
}
case class ArgumentValueMissing(field: ArgumentField)
extends ArgumentParsingError {
def message = {
field match {
case ArgumentField(None, None) =>
s"Argument is missing"
case ArgumentField(Some(name), _) =>
s"Argument ${name.value.yellow} is missing"
case ArgumentField(None, Some(description)) =>
s"""Argument ${description.value.yellow} is missing"""
}
}
}
case class FailedToDecodeArgument(details: ArgumentField, error: StringDecoderError)
extends ArgumentParsingError {
def message =
s"Failed to decode argument ${details.shortDescription.yellow}. ${error.message}"
}
开发者ID:pavlosgi,项目名称:freecli,代码行数:53,代码来源:ArgumentParsingError.scala
示例9: ops
//设置package包名称以及导入依赖的类
package freecli
package argument
package parser
import cats.data.NonEmptyList
import api.Action
import dsl.ArgumentDsl
import freecli.parser.CliParser
object ops extends ParserOps
trait ParserOps {
private[freecli] def parseArgumentNonStrict[T](
dsl: ArgumentDsl[T]):
CliParser[Action, ArgumentParsingErrors, T] = {
dsl.foldMap(ArgumentParserInterpreter)
}
def parseArgument[T](
dsl: ArgumentDsl[T]):
CliParser[Action, ArgumentParsingErrors, T] = {
parseArgumentNonStrict(dsl).failIfNotAllArgumentsUsed(
args => NonEmptyList.of(AdditionalArgumentsFound(args.map(_.name))))
}
}
开发者ID:pavlosgi,项目名称:freecli,代码行数:28,代码来源:Ops.scala
示例10: ArgumentParserInterpreter
//设置package包名称以及导入依赖的类
package freecli
package argument
package parser
import cats.data.NonEmptyList
import cats.~>
import api._
import core.api.StringDecoder
import freecli.parser.CliParser
object ArgumentParserInterpreter extends (Algebra ~> ParseResult) {
def apply[A](fa: Algebra[A]): ParseResult[A] = {
fa match {
case Arg(details, f, g) =>
for {
nextArg <- CliParser.extractNext[Action, ArgumentParsingErrors]
res <- parseArg(details, nextArg, g)
} yield f(res)
}
}
def parseArg[T](
details: ArgumentField,
value: Option[String],
g: StringDecoder[T]):
CliParser[Action, ArgumentParsingErrors, T] = {
value match {
case None =>
CliParser.error(NonEmptyList.of(ArgumentValueMissing(details)))
case Some(v) =>
CliParser.fromValidated(g.apply(v)).mapError { e =>
e.map(err => FailedToDecodeArgument(details, err))
}
}
}
}
开发者ID:pavlosgi,项目名称:freecli,代码行数:40,代码来源:ArgumentParserInterpreter.scala
示例11: ops
//设置package包名称以及导入依赖的类
package freecli
package option
package parser
import cats.data.NonEmptyList
import option.api.Action
import option.dsl.OptionDsl
import freecli.parser.{CliArgument, CliParser}
object ops extends ParserOps
trait ParserOps {
private[freecli] def parseOptionNonStrict[T](
dsl: OptionDsl[T]):
CliParser[Action, OptionParsingErrors, T] = {
def unusedOutOfOrder(args: Seq[CliArgument]) = {
val l = args.map(a => (a, !a.isUsable)).dropWhile(_._2)
l.take(l.indexWhere(_._2)).map(_._1)
}
for {
r <- dsl.foldMap(OptionParserInterpreter)
args <- CliParser.getArgs[Action, OptionParsingErrors]
_ <- unusedOutOfOrder(args) match {
case Nil => CliParser.success[Action, OptionParsingErrors, Unit](())
case l => CliParser.error[Action, OptionParsingErrors, Unit](
NonEmptyList.of(ArgumentsDidNotMatchAnyOptions(l.map(_.name))))
}
} yield r
}
def parseOption[T](
dsl: OptionDsl[T]):
CliParser[Action, OptionParsingErrors, T] = {
parseOptionNonStrict(dsl).failIfNotAllArgumentsUsed(
args => NonEmptyList.of(AdditionalArgumentsFound(args.map(_.name))))
}
}
开发者ID:pavlosgi,项目名称:freecli,代码行数:41,代码来源:Ops.scala
示例12: ops
//设置package包名称以及导入依赖的类
package freecli
package config
package parser
import cats.data.NonEmptyList
import api.Action
import dsl.ConfigDsl
import freecli.parser.CliParser
object ops extends ParserOps
trait ParserOps {
private[freecli] def parseConfigNonStrict[T](
dsl: ConfigDsl[T]):
CliParser[Action, ConfigParsingErrors, T] = {
dsl.foldMap(ConfigParserInterpreter)
}
def parseConfig[T](
dsl: ConfigDsl[T]):
CliParser[Action, ConfigParsingErrors, T] = {
parseConfigNonStrict(dsl).failIfNotAllArgumentsUsed(
args => NonEmptyList.of(AdditionalArgumentsFound(args.map(_.name))))
}
}
开发者ID:pavlosgi,项目名称:freecli,代码行数:28,代码来源:ParserOps.scala
示例13: message
//设置package包名称以及导入依赖的类
package freecli
package config
package parser
import cats.data.NonEmptyList
import argument.{parser => A}
import option.{parser => O}
import freecli.parser.DisplayErrors
sealed trait ConfigParsingError {
def message: String
}
object ConfigParsingError {
implicit object displayErrorsInstance extends DisplayErrors[NonEmptyList[ConfigParsingError]] {
override def display(errors: NonEmptyList[ConfigParsingError]): String = {
errors.map(_.message).toList.mkString("\n")
}
}
}
case class ArgumentErrors(errors: NonEmptyList[A.ArgumentParsingError])
extends ConfigParsingError {
def message = errors.toList.map(_.message).mkString("\n")
}
case class OptionErrors(errors: NonEmptyList[O.OptionParsingError])
extends ConfigParsingError {
def message = errors.toList.map(_.message).mkString("\n")
}
case class OptionAndArgumentErrors(
optionErrors: NonEmptyList[A.ArgumentParsingError],
argumentErrors: NonEmptyList[O.OptionParsingError])
extends ConfigParsingError {
def message =
s"""Option errors, ${optionErrors.toList.map(_.message).mkString(", ")}
|Argument errors, ${argumentErrors.toList.map(_.message).mkString(", ")}
""".stripMargin
}
case class AdditionalArgumentsFound(args: Seq[String])
extends ConfigParsingError {
def message = s"Additional arguments found: ${args.mkString(", ")}"
}
开发者ID:pavlosgi,项目名称:freecli,代码行数:51,代码来源:ConfigParsingError.scala
示例14: jsonDecodedStringDecoder
//设置package包名称以及导入依赖的类
package freecli
package circe
import scala.io.Source
import cats.Show
import cats.syntax.show._
import cats.data.{NonEmptyList, Validated, ValidatedNel}
import io.circe.{Decoder, Json}
import io.circe.parser.parse
import core.api.{StringDecoder, StringDecoderError}
trait Instances {
implicit def jsonDecodedStringDecoder[T](
implicit ev: StringDecoder[Json],
show: Show[T],
decoder: Decoder[T]):
StringDecoder[T] = {
new StringDecoder[T] {
def apply(value: String): ValidatedNel[StringDecoderError, T] = {
ev(value) match {
case Validated.Valid(j) =>
Validated.fromEither(j.as[T]).leftMap(
f => NonEmptyList.of(StringDecoderError(f.message)))
case Validated.Invalid(e) => Validated.Invalid(e)
}
}
def toString(v: T): String = {
v.show
}
}
}
implicit def jsonStringDecoder: StringDecoder[Json] = {
new StringDecoder[Json] {
def apply(value: String): ValidatedNel[StringDecoderError, Json] = {
val stringToParse =
if (value.matches(".+\\.json")) {
Source.fromFile(value).mkString
} else value
parse(stringToParse) match {
case Right(j) =>
Validated.valid(j)
case Left(e) => Validated.invalidNel(StringDecoderError(e.message))
}
}
def toString(v: Json): String = {
v.spaces2
}
}
}
}
开发者ID:pavlosgi,项目名称:freecli,代码行数:61,代码来源:Instances.scala
示例15: Validations
//设置package包名称以及导入依赖的类
package com.wunder.pets.validations
import cats.data
import cats.data.{NonEmptyList, ValidatedNel}
import eu.timepit.refined.api.Validate
import eu.timepit.refined.refineV
import org.postgresql.util.PSQLException
object Validations {
type Validated[T] = ValidatedNel[ValidationError, T]
type Errors = NonEmptyList[ValidationError]
type ErrorMessages = Seq[String]
type WithErrorMessages[T] = Either[ErrorMessages, T]
def validate[VALUE, VALIDATION](v: VALUE, e: ValidationError)
(implicit validation: Validate[VALUE, VALIDATION]): Validated[VALUE] = {
val validated: Either[Errors, VALUE] = refineV[VALIDATION](v)
.left.map(_ => NonEmptyList(e, Nil))
.right.map(_.value)
data.Validated.fromEither(validated)
}
def assureUnique[T]: PartialFunction[Throwable, WithErrorMessages[T]] = {
case e: PSQLException => {
toErrorMessages(dbError(e))
}
}
def dbError(e: PSQLException): Errors = {
def isUniquenessViolation(e: PSQLException) = e.getServerErrorMessage.getDetail.matches(".* already exists.")
val error = if (isUniquenessViolation(e)) {
new DuplicateValue(e)
} else {
new GeneralError(e.getMessage)
}
NonEmptyList(error, Nil)
}
def toErrorMessages[T](errors: Errors): WithErrorMessages[T] = Left(errors.map(_.message).toList)
}
开发者ID:wunderteam,项目名称:battle-pets-api,代码行数:42,代码来源:Validations.scala
示例16: ProfileValidation
//设置package包名称以及导入依赖的类
package com.ovoenergy.orchestration.profile
import cats.data.Validated.{Invalid, Valid}
import cats.data.{NonEmptyList, Validated}
import cats.{Apply, Semigroup}
import com.ovoenergy.comms.model.InvalidProfile
import com.ovoenergy.orchestration.domain.CustomerProfile
import com.ovoenergy.orchestration.logging.LoggingWithMDC
import com.ovoenergy.orchestration.processes.Orchestrator.ErrorDetails
object ProfileValidation extends LoggingWithMDC {
case class ValidationError(message: String)
case class ValidationErrors(errors: NonEmptyList[ValidationError]) {
def errorsString: String = {
errors.map(_.message).toList.mkString(", ")
}
}
object ValidationErrors {
def apply(message: String): ValidationErrors = ValidationErrors(ValidationError(message))
def apply(error: ValidationError): ValidationErrors = ValidationErrors(NonEmptyList.of(error))
implicit val sg = new Semigroup[ValidationErrors] {
def combine(x: ValidationErrors, y: ValidationErrors): ValidationErrors =
ValidationErrors(x.errors.concat(y.errors))
}
}
private type ValidationErrorsOr[A] = Validated[ValidationErrors, A]
def apply(customerProfile: CustomerProfile): Either[ErrorDetails, CustomerProfile] = {
val firstName: ValidationErrorsOr[String] = {
if (customerProfile.name.firstName.isEmpty) Validated.invalid(ValidationErrors("Customer has no first name"))
else Validated.valid(customerProfile.name.firstName)
}
val lastName: ValidationErrorsOr[String] = {
if (customerProfile.name.lastName.isEmpty) Validated.invalid(ValidationErrors("Customer has no last name"))
else Validated.valid(customerProfile.name.lastName)
}
val profileOrErrors = Apply[ValidationErrorsOr].map2(firstName, lastName) {
case (validFirstName, validLastName) =>
customerProfile
}
profileOrErrors match {
case Valid(profile) => Right(profile)
case Invalid(errors) =>
Left(ErrorDetails(errors.errorsString, InvalidProfile))
}
}
}
开发者ID:ovotech,项目名称:comms-orchestration,代码行数:52,代码来源:ProfileValidation.scala
示例17: MonoidTests
//设置package包名称以及导入依赖的类
package catz
class MonoidTests extends CatzSuite {
test("MonoidEx1 tests") {
// Associativity and Semigroup with Empty
MonoidEx1.combine1 shouldBe 1
MonoidEx1.combine2 shouldBe 1
}
test("MonoidEx2 tests") {
// combineAll functionality as have an Empty
MonoidEx2.combineAll1 shouldBe 6
MonoidEx2.combineAll2 shouldBe "hello world"
MonoidEx2.combineAll3 shouldBe Map('b' -> 7, 'c' -> 5, 'a' -> 3)
MonoidEx2.combineAll4 shouldBe Set(5,1,2,3,4)
}
test("MonoidEx3 tests") {
import cats.data.NonEmptyList
MonoidEx3.optionMonoid1 shouldBe Some(NonEmptyList.of(1,2,3,4,5,6))
MonoidEx3.optionMonoid2 shouldBe None
MonoidEx3.optionMonoid3 shouldBe Some(NonEmptyList.of(1,2,3,4,5,6))
}
}
开发者ID:typelevel,项目名称:catz-cradle,代码行数:27,代码来源:MonoidTests.scala
示例18: DefaultConfig
//设置package包名称以及导入依赖的类
package infrastructure.config
import scala.collection.immutable.Seq
import cats.data.NonEmptyList
import cats.implicits.{ catsSyntaxEither, catsSyntaxUCartesian }
import pureconfig.error._
import pureconfig.loadConfig
object DefaultConfig extends ConfigApp {
private val configValidations = (
loadConfig[CassandraConfig]("owasp-training.cassandra").toValidatedNel |@|
loadConfig[HttpConfig]("owasp-training.http").toValidatedNel |@|
loadConfig[JwtConfig]("owasp-training.jwt").toValidatedNel
).tupled
val (
cassandraConfig,
httpConfig,
jwtConfig
) =
configValidations.fold(throwException, identity)
private[infrastructure] def throwException(failures: NonEmptyList[ConfigReaderFailures]): Nothing = {
val msg: String = buildMessage(failures)
throw new Exception(msg)
}
private[infrastructure] def buildMessage(nestedFailures: NonEmptyList[ConfigReaderFailures]): String = {
val flatFailures: Seq[ConfigReaderFailure] = nestedFailures.map(_.toList).toList.flatten
val errors: String = flatFailures.map {
case CannotParse(msg, _) => s"Can't not parse: $msg"
case CannotConvertNull(_) => "Found null config"
case CannotConvert(value, toTyp, because, _, _) => s"Att $value can't be set to $toTyp because $because"
case CollidingKeys(key, existingValue, _) => s"Att error: CollidingKeys $key - $existingValue"
case KeyNotFound(key, _, _) => s"Att $key not found"
case UnknownKey(key, _) => s"Att $key unknown"
case WrongType(foundTyp, expectedTyp, _, _) => s"Att has wrong type: found $foundTyp, expected $expectedTyp"
case ThrowableFailure(throwable, _, _) => s"Config throwable was thrown ${throwable.getMessage}"
case EmptyStringFound(typ, _, _) => s"Att empty string found $typ"
case NoValidCoproductChoiceFound(value, _, _) => s"Att No valid coproduct $value"
} mkString ", "
s"Errors while parsing config file: [$errors]"
}
}
开发者ID:karenvega,项目名称:owasp-training-play,代码行数:48,代码来源:DefaultConfig.scala
示例19: ManagementRoute
//设置package包名称以及导入依赖的类
package pl.touk.nussknacker.engine.standalone.http
import akka.http.scaladsl.marshalling.ToResponseMarshallable
import akka.http.scaladsl.model.{HttpResponse, StatusCodes}
import akka.http.scaladsl.server.{Directives, Route}
import cats.data.NonEmptyList
import com.typesafe.scalalogging.LazyLogging
import pl.touk.nussknacker.engine.api.deployment.DeploymentData
import pl.touk.nussknacker.engine.standalone.management.{DeploymentError, DeploymentService}
import pl.touk.nussknacker.engine.util.ThreadUtils
import pl.touk.http.argonaut.Argonaut62Support
import scala.concurrent.ExecutionContext
class ManagementRoute(processesClassLoader: ClassLoader, deploymentService: DeploymentService) extends Directives with Argonaut62Support with LazyLogging {
import argonaut.ArgonautShapeless._
def route(implicit ec: ExecutionContext): Route = ThreadUtils.withThisAsContextClassLoader(processesClassLoader) {
path("deploy") {
post {
entity(as[DeploymentData]) { data =>
complete {
toResponse(deploymentService.deploy(data.processId, data.processJson))
}
}
}
} ~ path("checkStatus" / Segment) { processId =>
get {
complete {
deploymentService.checkStatus(processId) match {
case None => HttpResponse(status = StatusCodes.NotFound)
case Some(resp) => resp
}
}
}
} ~ path("cancel" / Segment) { processId =>
post {
complete {
deploymentService.cancel(processId) match {
case None => HttpResponse(status = StatusCodes.NotFound)
case Some(resp) => resp
}
}
}
}
}
def toResponse(either: Either[NonEmptyList[DeploymentError], Unit]): ToResponseMarshallable = either match {
case Right(unit) =>
unit
case Left(error) =>
//TODO: something better?
HttpResponse(status = StatusCodes.BadRequest, entity = error.toList.mkString(", "))
}
}
开发者ID:TouK,项目名称:nussknacker,代码行数:60,代码来源:ManagementRoute.scala
示例20: instantTimerWindowInSeconds
//设置package包名称以及导入依赖的类
package pl.touk.nussknacker.engine.standalone.metrics
import cats.data.NonEmptyList
import pl.touk.nussknacker.engine.api.exception.EspExceptionInfo
import pl.touk.nussknacker.engine.standalone.utils.metrics.WithEspTimers
import pl.touk.nussknacker.engine.util.service.EspTimer
import scala.concurrent.{ExecutionContext, Future}
import scala.util.control.NonFatal
import scala.util.{Failure, Success}
trait InvocationMetrics extends WithEspTimers {
override protected def instantTimerWindowInSeconds = 20
private val nodeErrorTimers : collection.concurrent.TrieMap[String, EspTimer] = collection.concurrent.TrieMap()
//TODO: maybe var initialized in `open`?
private lazy val succesTimer = espTimer("success")
def measureTime[T](invocation: => Future[Either[NonEmptyList[EspExceptionInfo[_ <: Throwable]], T]])(implicit ec: ExecutionContext) :
Future[Either[NonEmptyList[EspExceptionInfo[_ <: Throwable]], T]]= {
val start = System.nanoTime()
try {
val future = invocation
future.onComplete {
case Success(Left(errors)) => errors.toList.foreach(ex => markErrorTimer(start, ex.nodeId))
case Success(Right(_)) => succesTimer.update(start)
case Failure(e) => markErrorTimer(start)
}
future
} catch {
case NonFatal(e) => markErrorTimer(start); throw e
}
}
private def markErrorTimer(startTime: Long, nodeId: Option[String] = None) : Unit = {
val id = nodeId.getOrElse("unknown")
nodeErrorTimers.getOrElseUpdate(id, espTimer(id)).update(startTime)
}
}
开发者ID:TouK,项目名称:nussknacker,代码行数:42,代码来源:InvocationMetrics.scala
注:本文中的cats.data.NonEmptyList类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论