本文整理汇总了Scala中cats.data.NonEmptyList类的典型用法代码示例。如果您正苦于以下问题:Scala NonEmptyList类的具体用法?Scala NonEmptyList怎么用?Scala NonEmptyList使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了NonEmptyList类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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}")
}
}
}
示例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
}
}
示例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)
}
示例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)
})
}
}
示例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}"))
}
}
}
示例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"))
}
}
}
示例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)
}
示例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}"
}
示例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))))
}
}
示例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))
}
}
}
}
示例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))))
}
}
示例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))))
}
}
示例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(", ")}"
}
示例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
}
}
}
}
示例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)
}