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

Scala 2.13: Fix ambiguous overloaded JsonComponent method #25288

Merged
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions admin/app/controllers/admin/CommercialController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ class CommercialController(
val lineItems: Seq[GuLineItem] = Store.getDfpLineItemsReport().lineItems filter (_.orderId.toString == orderId)

Cached(5.minutes) {
JsonComponent(Json.toJson(lineItems))
JsonComponent.fromWritable(lineItems)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two things are happening here:

  1. We're moving from the ambiguous apply() method invocation (ie JsonComponent()) to the unambiguous JsonComponent.fromWritable() invocation - it's still the same method implementation we're calling, it's just the method is now explicitly named.
  2. We're removing a superfluous call to Json.toJson() - that was always superfluous, it's just clearer to see now when we look at the JsonComponent.fromWritable() method that it also does a call to Json.toJson(), so there's no point in doing it twice.

}
}

Expand All @@ -144,7 +144,7 @@ class CommercialController(
}) getOrElse Nil

Cached(5.minutes) {
JsonComponent(Json.toJson(previewUrls))
JsonComponent.fromWritable(previewUrls)
}
}

Expand Down
2 changes: 1 addition & 1 deletion admin/app/football/controllers/PlayerController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ class PlayerController(val wsClient: WSClient, val controllerComponents: Control
),
),
)
Cached(600)(JsonComponent(responseJson))
Cached(600)(JsonComponent.fromWritable(responseJson))
}
}
}
2 changes: 1 addition & 1 deletion applications/app/controllers/GalleryController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ class GalleryController(contentApiClient: ContentApiClient, val controllerCompon
val index = request.getIntParameter("index") getOrElse 1
lookup(path, index, isTrail = false) map {
case Right(other) => RenderOtherStatus(other)
case Left(model) => Cached(model) { JsonComponent(model.gallery.lightbox.javascriptConfig) }
case Left(model) => Cached(model) { JsonComponent.fromWritable(model.gallery.lightbox.javascriptConfig) }
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ class ImageContentController(
case _ => None
},
)
Cached(CacheTime.Default)(JsonComponent(JsArray(lightboxJson)))
Cached(CacheTime.Default)(JsonComponent.fromWritable(JsArray(lightboxJson)))
}
}
}
2 changes: 1 addition & 1 deletion applications/app/controllers/MediaController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class MediaController(contentApiClient: ContentApiClient, val controllerComponen
case Left(model) => MediaInfo(expired = false, shouldHideAdverts = model.media.content.shouldHideAdverts)
case Right(other) => MediaInfo(expired = other.header.status == GONE, shouldHideAdverts = true)
} map { mediaInfo =>
Cached(60)(JsonComponent(withRefreshStatus(Json.toJson(mediaInfo).as[JsObject])))
Cached(60)(JsonComponent.fromWritable(withRefreshStatus(Json.toJson(mediaInfo).as[JsObject])))
}
}

Expand Down
7 changes: 3 additions & 4 deletions commercial/app/controllers/BookOffersController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,12 @@ class BookOffersController(
def getBook: Action[AnyContent] =
Action { implicit request =>
lazy val failedLookupResult: Result = Cached(30.seconds)(JsonNotFound())(request)
lazy val badRequestResponse: Result = Cached(1.day)(JsonComponent(JsNull))(request)
lazy val badRequestResponse: Result = Cached(1.day)(JsonComponent.fromWritable(JsNull))(request)

specificId match {
case Some(isbn) if isValidIsbn(isbn) =>
bookFinder.findByIsbn(isbn) map { book: Book =>
Cached(1.hour)(JsonComponent(Json.toJson(book)))
Cached(1.hour)(JsonComponent.fromWritable(book))
} getOrElse failedLookupResult
case Some(invalidIsbn) =>
log.error(s"Book lookup called with invalid ISBN '$invalidIsbn'. Returning empty response.")
Expand All @@ -49,9 +49,8 @@ class BookOffersController(

def getBooks: Action[AnyContent] =
Action { implicit request =>
val json: JsValue = Json.toJson(booksSample(specificIds, segment))
Cached(60.seconds) {
JsonComponent(json)
JsonComponent.fromWritable(booksSample(specificIds, segment))
}
}
}
4 changes: 2 additions & 2 deletions commercial/app/controllers/ContentApiOffersController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,11 @@ class ContentApiOffersController(
case Nil => Cached(componentNilMaxAge) { jsonFormat.nilResult }
case content if isMulti =>
Cached(1.hour) {
JsonComponent(CapiMultiple.fromContent(content, Edition(request)))
JsonComponent.fromWritable(CapiMultiple.fromContent(content, Edition(request)))
}
case first :: _ =>
Cached(1.hour) {
JsonComponent(CapiSingle.fromContent(first, Edition(request)))
JsonComponent.fromWritable(CapiSingle.fromContent(first, Edition(request)))
}
}

Expand Down
2 changes: 1 addition & 1 deletion commercial/app/controllers/JobsController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class JobsController(jobsAgent: JobsAgent, val controllerComponents: ControllerC
def getJobs: Action[AnyContent] =
Action { implicit request =>
Cached(60.seconds) {
JsonComponent(jobSample(specificIds, segment))
JsonComponent.fromWritable(jobSample(specificIds, segment))
}
}
}
2 changes: 1 addition & 1 deletion commercial/app/controllers/LiveEventsController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class LiveEventsController(liveEventAgent: LiveEventAgent, val controllerCompone
for {
id <- specificId
event <- liveEventAgent.specificLiveEvent(id)
} yield Cached(componentMaxAge) { JsonComponent(event) }
} yield Cached(componentMaxAge) { JsonComponent.fromWritable(event) }
} getOrElse Cached(componentNilMaxAge) { jsonFormat.nilResult }
}
}
2 changes: 1 addition & 1 deletion commercial/app/controllers/Multi.scala
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ class Multi(

if (offerTypes.size == contents.size) {
Cached(componentMaxAge) {
JsonComponent(JsArray((offerTypes zip contents).map {
JsonComponent.fromWritable(JsArray((offerTypes zip contents).map {
case (contentType, content) =>
Json.obj(
"type" -> contentType,
Expand Down
2 changes: 1 addition & 1 deletion commercial/app/controllers/TrafficDriverController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ class TrafficDriverController(
case None => Cached(componentNilMaxAge) { jsonFormat.nilResult }
case Some(content) =>
Cached(60.seconds) {
JsonComponent(TrafficDriver.fromContent(content, Edition(request)))
JsonComponent.fromWritable(TrafficDriver.fromContent(content, Edition(request)))
}
}

Expand Down
3 changes: 1 addition & 2 deletions commercial/app/controllers/TravelOffersController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,8 @@ class TravelOffersController(travelOffersAgent: TravelOffersAgent, val controlle

def getTravel: Action[AnyContent] =
Action { implicit request =>
val json = Json.toJson(travelSample(specificIds, segment))
Cached(60.seconds) {
JsonComponent(json)
JsonComponent.fromWritable(travelSample(specificIds, segment))
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,9 @@ class nonRefreshableLineItemsController(val controllerComponents: ControllerComp
def getIds: Action[AnyContent] =
Action { implicit request =>
val nonRefreshableLineItems: Seq[Long] = DfpAgent.nonRefreshableLineItemIds()
val json = Json.toJson(nonRefreshableLineItems)

Cors(
Cached(15.minutes) {
JsonComponent(json)
JsonComponent.fromWritable(nonRefreshableLineItems)
},
None,
None,
Expand Down
2 changes: 1 addition & 1 deletion common/app/common/JsonComponent.scala
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ object JsonComponent extends Results with implicits.Requests {

def withRefreshStatus(obj: JsObject): JsValue = obj + ("refreshStatus" -> toJson(AutoRefreshSwitch.isSwitchedOn))

def apply[A](value: A)(implicit request: RequestHeader, writes: Writes[A]): RevalidatableResult =
def fromWritable[A](value: A)(implicit request: RequestHeader, writes: Writes[A]): RevalidatableResult =
resultFor(
request,
Json.stringify(Json.toJson(value)),
Expand Down
2 changes: 1 addition & 1 deletion common/test/common/JsonComponentTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ class JsonComponentTest extends AnyFlatSpec with Matchers with WithTestExecution

val result = Future {
implicit val request = FakeRequest("GET", "http://foo.bar.com/data.json")
JsonComponent(JsonComponent.withRefreshStatus(obj("name" -> "foo"))).result
JsonComponent.fromWritable(JsonComponent.withRefreshStatus(obj("name" -> "foo"))).result
}

contentType(result) should be(Some("application/json"))
Expand Down
2 changes: 1 addition & 1 deletion discussion/app/controllers/CommentCountController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class CommentCountController(val discussionApi: DiscussionApiLike, val controlle
val counts = discussionApi.commentCounts(shortUrls)
counts map { counts =>
Cached(300) {
JsonComponent(
JsonComponent.fromWritable(
JsObject(Seq("counts" -> JsArray(counts.map(_.toJson)))),
)
}
Expand Down
12 changes: 7 additions & 5 deletions facia/app/controllers/FaciaController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ trait FaciaController
val onwardItems = OnwardCollection.pressedCollectionToOnwardCollection(collection)

Cached(CacheTime.Facia) {
JsonComponent(onwardItems)
JsonComponent.fromWritable(onwardItems)
}
case None =>
Cached(CacheTime.NotFound)(
Expand Down Expand Up @@ -156,9 +156,11 @@ trait FaciaController

def renderFrontJsonLite(path: String): Action[AnyContent] =
Action.async { implicit request =>
frontJsonFapi.get(path, liteRequestType).map {
case Some(pressedPage) => Cached(CacheTime.Facia)(JsonComponent(FapiFrontJsonLite.get(pressedPage)))
case None => Cached(CacheTime.Facia)(JsonComponent(JsObject(Nil)))
frontJsonFapi.get(path, liteRequestType).map { resp =>
Cached(CacheTime.Facia)(JsonComponent.fromWritable(resp match {
case Some(pressedPage) => FapiFrontJsonLite.get(pressedPage)
case None => JsObject(Nil)
}))
}
}

Expand Down Expand Up @@ -211,7 +213,7 @@ trait FaciaController
RevalidatableResult(Ok(body).as("text/xml; charset=utf-8"), body)
} else if (request.isJson) {
if (request.forceDCR) {
JsonComponent(
JsonComponent.fromWritable(
DotcomFrontsRenderingDataModel(
page = faciaPage,
request = request,
Expand Down
4 changes: 2 additions & 2 deletions onward/app/controllers/CardController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ class CardController(
// To test a story that has no image:
// /cards/opengraph/http%3A%2F%2Fwww.theguardian.com%2Fmedia%2Fgreenslade%2F2013%2Faug%2F22%2Fjournalist-safety-egypt.json

JsonComponent(
JsonComponent.fromWritable(
withRefreshStatus(
Json
.toJson(
Expand Down Expand Up @@ -92,7 +92,7 @@ class CardController(
val firstParagraph = fragment.select("#mw-content-text > p").first
firstParagraph.select(".reference").remove()

JsonComponent(
JsonComponent.fromWritable(
withRefreshStatus(
Json
.toJson(
Expand Down
6 changes: 3 additions & 3 deletions onward/app/controllers/MostPopularController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ class MostPopularController(
OnwardItem.contentCardToOnwardItem(contentCard)
}
val response = OnwardCollectionResponseDCR(tabs, mostCommented, mostShared)
Cached(900)(JsonComponent(response))
Cached(900)(JsonComponent.fromWritable(response))
}

def jsonResponseNx2(mostPopulars: Seq[MostPopularNx2], mostCards: Map[String, Option[ContentCard]])(implicit
Expand All @@ -154,7 +154,7 @@ class MostPopularController(
OnwardItem.contentCardToOnwardItem(contentCard)
}
val response = OnwardCollectionResponseDCR(tabs, mostCommented, mostShared)
Cached(900)(JsonComponent(response))
Cached(900)(JsonComponent.fromWritable(response))
}

def jsonResponse(mostPopular: MostPopular, countryCode: String)(implicit request: RequestHeader): Result = {
Expand All @@ -163,7 +163,7 @@ class MostPopularController(
heading = mostPopular.heading,
trails = mostPopular.trails.map(OnwardItem.pressedContentToOnwardItem).take(10),
)
Cached(900)(JsonComponent(data))
Cached(900)(JsonComponent.fromWritable(data))
}

def renderPopularDay(countryCode: String): Action[AnyContent] =
Expand Down
2 changes: 1 addition & 1 deletion onward/app/controllers/NavigationController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class NavigationController(val controllerComponents: ControllerComponents) exten
Edition.byId(editionId) match {
case Some(edition) =>
val menu = SimpleMenu(edition)
Cached(900)(JsonComponent(menu))
Cached(900)(JsonComponent.fromWritable(menu))
case None =>
Cached(60) {
val json = Json.toJson(ApiError("Invalid edition ID.", 400)).toString()
Expand Down
2 changes: 1 addition & 1 deletion onward/app/controllers/PopularInTag.scala
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ class PopularInTag(
val numberOfCards = if (trails.faciaItems.length == 5 || trails.faciaItems.length == 6) 4 else 8

if (request.forceDCR) {
JsonComponent(
JsonComponent.fromWritable(
OnwardCollectionResponse(
heading = "Related content",
trails = trails.items.map(_.faciaContent).map(OnwardItem.pressedContentToOnwardItem).take(numberOfCards),
Expand Down
2 changes: 1 addition & 1 deletion onward/app/controllers/RelatedController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ class RelatedController(
trails = trails.map(_.faciaContent).map(OnwardItem.pressedContentToOnwardItem).take(10),
)

JsonComponent(data)
JsonComponent.fromWritable(data)
} else if (request.isJson) {
val html = views.html.fragments.containers.facia_cards.container(
onwardContainer(containerTitle, relatedTrails.map(_.faciaContent)),
Expand Down
2 changes: 1 addition & 1 deletion onward/app/controllers/RichLinkController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ class RichLinkController(contentApiClient: ContentApiClient, controllerComponent
pillar = OnwardsUtils.normalisePillar(content.metadata.pillar),
format = content.metadata.format.getOrElse(ContentFormat.defaultContentFormat),
)
Cached(900)(JsonComponent(richLink)(request, RichLink.writes))
Cached(900)(JsonComponent.fromWritable(richLink)(request, RichLink.writes))
case Some(content) => renderContent(richLinkHtml(content), richLinkBodyHtml(content))
case None => NotFound
}
Expand Down
4 changes: 3 additions & 1 deletion onward/app/controllers/SeriesController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ class SeriesController(
Action.async { implicit request =>
if (request.forceDCR) {
lookup(Edition(request), seriesId).map { mseries =>
mseries.map { series => JsonComponent(SeriesStoriesDCR.fromSeries(series)).result }.getOrElse(NotFound)
mseries
.map { series => JsonComponent.fromWritable(SeriesStoriesDCR.fromSeries(series)).result }
.getOrElse(NotFound)
}
} else {
lookup(Edition(request), seriesId) map { series =>
Expand Down
4 changes: 2 additions & 2 deletions onward/app/controllers/StocksController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ class StocksController(stocksData: StocksData, val controllerComponents: Control
Action { implicit request =>
// Decommissioned, see marker: 7dde429f00b1
if (false && StocksWidgetSwitch.isSwitchedOff) {
Cached(1.minute)(JsonComponent(Stocks(Seq.empty)))
Cached(1.minute)(JsonComponent.fromWritable(Stocks(Seq.empty)))
} else {
stocksData.get match {
case None => InternalServerError("Business data not loaded")
case Some(stocks) =>
Cached(1.minute)(JsonComponent(stocks))
Cached(1.minute)(JsonComponent.fromWritable(stocks))
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion onward/app/controllers/StoryPackageController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class StoryPackageController(val contentApiClient: ContentApiClient, val control
def render(path: String): Action[AnyContent] =
Action.async { implicit request =>
getRelatedContent(path).map(items => {
val json = JsonComponent(
val json = JsonComponent.fromWritable(
OnwardCollectionResponse(
heading = "More on this story",
trails = items.map(_.faciaContent).map(OnwardItem.pressedContentToOnwardItem).take(10),
Expand Down
6 changes: 3 additions & 3 deletions onward/app/weather/controllers/LocationsController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class LocationsController(weatherApi: WeatherApi, val controllerComponents: Cont
def findCity(query: String): Action[AnyContent] =
Action.async { implicit request =>
weatherApi.searchForLocations(query) map { locations =>
Cached(7.days)(JsonComponent(CityResponse.fromLocationResponses(locations.toList)))
Cached(7.days)(JsonComponent.fromWritable(CityResponse.fromLocationResponses(locations.toList)))
}
}

Expand Down Expand Up @@ -58,7 +58,7 @@ class LocationsController(weatherApi: WeatherApi, val controllerComponents: Cont
// We do this as AccuWeather writes "New York, New York" if no region is specified, where as we
// just get "New York" from Fastly.
val weatherCityWithoutRegion = weatherCity.copy(city = city)
Cached(1 hour)(JsonComponent(weatherCityWithoutRegion))
Cached(1 hour)(JsonComponent.fromWritable(weatherCityWithoutRegion))
}
}

Expand All @@ -67,7 +67,7 @@ class LocationsController(weatherApi: WeatherApi, val controllerComponents: Cont
cityFromRequestEdition.fold {
Cached(CacheTime.NotFound)(JsonNotFound())
} { city =>
Cached(1 hour)(JsonComponent(city))
Cached(1 hour)(JsonComponent.fromWritable(city))
},
)
}
Expand Down
2 changes: 1 addition & 1 deletion sport/app/football/controllers/MatchController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ class MatchController(
page map { page =>
if (request.forceDCR) {
Cached(30) {
JsonComponent(Json.toJson(NsAnswer.makeFromFootballMatch(theMatch, page.lineUp)))
JsonComponent.fromWritable(NsAnswer.makeFromFootballMatch(theMatch, page.lineUp))
}
} else {
val htmlResponse = () =>
Expand Down
20 changes: 9 additions & 11 deletions sport/app/football/controllers/MoreOnMatchController.scala
Original file line number Diff line number Diff line change
Expand Up @@ -268,17 +268,15 @@ class MoreOnMatchController(
filtered <- related map { _ filter hasExactlyTwoTeams }
} yield {
Cached(if (theMatch.isLive) 10 else 300) {
JsonComponent(
Json.toJson(
NxAnswer.makeFromFootballMatch(
request,
theMatch,
filtered,
lineup,
competition,
theMatch.isResult,
theMatch.isLive,
),
JsonComponent.fromWritable(
NxAnswer.makeFromFootballMatch(
request,
theMatch,
filtered,
lineup,
competition,
theMatch.isResult,
theMatch.isLive,
),
)
}
Expand Down