Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

avoid deprecated scala.Either#right #10910

Merged
merged 1 commit into from
Jun 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ class BodyParserSpec extends PlaySpecification with ScalaCheck {
.validate(dbl)
} must_== run {
constant(x).validate { y =>
inc(y).right.flatMap(dbl)
inc(y).flatMap(dbl)
}
}
}
Expand Down
12 changes: 6 additions & 6 deletions core/play/src/main/scala/play/api/data/Form.scala
Original file line number Diff line number Diff line change
Expand Up @@ -638,7 +638,7 @@ trait Mapping[T] { self =>
}

protected def applyConstraints(t: T): Either[Seq[FormError], T] = {
Right(t).right.flatMap(v => Option(collectErrors(v)).filterNot(_.isEmpty).toLeft(v))
Right(t).flatMap(v => Option(collectErrors(v)).filterNot(_.isEmpty).toLeft(v))
}

protected def collectErrors(t: T): Seq[FormError] = {
Expand Down Expand Up @@ -692,7 +692,7 @@ case class WrappedMapping[A, B](
* @return either a concrete value of type `B` or a set of errors, if the binding failed
*/
def bind(data: Map[String, String]): Either[Seq[FormError], B] = {
wrapped.bind(data).right.map(t => f1(t)).right.flatMap(applyConstraints)
wrapped.bind(data).map(t => f1(t)).flatMap(applyConstraints)
}

/**
Expand Down Expand Up @@ -800,7 +800,7 @@ case class RepeatedMapping[T](
val allErrorsOrItems: Seq[Either[Seq[FormError], T]] =
RepeatedMapping.indexes(key, data).map(i => wrapped.withPrefix(s"$key[$i]").bind(data))
if (allErrorsOrItems.forall(_.isRight)) {
Right(allErrorsOrItems.map(_.right.get).toList).right.flatMap(applyConstraints)
Right(allErrorsOrItems.map(_.right.get).toList).flatMap(applyConstraints)
} else {
Left(allErrorsOrItems.collect { case Left(errors) => errors }.flatten)
}
Expand Down Expand Up @@ -888,7 +888,7 @@ case class OptionalMapping[T](wrapped: Mapping[T], constraints: Seq[Constraint[O
.filter(p => p == key || p.startsWith(s"$key.") || p.startsWith(s"$key["))
.map(k => data.get(k).filterNot(_.isEmpty))
.collectFirst { case Some(v) => v }
.map(_ => wrapped.bind(data).right.map(Some(_)))
.map(_ => wrapped.bind(data).map(Some(_)))
.getOrElse(Right(None))
.right
.flatMap(applyConstraints)
Expand Down Expand Up @@ -979,7 +979,7 @@ case class FieldMapping[T](key: String = "", constraints: Seq[Constraint[T]] = N
* @return either a concrete value of type `T` or a set of errors, if binding failed
*/
def bind(data: Map[String, String]): Either[Seq[FormError], T] = {
binder.bind(key, data).right.flatMap { applyConstraints(_) }
binder.bind(key, data).flatMap { applyConstraints(_) }
}

/**
Expand Down Expand Up @@ -1042,7 +1042,7 @@ trait ObjectMapping {
* @see bind()
*/
def merge(results: Either[Seq[FormError], Any]*): Either[Seq[FormError], Seq[Any]] = {
val all: Seq[Either[Seq[FormError], Seq[Any]]] = results.map(_.right.map(Seq(_)))
val all: Seq[Either[Seq[FormError], Seq[Any]]] = results.map(_.map(Seq(_)))
all.fold(Right(Nil)) { (s, i) =>
merge2(s, i)
}
Expand Down
8 changes: 4 additions & 4 deletions core/play/src/main/scala/play/api/data/format/Format.scala
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ object Formats {
key: String,
data: Map[String, String]
): Either[Seq[FormError], T] = {
stringFormat.bind(key, data).right.flatMap { s =>
stringFormat.bind(key, data).flatMap { s =>
scala.util.control.Exception
.allCatch[T]
.either(parse(s))
Expand Down Expand Up @@ -148,7 +148,7 @@ object Formats {
override val format = Some(("format.real", Nil))

def bind(key: String, data: Map[String, String]) = {
Formats.stringFormat.bind(key, data).right.flatMap { s =>
Formats.stringFormat.bind(key, data).flatMap { s =>
scala.util.control.Exception
.allCatch[BigDecimal]
.either {
Expand Down Expand Up @@ -198,7 +198,7 @@ object Formats {
override val format = Some(("format.boolean", Nil))

def bind(key: String, data: Map[String, String]) = {
Right(data.getOrElse(key, "false")).right.flatMap {
Right(data.getOrElse(key, "false")).flatMap {
case "true" => Right(true)
case "false" => Right(false)
case _ => Left(Seq(FormError(key, "error.boolean", Nil)))
Expand Down Expand Up @@ -249,7 +249,7 @@ object Formats {
override val format = Some(("format.date", Seq(pattern)))

def bind(key: String, data: Map[String, String]) = {
dateFormatter.bind(key, data).right.map(d => java.sql.Date.valueOf(d))
dateFormatter.bind(key, data).map(d => java.sql.Date.valueOf(d))
}

def unbind(key: String, value: java.sql.Date) = dateFormatter.unbind(key, value.toLocalDate)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ package play.api.data
* val signedIntFormat = new Formatter[Int] {
*
* def bind(key: String, data: Map[String, String]) = {
* stringFormat.bind(key, data).right.flatMap { value =>
* stringFormat.bind(key, data).flatMap { value =>
* scala.util.control.Exception.allCatch[Int]
* .either(java.lang.Integer.parseInt(value))
* .left.map(e => Seq(FormError(key, "error.signedNumber", Nil)))
Expand Down
2 changes: 1 addition & 1 deletion core/play/src/main/scala/play/api/i18n/Messages.scala
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ object Messages extends MessagesImplicits {
messageSource: MessageSource,
messageSourceName: String
): Either[PlayException.ExceptionSource, Map[String, String]] = {
new Messages.MessagesParser(messageSource, messageSourceName).parse.right.map { messages =>
new Messages.MessagesParser(messageSource, messageSourceName).parse.map { messages =>
messages.iterator.map(message => message.key -> message.pattern).toMap
}
}
Expand Down
2 changes: 1 addition & 1 deletion core/play/src/main/scala/play/api/mvc/Action.scala
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ trait BodyParser[+A] extends (RequestHeader => Accumulator[ByteString, Either[Re
// prepare execution context as body parser object may cross thread boundary
implicit val pec = ExecCtxUtils.prepare(ec)
new BodyParser[B] {
def apply(request: RequestHeader) = self(request).map(_.right.map(f))(pec)
def apply(request: RequestHeader) = self(request).map(_.map(f))(pec)
override def toString = self.toString
}
}
Expand Down
16 changes: 8 additions & 8 deletions core/play/src/main/scala/play/api/mvc/Binders.scala
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ trait QueryStringBindable[A] {
*/
def transform[B](toB: A => B, toA: B => A) = new QueryStringBindable[B] {
def bind(key: String, params: Map[String, Seq[String]]): Option[Either[String, B]] = {
self.bind(key, params).map(_.right.map(toB))
self.bind(key, params).map(_.map(toB))
}
def unbind(key: String, value: B): String = self.unbind(key, toA(value))
override def javascriptUnbind: String = self.javascriptUnbind
Expand Down Expand Up @@ -183,7 +183,7 @@ trait PathBindable[A] {
* Transform this PathBinding[A] to PathBinding[B]
*/
def transform[B](toB: A => B, toA: B => A) = new PathBindable[B] {
def bind(key: String, value: String): Either[String, B] = self.bind(key, value).right.map(toB)
def bind(key: String, value: String): Either[String, B] = self.bind(key, value).map(toB)
def unbind(key: String, value: B): String = self.unbind(key, toA(value))
}
}
Expand Down Expand Up @@ -467,7 +467,7 @@ object QueryStringBindable {
Some(
implicitly[QueryStringBindable[T]]
.bind(key, params)
.map(_.right.map(Some(_)))
.map(_.map(Some(_)))
.getOrElse(Right(None))
)
}
Expand All @@ -485,7 +485,7 @@ object QueryStringBindable {
Some(
implicitly[QueryStringBindable[T]]
.bind(key, params)
.map(_.right.map(Optional.ofNullable[T]))
.map(_.map(Optional.ofNullable[T]))
.getOrElse(Right(Optional.empty[T]))
)
}
Expand All @@ -503,7 +503,7 @@ object QueryStringBindable {
Some(
bindableInt
.bind(key, params)
.map(_.right.map(OptionalInt.of))
.map(_.map(OptionalInt.of))
.getOrElse(Right(OptionalInt.empty))
)
}
Expand All @@ -519,7 +519,7 @@ object QueryStringBindable {
Some(
bindableLong
.bind(key, params)
.map(_.right.map(OptionalLong.of))
.map(_.map(OptionalLong.of))
.getOrElse(Right(OptionalLong.empty))
)
}
Expand All @@ -536,7 +536,7 @@ object QueryStringBindable {
Some(
bindableDouble
.bind(key, params)
.map(_.right.map(OptionalDouble.of))
.map(_.map(OptionalDouble.of))
.getOrElse(Right(OptionalDouble.empty))
)
}
Expand Down Expand Up @@ -566,7 +566,7 @@ object QueryStringBindable {
*/
implicit def bindableJavaList[T: QueryStringBindable]: QueryStringBindable[java.util.List[T]] =
new QueryStringBindable[java.util.List[T]] {
def bind(key: String, params: Map[String, Seq[String]]) = bindSeq[T](key, params).map(_.right.map(_.asJava))
def bind(key: String, params: Map[String, Seq[String]]) = bindSeq[T](key, params).map(_.map(_.asJava))
def unbind(key: String, values: java.util.List[T]) = unbindSeq(key, values.asScala)
override def javascriptUnbind = javascriptUnbindSeq(implicitly[QueryStringBindable[T]].javascriptUnbind)
}
Expand Down
14 changes: 7 additions & 7 deletions core/play/src/main/scala/play/api/mvc/BodyParsers.scala
Original file line number Diff line number Diff line change
Expand Up @@ -735,7 +735,7 @@ trait PlayBodyParsers extends BodyParserUtils {
val parser = anyContent(maxLength)
val binding = formBinding(maxLength.getOrElse(DefaultMaxTextLength))
parser(requestHeader).map { resultOrBody =>
resultOrBody.right.flatMap { body =>
resultOrBody.flatMap { body =>
form
.bindFromRequest()(Request[AnyContent](requestHeader, body), binding)
.fold(formErrors => Left(onErrors(formErrors)), a => Right(a))
Expand Down Expand Up @@ -924,19 +924,19 @@ trait PlayBodyParsers extends BodyParserUtils {
contentType match {
case Some("text/plain") =>
logger.trace("Parsing AnyContent as text")
text(maxLengthOrDefault)(request).map(_.right.map(s => AnyContentAsText(s)))
text(maxLengthOrDefault)(request).map(_.map(s => AnyContentAsText(s)))

case Some("text/xml") | Some("application/xml") | Some(ApplicationXmlMatcher()) =>
logger.trace("Parsing AnyContent as xml")
xml(maxLengthOrDefault)(request).map(_.right.map(x => AnyContentAsXml(x)))
xml(maxLengthOrDefault)(request).map(_.map(x => AnyContentAsXml(x)))

case Some("text/json") | Some("application/json") =>
logger.trace("Parsing AnyContent as json")
json(maxLengthOrDefault)(request).map(_.right.map(j => AnyContentAsJson(j)))
json(maxLengthOrDefault)(request).map(_.map(j => AnyContentAsJson(j)))

case Some("application/x-www-form-urlencoded") =>
logger.trace("Parsing AnyContent as urlFormEncoded")
formUrlEncoded(maxLengthOrDefault)(request).map(_.right.map(d => AnyContentAsFormUrlEncoded(d)))
formUrlEncoded(maxLengthOrDefault)(request).map(_.map(d => AnyContentAsFormUrlEncoded(d)))

case Some("multipart/form-data") =>
logger.trace("Parsing AnyContent as multipartFormData")
Expand All @@ -945,11 +945,11 @@ trait PlayBodyParsers extends BodyParserUtils {
maxLengthOrDefaultLarge,
DefaultAllowEmptyFileUploads
).apply(request)
.map(_.right.map(m => AnyContentAsMultipartFormData(m)))
.map(_.map(m => AnyContentAsMultipartFormData(m)))

case _ =>
logger.trace("Parsing AnyContent as raw")
raw(DefaultMaxTextLength, maxLengthOrDefaultLarge)(request).map(_.right.map(r => AnyContentAsRaw(r)))
raw(DefaultMaxTextLength, maxLengthOrDefaultLarge)(request).map(_.map(r => AnyContentAsRaw(r)))
}
}

Expand Down
2 changes: 1 addition & 1 deletion core/play/src/main/scala/play/api/mvc/WebSocket.scala
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ object WebSocket {
f: RequestHeader => Future[Either[Result, Flow[In, Out, _]]]
)(implicit transformer: MessageFlowTransformer[In, Out]): WebSocket = {
WebSocket { request =>
f(request).map(_.right.map(transformer.transform))
f(request).map(_.map(transformer.transform))
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class BinderMacros(val c: MacroContext) {
new _root_.play.api.mvc.PathBindable[${t.tpe}] {
private val binder = _root_.scala.Predef.implicitly[_root_.play.api.mvc.PathBindable[${param.typeSignature}]]
override def bind(key: String, value: String): Either[String, ${t.tpe}] = {
binder.bind(key, value).right.map((p: ${param.typeSignature}) => new ${t.tpe}(p))
binder.bind(key, value).map((p: ${param.typeSignature}) => new ${t.tpe}(p))
}

override def unbind(key: String, value: ${t.tpe}): String = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -463,7 +463,7 @@ a1 <- pa1.value.right
def call[T](params: List[Param[_]])(generator: (Seq[_]) => Handler): Handler =
(params
.foldLeft[Either[String, Seq[_]]](Right(Seq[T]())) { (seq, param) =>
seq.right.flatMap(s => param.value.right.map(s :+ _))
seq.flatMap(s => param.value.map(s :+ _))
})
.fold(badRequest, generator)
def fakeValue[A]: A = throw new UnsupportedOperationException("Can't get a fake value")
Expand Down
44 changes: 22 additions & 22 deletions core/play/src/test/scala/play/api/data/format/FormatSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,19 @@ class FormatSpec extends Specification {
val format = Formats.sqlDateFormat("dd-MM-yyyy")
val bindResult = format.bind("date", data)

bindResult.right.map(_.toLocalDate.getDayOfMonth) should beRight(4)
bindResult.right.map(_.toLocalDate.getMonth) should beRight(java.time.Month.JULY)
bindResult.right.map(_.toLocalDate.getYear) should beRight(2017)
bindResult.map(_.toLocalDate.getDayOfMonth) should beRight(4)
bindResult.map(_.toLocalDate.getMonth) should beRight(java.time.Month.JULY)
bindResult.map(_.toLocalDate.getYear) should beRight(2017)
}

"use yyyy-MM-dd as the default format" in {
val data = Map("date" -> "2017-07-04")
val format = Formats.sqlDateFormat
val bindResult = format.bind("date", data)

bindResult.right.map(_.toLocalDate.getDayOfMonth) should beRight(4)
bindResult.right.map(_.toLocalDate.getMonth) should beRight(java.time.Month.JULY)
bindResult.right.map(_.toLocalDate.getYear) should beRight(2017)
bindResult.map(_.toLocalDate.getDayOfMonth) should beRight(4)
bindResult.map(_.toLocalDate.getMonth) should beRight(java.time.Month.JULY)
bindResult.map(_.toLocalDate.getYear) should beRight(2017)
}

"fails when form data is using the wrong pattern" in {
Expand Down Expand Up @@ -72,25 +72,25 @@ class FormatSpec extends Specification {
val format = Formats.sqlTimestampFormat("dd-MM-yyyy HH:mm:ss")
val bindResult = format.bind("date", data)

bindResult.right.map(_.toLocalDateTime.getDayOfMonth) should beRight(4)
bindResult.right.map(_.toLocalDateTime.getMonth) should beRight(java.time.Month.JULY)
bindResult.right.map(_.toLocalDateTime.getYear) should beRight(2017)
bindResult.right.map(_.toLocalDateTime.getHour) should beRight(10)
bindResult.right.map(_.toLocalDateTime.getMinute) should beRight(11)
bindResult.right.map(_.toLocalDateTime.getSecond) should beRight(12)
bindResult.map(_.toLocalDateTime.getDayOfMonth) should beRight(4)
bindResult.map(_.toLocalDateTime.getMonth) should beRight(java.time.Month.JULY)
bindResult.map(_.toLocalDateTime.getYear) should beRight(2017)
bindResult.map(_.toLocalDateTime.getHour) should beRight(10)
bindResult.map(_.toLocalDateTime.getMinute) should beRight(11)
bindResult.map(_.toLocalDateTime.getSecond) should beRight(12)
}

"use yyyy-MM-dd HH:ss:mm as the default format" in {
val data = Map("date" -> "2017-07-04 10:11:12")
val format = Formats.sqlTimestampFormat
val bindResult = format.bind("date", data)

bindResult.right.map(_.toLocalDateTime.getDayOfMonth) should beRight(4)
bindResult.right.map(_.toLocalDateTime.getMonth) should beRight(java.time.Month.JULY)
bindResult.right.map(_.toLocalDateTime.getYear) should beRight(2017)
bindResult.right.map(_.toLocalDateTime.getHour) should beRight(10)
bindResult.right.map(_.toLocalDateTime.getMinute) should beRight(11)
bindResult.right.map(_.toLocalDateTime.getSecond) should beRight(12)
bindResult.map(_.toLocalDateTime.getDayOfMonth) should beRight(4)
bindResult.map(_.toLocalDateTime.getMonth) should beRight(java.time.Month.JULY)
bindResult.map(_.toLocalDateTime.getYear) should beRight(2017)
bindResult.map(_.toLocalDateTime.getHour) should beRight(10)
bindResult.map(_.toLocalDateTime.getMinute) should beRight(11)
bindResult.map(_.toLocalDateTime.getSecond) should beRight(12)
}

"fails when form data is using the wrong pattern" in {
Expand Down Expand Up @@ -125,11 +125,11 @@ class FormatSpec extends Specification {
val data = Map("date" -> "00:00")

val format = Formats.dateFormat("HH:mm", TimeZone.getTimeZone("America/Los_Angeles"))
format.bind("date", data).right.map(_.getTime) should beRight(28800000L)
format.bind("date", data).map(_.getTime) should beRight(28800000L)
format.unbind("date", new Date(28800000L)) should equalTo(data)

val format2 = Formats.dateFormat("HH:mm", TimeZone.getTimeZone("GMT+0000"))
format2.bind("date", data).right.map(_.getTime) should beRight(0L)
format2.bind("date", data).map(_.getTime) should beRight(0L)
format2.unbind("date", new Date(0L)) should equalTo(data)
}
}
Expand All @@ -142,15 +142,15 @@ class FormatSpec extends Specification {

val format = Formats.localDateTimeFormat(pattern)
val bind: Either[Seq[FormError], LocalDateTime] = format.bind("localDateTime", data)
bind.right.map(dt => {
bind.map(dt => {
(dt.getYear, dt.getMonthValue, dt.getDayOfMonth, dt.getHour, dt.getMinute, dt.getSecond)
}) should beRight((2016, 6, 6, 0, 30, 30))
}

"support LocalDateTime formatting with default pattern" in {
val data = Map("localDateTime" -> "2016-10-10 11:11:11")
val format = Formats.localDateTimeFormat
format.bind("localDateTime", data).right.map { dt =>
format.bind("localDateTime", data).map { dt =>
(dt.getYear, dt.getMonthValue, dt.getDayOfMonth, dt.getHour, dt.getMinute, dt.getSecond)
} should beRight((2016, 10, 10, 11, 11, 11))
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ object RoutesCompiler {

val routeFile = task.file.getAbsoluteFile

RoutesFileParser.parse(routeFile).right.map { rules =>
RoutesFileParser.parse(routeFile).map { rules =>
val generated = generator.generate(task, namespace, rules)
generated.map {
case (filename, content) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ object PlayRun {
// Then launch compile
Project.synchronized {
val start = System.currentTimeMillis
Project.runTask(compile in Compile, newState).get._2.toEither.right.map { _ =>
Project.runTask(compile in Compile, newState).get._2.toEither.map { _ =>
val duration = System.currentTimeMillis - start match {
case ms if ms < 1000 => ms + "ms"
case seconds => (seconds / 1000) + "s"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class ScalaWebSockets extends PlaySpecification {
def runWebSocket[In, Out](webSocket: WebSocket, in: Source[Message, _], expectOut: Int)(
implicit mat: Materializer
): Either[Result, List[Message]] = {
await(webSocket(FakeRequest())).right.map { flow =>
await(webSocket(FakeRequest())).map { flow =>
// When running in the real world, if the flow cancels upstream, Play's WebSocket protocol implementation will
// handle this and close the WebSocket, but here, that won't happen, so we redeem the future when we receive
// enough.
Expand Down