diff --git a/admin/app/controllers/admin/TroubleshooterController.scala b/admin/app/controllers/admin/TroubleshooterController.scala index 186943395ae5..fdab09616179 100644 --- a/admin/app/controllers/admin/TroubleshooterController.scala +++ b/admin/app/controllers/admin/TroubleshooterController.scala @@ -11,7 +11,7 @@ import play.api.libs.ws.WSClient import play.api.mvc.{Action, AnyContent, BaseController, ControllerComponents} import tools.LoadBalancer -import scala.collection.JavaConverters._ +import scala.jdk.CollectionConverters._ import scala.concurrent.Future import scala.concurrent.duration._ import scala.util.Random diff --git a/admin/app/controllers/admin/commercial/AdsDotTextEditController.scala b/admin/app/controllers/admin/commercial/AdsDotTextEditController.scala index 295dac735fa5..4dc41a9e2d1b 100644 --- a/admin/app/controllers/admin/commercial/AdsDotTextEditController.scala +++ b/admin/app/controllers/admin/commercial/AdsDotTextEditController.scala @@ -42,16 +42,18 @@ class AdsDotTextEditController(val controllerComponents: ControllerComponents)(i postSave: Call, ): Action[AnyContent] = Action { implicit request => - AdsTextSellers.form.bindFromRequest.fold( - formWithErrors => { - NoCache(BadRequest(views.html.commercial.adsDotText(name, saveRoute, formWithErrors))) - }, - adsTextSellers => { - S3.putPrivate(s3DotTextKey, adsTextSellers.sellers, "text/plain") - log.info(s"Wrote new $name file to $s3DotTextKey") - NoCache(Redirect(postSave)) - }, - ) + AdsTextSellers.form + .bindFromRequest() + .fold( + formWithErrors => { + NoCache(BadRequest(views.html.commercial.adsDotText(name, saveRoute, formWithErrors))) + }, + adsTextSellers => { + S3.putPrivate(s3DotTextKey, adsTextSellers.sellers, "text/plain") + log.info(s"Wrote new $name file to $s3DotTextKey") + NoCache(Redirect(postSave)) + }, + ) } def postAdsDotText(): Action[AnyContent] = diff --git a/admin/app/controllers/admin/commercial/TakeoverWithEmptyMPUsController.scala b/admin/app/controllers/admin/commercial/TakeoverWithEmptyMPUsController.scala index 12dd236d11b2..9aeee38eb418 100644 --- a/admin/app/controllers/admin/commercial/TakeoverWithEmptyMPUsController.scala +++ b/admin/app/controllers/admin/commercial/TakeoverWithEmptyMPUsController.scala @@ -22,15 +22,17 @@ class TakeoverWithEmptyMPUsController(val controllerComponents: ControllerCompon def create(): Action[AnyContent] = Action { implicit request => - TakeoverWithEmptyMPUs.form.bindFromRequest.fold( - formWithErrors => { - NoCache(BadRequest(views.html.commercial.takeoverWithEmptyMPUsCreate(formWithErrors))) - }, - takeover => { - TakeoverWithEmptyMPUs.create(takeover) - NoCache(Redirect(routes.TakeoverWithEmptyMPUsController.viewList())) - }, - ) + TakeoverWithEmptyMPUs.form + .bindFromRequest() + .fold( + formWithErrors => { + NoCache(BadRequest(views.html.commercial.takeoverWithEmptyMPUsCreate(formWithErrors))) + }, + takeover => { + TakeoverWithEmptyMPUs.create(takeover) + NoCache(Redirect(routes.TakeoverWithEmptyMPUsController.viewList())) + }, + ) } def remove(url: String): Action[AnyContent] = diff --git a/admin/app/controllers/cache/ImageDecacheController.scala b/admin/app/controllers/cache/ImageDecacheController.scala index a7a010abc48f..efa6742354f4 100644 --- a/admin/app/controllers/cache/ImageDecacheController.scala +++ b/admin/app/controllers/cache/ImageDecacheController.scala @@ -51,7 +51,7 @@ class ImageDecacheController( ImageServices.clearFastly(originUri, wsClient) - val decacheRequest: Future[WSResponse] = wsClient.url(s"$originUrl?cachebust=$cacheBust").get + val decacheRequest: Future[WSResponse] = wsClient.url(s"$originUrl?cachebust=$cacheBust").get() decacheRequest .map(_.status) .map { diff --git a/admin/app/dfp/DataAgent.scala b/admin/app/dfp/DataAgent.scala index 6f7537d8bb4c..4627fbd83137 100644 --- a/admin/app/dfp/DataAgent.scala +++ b/admin/app/dfp/DataAgent.scala @@ -31,10 +31,10 @@ trait DataAgent[K, V] extends GuLogging with implicits.Strings { freshCache case Success(_) => log.error("No fresh data loaded so keeping old data") - cache.get + cache.get() case Failure(e) => log.error("Loading of fresh data has failed.", e) - cache.get + cache.get() } } diff --git a/admin/app/dfp/DataMapper.scala b/admin/app/dfp/DataMapper.scala index 0da6ff8f262f..a1e305b934cb 100644 --- a/admin/app/dfp/DataMapper.scala +++ b/admin/app/dfp/DataMapper.scala @@ -7,9 +7,9 @@ import dfp.ApiHelper.{isPageSkin, optJavaInt, toJodaTime, toSeq} // These mapping functions use libraries that are only available in admin to create common DFP data models. class DataMapper( adUnitService: AdUnitService, - placementService: PlacementService, - customTargetingService: CustomTargetingService, - customFieldService: CustomFieldService, + placementService: dfp.PlacementService, + customTargetingService: dfp.CustomTargetingService, + customFieldService: dfp.CustomFieldService, ) { def toGuAdUnit(dfpAdUnit: AdUnit): GuAdUnit = { @@ -46,7 +46,7 @@ class DataMapper( CustomTarget( customTargetingService.targetingKey(session)(criterion.getKeyId), criterion.getOperator.getValue, - criterion.getValueIds map (valueId => + criterion.getValueIds.toSeq map (valueId => customTargetingService.targetingValue(session)(criterion.getKeyId, valueId), ), ) @@ -54,7 +54,7 @@ class DataMapper( val targets = criteria.getChildren collect { case criterion: CustomCriteria => criterion } map toCustomTarget - CustomTargetSet(criteria.getLogicalOperator.getValue, targets) + CustomTargetSet(criteria.getLogicalOperator.getValue, targets.toIndexedSeq) } criteriaSets.getChildren @@ -105,7 +105,7 @@ class DataMapper( GuCreativePlaceholder(AdSize(size.getWidth, size.getHeight), targeting) } - placeholders sortBy { placeholder => + placeholders.toIndexedSeq sortBy { placeholder => val size = placeholder.size (size.width, size.height) } diff --git a/admin/app/dfp/DfpApi.scala b/admin/app/dfp/DfpApi.scala index a8d5e6f7ccaf..b6a85c73361c 100644 --- a/admin/app/dfp/DfpApi.scala +++ b/admin/app/dfp/DfpApi.scala @@ -31,7 +31,9 @@ class DfpApi(dataMapper: DataMapper, dataValidation: DataValidation) extends GuL // item, potentially making one API call per lineitem. val validatedLineItems = lineItems .groupBy(Function.tupled(dataValidation.isGuLineItemValid)) + .view .mapValues(_.map(_._1)) + .toMap DfpLineItems( validItems = validatedLineItems.getOrElse(true, Nil), diff --git a/admin/app/dfp/SessionWrapper.scala b/admin/app/dfp/SessionWrapper.scala index c723f215895b..535a877fabf6 100644 --- a/admin/app/dfp/SessionWrapper.scala +++ b/admin/app/dfp/SessionWrapper.scala @@ -10,7 +10,7 @@ import common.GuLogging import conf.{AdminConfiguration, Configuration} import dfp.Reader.read import dfp.SessionLogger.{logAroundCreate, logAroundPerform, logAroundRead, logAroundReadSingle} -import collection.JavaConverters._ +import scala.jdk.CollectionConverters._ import scala.util.control.NonFatal @@ -140,7 +140,7 @@ private[dfp] class SessionWrapper(dfpSession: AdManagerSession) { options.setExportFormat(ExportFormat.CSV_DUMP) options.setUseGzipCompression(true) val charSource: CharSource = reportDownloader.getReportAsCharSource(options) - charSource.readLines().asScala + charSource.readLines().asScala.toSeq } object lineItemCreativeAssociations { @@ -164,7 +164,7 @@ private[dfp] class SessionWrapper(dfpSession: AdManagerSession) { def create(licas: Seq[LineItemCreativeAssociation]): Seq[LineItemCreativeAssociation] = { logAroundCreate(typeName) { - licaService.createLineItemCreativeAssociations(licas.toArray) + licaService.createLineItemCreativeAssociations(licas.toArray).toIndexedSeq } } @@ -193,7 +193,7 @@ private[dfp] class SessionWrapper(dfpSession: AdManagerSession) { def create(creatives: Seq[Creative]): Seq[Creative] = { logAroundCreate(typeName) { - creativeService.createCreatives(creatives.toArray) + creativeService.createCreatives(creatives.toArray).toIndexedSeq } } } diff --git a/admin/app/football/controllers/PlayerController.scala b/admin/app/football/controllers/PlayerController.scala index 2dac7fa04932..91dd77c113e0 100644 --- a/admin/app/football/controllers/PlayerController.scala +++ b/admin/app/football/controllers/PlayerController.scala @@ -76,7 +76,7 @@ class PlayerController(val wsClient: WSClient, val controllerComponents: Control client.appearances(playerId, competition.startDate, LocalDate.now(), teamId, competitionId) } yield { val result = createPlayerCard(cardType, playerId, playerProfile, playerStats, playerAppearances) - result.map(renderPlayerCard).getOrElse(renderNotFound) + result.map(renderPlayerCard).getOrElse(renderNotFound()) } } } @@ -94,7 +94,7 @@ class PlayerController(val wsClient: WSClient, val controllerComponents: Control playerAppearances <- client.appearances(playerId, startDate, LocalDate.now(), teamId) } yield { val result = createPlayerCard(cardType, playerId, playerProfile, playerStats, playerAppearances) - result.map(renderPlayerCard).getOrElse(renderNotFound) + result.map(renderPlayerCard).getOrElse(renderNotFound()) } } diff --git a/admin/app/indexes/ContentApiTagsEnumerator.scala b/admin/app/indexes/ContentApiTagsEnumerator.scala index 06b2f9b7c521..dae94c79df10 100644 --- a/admin/app/indexes/ContentApiTagsEnumerator.scala +++ b/admin/app/indexes/ContentApiTagsEnumerator.scala @@ -18,7 +18,7 @@ class ContentApiTagsEnumerator(contentApiClient: ContentApiClient)(implicit exec def enumerateTagType(tagType: String): Future[Seq[Tag]] = { val tagQuery = contentApiClient.tags.tagType(tagType).pageSize(MaxPageSize) contentApiClient.thriftClient.paginateAccum(tagQuery)( - { r: TagsResponse => r.results.filter(isSuitableTag) }, + { r: TagsResponse => r.results.filter(isSuitableTag).toSeq }, { (a: Seq[Tag], b: Seq[Tag]) => a ++ b }, ) } diff --git a/admin/app/jobs/AnalyticsSanityCheckJob.scala b/admin/app/jobs/AnalyticsSanityCheckJob.scala index c6daf022f92c..065e4a465b91 100644 --- a/admin/app/jobs/AnalyticsSanityCheckJob.scala +++ b/admin/app/jobs/AnalyticsSanityCheckJob.scala @@ -9,7 +9,7 @@ import model.diagnostics.CloudWatch import java.time.{LocalDateTime, ZoneId} import services.{CloudWatchStats, OphanApi} -import scala.collection.JavaConverters._ +import scala.jdk.CollectionConverters._ import scala.concurrent.{ExecutionContext, Future} class AnalyticsSanityCheckJob(ophanApi: OphanApi) extends GuLogging { diff --git a/admin/app/jobs/FastlyCloudwatchLoadJob.scala b/admin/app/jobs/FastlyCloudwatchLoadJob.scala index 19633a5fe453..f3c9d8a7e61f 100644 --- a/admin/app/jobs/FastlyCloudwatchLoadJob.scala +++ b/admin/app/jobs/FastlyCloudwatchLoadJob.scala @@ -61,8 +61,8 @@ class FastlyCloudwatchLoadJob(fastlyStatisticService: FastlyStatisticService) ex } val groups = fresh groupBy { _.key } - val timestampsSent = groups mapValues { _ map { _.timestamp } } - timestampsSent mapValues { _.max } foreach { + val timestampsSent = groups.view mapValues { _ map { _.timestamp } } + timestampsSent.view mapValues { _.max } foreach { case (key, value) => latestTimestampsSent.update(key, value) } diff --git a/admin/app/model/AdminLifecycle.scala b/admin/app/model/AdminLifecycle.scala index f188faa7fa82..877f92d03359 100644 --- a/admin/app/model/AdminLifecycle.scala +++ b/admin/app/model/AdminLifecycle.scala @@ -59,7 +59,7 @@ class AdminLifecycle( } jobs.scheduleEvery("R2PagePressJob", r2PagePressRateInSeconds.seconds) { - r2PagePressJob.run + r2PagePressJob.run() } //every 2, 17, 32, 47 minutes past the hour, on the 12th second past the minute (e.g 13:02:12, 13:17:12) diff --git a/admin/app/model/abtests/AbTestJob.scala b/admin/app/model/abtests/AbTestJob.scala index f9fb864ee283..ba49e7aac7fd 100644 --- a/admin/app/model/abtests/AbTestJob.scala +++ b/admin/app/model/abtests/AbTestJob.scala @@ -4,7 +4,7 @@ import common.GuLogging import tools.CloudWatch import views.support.CamelCase -import scala.collection.JavaConverters._ +import scala.jdk.CollectionConverters._ import scala.concurrent.ExecutionContext object AbTestJob extends GuLogging { @@ -27,7 +27,7 @@ object AbTestJob extends GuLogging { val testVariants = switches.foldLeft(Map.empty[String, Seq[String]])((acc, switch) => { if (tests.isDefinedAt(switch)) { // Update map with a list of variants for the ab-test switch. - acc.updated(switch, tests(switch).map(_._2)) + acc.updated(switch, tests(switch).map(_._2).toSeq) } else { acc } diff --git a/admin/app/services/EmailService.scala b/admin/app/services/EmailService.scala index 4e686b371bd9..dab31c0f8c99 100644 --- a/admin/app/services/EmailService.scala +++ b/admin/app/services/EmailService.scala @@ -8,7 +8,7 @@ import com.amazonaws.services.simpleemail.model.{Destination => EmailDestination import common.{AkkaAsync, GuLogging} import conf.Configuration.aws.mandatoryCredentials -import scala.collection.JavaConverters._ +import scala.jdk.CollectionConverters._ import scala.concurrent.duration._ import scala.concurrent.{ExecutionContext, Future, Promise} import scala.util.control.NonFatal diff --git a/admin/app/tools/AssetMetrics.scala b/admin/app/tools/AssetMetrics.scala index fd735a0ae7b8..4f556bc00ff8 100644 --- a/admin/app/tools/AssetMetrics.scala +++ b/admin/app/tools/AssetMetrics.scala @@ -6,7 +6,7 @@ import common.{Box, GuLogging} import org.joda.time.DateTime import tools.CloudWatch._ -import scala.collection.JavaConverters._ +import scala.jdk.CollectionConverters._ import scala.concurrent.{ExecutionContext, Future} import scala.math.BigDecimal import scala.util.control.NonFatal @@ -91,7 +91,7 @@ object AssetMetricsCache extends GuLogging { .sizeMetrics() .map { metrics => log.info("Successfully refreshed Asset Metrics data") - cache.send(cache.get + (ReportTypes.sizeOfFiles -> metrics)) + cache.send(cache.get() + (ReportTypes.sizeOfFiles -> metrics)) } .recover { case NonFatal(e) => diff --git a/admin/app/tools/CloudWatch.scala b/admin/app/tools/CloudWatch.scala index 5310d4b3f34d..b50b5c04f15b 100644 --- a/admin/app/tools/CloudWatch.scala +++ b/admin/app/tools/CloudWatch.scala @@ -12,7 +12,7 @@ import conf.Configuration import conf.Configuration._ import org.joda.time.DateTime -import scala.collection.JavaConverters._ +import scala.jdk.CollectionConverters._ import scala.concurrent.{ExecutionContext, Future} case class MaximumMetric(metric: GetMetricStatisticsResult) { diff --git a/admin/app/tools/LoadBalancer.scala b/admin/app/tools/LoadBalancer.scala index fac6aa75fde5..fe380fec634d 100644 --- a/admin/app/tools/LoadBalancer.scala +++ b/admin/app/tools/LoadBalancer.scala @@ -3,7 +3,7 @@ package tools import common.{Box, GuLogging} import com.amazonaws.services.elasticloadbalancing.AmazonElasticLoadBalancingClient -import scala.collection.JavaConverters._ +import scala.jdk.CollectionConverters._ case class LoadBalancer( id: String, diff --git a/admin/app/tools/charts/charts.scala b/admin/app/tools/charts/charts.scala index 0f5210725d15..21ed89997be6 100644 --- a/admin/app/tools/charts/charts.scala +++ b/admin/app/tools/charts/charts.scala @@ -7,7 +7,7 @@ import common.editions.Uk import org.joda.time.{DateTime, DateTimeZone} import play.api.libs.json._ -import scala.collection.JavaConverters._ +import scala.jdk.CollectionConverters._ import scala.collection.mutable.{Map => MutableMap} case class ChartRow[K](rowKey: K, values: Seq[Double]) @@ -47,7 +47,7 @@ class ChartTable(private val labels: Seq[String]) { ChartRow(dateFormat(new DateTime(row._1)), row._2) } - chartRows.seq + chartRows } } @@ -118,9 +118,11 @@ class AwsLineChart( val dataColumns = labels.tail val table = new ChartTable(dataColumns) - (dataColumns, charts.toList).zipped.map((column, chart) => { - table.addColumn(column, ChartColumn(chart.getDatapoints.asScala)) - }) + dataColumns + .lazyZip(charts.toList) + .map((column, chart) => { + table.addColumn(column, ChartColumn(chart.getDatapoints.asScala.toSeq)) + }) table.asChartRow(toLabel, toValue) } @@ -158,8 +160,9 @@ class ABDataChart(name: String, ablabels: Seq[String], format: ChartFormat, char private val dataColumns: Seq[(String, ChartColumn)] = { // Do not consider any metrics that have less than three data points. - (ablabels.tail, charts.toList).zipped - .map((column, chart) => (column, ChartColumn(chart.getDatapoints.asScala))) + ablabels.tail + .lazyZip(charts.toList) + .map((column, chart) => (column, ChartColumn(chart.getDatapoints.asScala.toSeq))) .filter { case (label, column) => column.values.length > 3 } } diff --git a/admin/app/views/commercial/adsDotText.scala.html b/admin/app/views/commercial/adsDotText.scala.html index 5c21ff46edbb..ea5b76763768 100644 --- a/admin/app/views/commercial/adsDotText.scala.html +++ b/admin/app/views/commercial/adsDotText.scala.html @@ -17,7 +17,7 @@

@{name} editor

} } - @textarea(sellersForm("sellers"), '_label -> "Authorised sellers:", 'rows -> 30, 'cols -> 100, '_help -> "") + @textarea(sellersForm("sellers"), Symbol("_label") -> "Authorised sellers:", Symbol("rows") -> 30, Symbol("cols") -> 100, Symbol("_help") -> "") } diff --git a/admin/app/views/commercial/takeoverWithEmptyMPUsCreate.scala.html b/admin/app/views/commercial/takeoverWithEmptyMPUsCreate.scala.html index 6d407de3d2c5..03b8143c86fa 100644 --- a/admin/app/views/commercial/takeoverWithEmptyMPUsCreate.scala.html +++ b/admin/app/views/commercial/takeoverWithEmptyMPUsCreate.scala.html @@ -19,17 +19,17 @@

New Takeover with Empty MPUs

} } - @inputText(takeoverForm("url"), '_label -> "Paste URL here:", 'size -> 100, '_help -> "") + @inputText(takeoverForm("url"), Symbol("_label")-> "Paste URL here:", Symbol("size") -> 100, Symbol("_help") -> "") @select( takeoverForm("editions"), options = for(e <- Edition.all) yield { e.id -> e.displayName }, - 'multiple -> true, - '_label -> "Editions this applies to (one or multiple):" + Symbol("multiple") -> true, + Symbol("_label") -> "Editions this applies to (one or multiple):" ) - @input(takeoverForm("startTime"), '_label -> "Takeover starts (UTC):", '_help -> "") { (id, name, value, args) => + @input(takeoverForm("startTime"), Symbol("_label") -> "Takeover starts (UTC):", Symbol("_help") -> "") { (id, name, value, args) => } - @input(takeoverForm("endTime"), '_label -> "Takeover ends (UTC):", '_help -> "") { (id, name, value, args) => + @input(takeoverForm("endTime"), Symbol("_label") -> "Takeover ends (UTC):", Symbol("_help") -> "") { (id, name, value, args) => } diff --git a/admin/app/views/fragments/formattedChart.scala.html b/admin/app/views/fragments/formattedChart.scala.html index 7aa70acc4a8a..ff539ead9bce 100644 --- a/admin/app/views/fragments/formattedChart.scala.html +++ b/admin/app/views/fragments/formattedChart.scala.html @@ -5,7 +5,7 @@ diff --git a/common/app/views/fragments/atoms/structureddata/restaurant/restaurantReview.scala.html b/common/app/views/fragments/atoms/structureddata/restaurant/restaurantReview.scala.html index b30c655e137b..8b05d180511f 100644 --- a/common/app/views/fragments/atoms/structureddata/restaurant/restaurantReview.scala.html +++ b/common/app/views/fragments/atoms/structureddata/restaurant/restaurantReview.scala.html @@ -27,7 +27,7 @@ "priceRange": "ÂŁÂŁÂŁ", @for(address <- entity.address) { @fragments.atoms.structureddata.restaurant.address(address) } @for(geoLocation <- entity.geolocation) { "geo" : @fragments.atoms.structureddata.restaurant.geo(geoLocation), } - @review.data.images.flatMap(ReviewAtom.getLargestImageUrl).map { img => "image": "@img" } + @review.data.images.map(_.toSeq).flatMap(ReviewAtom.getLargestImageUrl).map { img => "image": "@img" } }, "reviewRating": { "@@type": "Rating", diff --git a/common/app/views/fragments/audio/containers/flagshipContainer.scala.html b/common/app/views/fragments/audio/containers/flagshipContainer.scala.html index cb1c418362b7..f0998bbe51d6 100644 --- a/common/app/views/fragments/audio/containers/flagshipContainer.scala.html +++ b/common/app/views/fragments/audio/containers/flagshipContainer.scala.html @@ -43,8 +43,8 @@
- @fragments.social(item.sharelinks.pageShares, "top", iconModifier = iconModifier) + @fragments.social(item.sharelinks.pageShares, "top", iconModifier = iconModifier())
diff --git a/common/app/views/support/HtmlCleaner.scala b/common/app/views/support/HtmlCleaner.scala index 3832f443f795..1198dd5f4064 100644 --- a/common/app/views/support/HtmlCleaner.scala +++ b/common/app/views/support/HtmlCleaner.scala @@ -23,7 +23,7 @@ import services.SkimLinksCache import views.html.fragments.affiliateLinksDisclaimer import views.support.Commercial.isAdFree -import scala.collection.JavaConverters._ +import scala.jdk.CollectionConverters._ import scala.collection.mutable import scala.util.Try diff --git a/common/app/views/support/JavaScriptPage.scala b/common/app/views/support/JavaScriptPage.scala index fcf56959e074..547d71408530 100644 --- a/common/app/views/support/JavaScriptPage.scala +++ b/common/app/views/support/JavaScriptPage.scala @@ -26,7 +26,7 @@ object JavaScriptPage { CamelCase.fromHyphenated(key.split('.').lastOption.getOrElse("")) } - val config = (Configuration.javascript.config ++ pageData).mapValues(JsString.apply) + val config = (Configuration.javascript.config ++ pageData).view.mapValues(JsString.apply).toMap val sponsorshipType = for { commercial <- page.metadata.commercial branding <- commercial.branding(edition) @@ -100,5 +100,5 @@ object JavaScriptPage { ("brazeApiKey", JsString(Configuration.braze.apiKey)), ("ipsosTag", JsString(ipsos)), ) ++ commercialBundleUrl - } + }.toMap } diff --git a/common/app/views/support/MinuteCleaner.scala b/common/app/views/support/MinuteCleaner.scala index 4b7ee9219928..96cdd50a0aec 100644 --- a/common/app/views/support/MinuteCleaner.scala +++ b/common/app/views/support/MinuteCleaner.scala @@ -1,7 +1,7 @@ package views.support import org.jsoup.nodes.{Document, Element} -import scala.collection.JavaConverters._ +import scala.jdk.CollectionConverters._ case class TimestampCleaner(article: model.Article) extends HtmlCleaner { override def clean(document: Document): Document = { diff --git a/common/app/views/support/WitnessCleaner.scala b/common/app/views/support/WitnessCleaner.scala index 13eb38bb36e2..fc2c3922469a 100644 --- a/common/app/views/support/WitnessCleaner.scala +++ b/common/app/views/support/WitnessCleaner.scala @@ -1,7 +1,7 @@ package views.support import org.jsoup.nodes.{Element, Document} -import scala.collection.JavaConverters._ +import scala.jdk.CollectionConverters._ object WitnessCleaner extends HtmlCleaner { override def clean(document: Document): Document = { diff --git a/common/app/views/support/cleaner/CmpParamCleaner.scala b/common/app/views/support/cleaner/CmpParamCleaner.scala index d8780745f8cf..2fab1fde7aa0 100644 --- a/common/app/views/support/cleaner/CmpParamCleaner.scala +++ b/common/app/views/support/cleaner/CmpParamCleaner.scala @@ -3,7 +3,7 @@ package views.support.cleaner import org.jsoup.nodes.{Document, Element} import views.support.HtmlCleaner -import scala.collection.JavaConverters._ +import scala.jdk.CollectionConverters._ object CmpParamCleaner extends HtmlCleaner { override def clean(document: Document): Document = { diff --git a/common/app/views/support/cleaner/VideoEmbedCleaner.scala b/common/app/views/support/cleaner/VideoEmbedCleaner.scala index 979abc790c53..3da00a6b9467 100644 --- a/common/app/views/support/cleaner/VideoEmbedCleaner.scala +++ b/common/app/views/support/cleaner/VideoEmbedCleaner.scala @@ -6,7 +6,7 @@ import model.{Article, DotcomContentType, ShareLinks, VideoElement} import org.jsoup.nodes.{Document, Element} import views.support.{HtmlCleaner, Item640} -import scala.collection.JavaConverters._ +import scala.jdk.CollectionConverters._ /* * maxEmbedHeight: 812px - full height on an iPhone X diff --git a/common/app/views/support/package.scala b/common/app/views/support/package.scala index 27caae7ee829..e4233f485bb2 100644 --- a/common/app/views/support/package.scala +++ b/common/app/views/support/package.scala @@ -18,7 +18,7 @@ import play.api.mvc.{RequestHeader, Result} import play.twirl.api.Html import layout.slices.ContainerDefinition -import scala.collection.JavaConverters._ +import scala.jdk.CollectionConverters._ /** * Encapsulates previous and next urls diff --git a/common/test/common/ExperimentsTest.scala b/common/test/common/ExperimentsTest.scala index 06ababdc40af..46a7e92d7dae 100644 --- a/common/test/common/ExperimentsTest.scala +++ b/common/test/common/ExperimentsTest.scala @@ -11,7 +11,7 @@ import play.api.mvc.RequestHeader class ExperimentsTest extends AnyFlatSpec with Matchers { - conf.switches.Switches.ServerSideExperiments.switchOn + conf.switches.Switches.ServerSideExperiments.switchOn() "Experiments" should "not share participation group" in { ActiveExperiments.allExperiments.size should be(ActiveExperiments.allExperiments.map(_.participationGroup).size) @@ -176,9 +176,9 @@ class ExperimentsTest extends AnyFlatSpec with Matchers { trait EnabledExperiments { def apply[T](block: => T): T = { - TestCases.experiments.foreach(_.switch.switchOn) + TestCases.experiments.foreach(_.switch.switchOn()) val result = block - TestCases.experiments.foreach(_.switch.switchOff) + TestCases.experiments.foreach(_.switch.switchOff()) result } } diff --git a/common/test/common/ModelOrResultTest.scala b/common/test/common/ModelOrResultTest.scala index 805df639ed5c..d86ed43102b3 100644 --- a/common/test/common/ModelOrResultTest.scala +++ b/common/test/common/ModelOrResultTest.scala @@ -94,7 +94,7 @@ class ModelOrResultTest extends AnyFlatSpec with Matchers with WithTestExecution ModelOrResult( item = None, response = stubResponse.copy(content = Some(testArticle)), - ).right.get + ).toOption.get } status(notFound) should be(200) @@ -106,7 +106,7 @@ class ModelOrResultTest extends AnyFlatSpec with Matchers with WithTestExecution ModelOrResult( item = None, response = stubResponse.copy(content = Some(testVideo)), - ).right.get + ).toOption.get } status(notFound) should be(200) @@ -118,7 +118,7 @@ class ModelOrResultTest extends AnyFlatSpec with Matchers with WithTestExecution ModelOrResult( item = None, response = stubResponse.copy(content = Some(testGallery)), - ).right.get + ).toOption.get } status(notFound) should be(200) @@ -130,7 +130,7 @@ class ModelOrResultTest extends AnyFlatSpec with Matchers with WithTestExecution ModelOrResult( item = None, response = stubResponse.copy(content = Some(testAudio)), - ).right.get + ).toOption.get } status(notFound) should be(200) @@ -142,7 +142,7 @@ class ModelOrResultTest extends AnyFlatSpec with Matchers with WithTestExecution ModelOrResult( item = None, response = stubResponse.copy(content = Some(testContent)), - ).right.get + ).toOption.get } status(notFound) should be(404) @@ -153,7 +153,7 @@ class ModelOrResultTest extends AnyFlatSpec with Matchers with WithTestExecution ModelOrResult( item = None, response = stubResponse.copy(tag = Some(articleTag)), - ).right.get + ).toOption.get } status(notFound) should be(200) @@ -167,7 +167,7 @@ class ModelOrResultTest extends AnyFlatSpec with Matchers with WithTestExecution ModelOrResult( item = None, response = stubResponse.copy(section = Some(testSection)), - ).right.get + ).toOption.get } status(notFound) should be(200) diff --git a/common/test/common/TagLinkerTest.scala b/common/test/common/TagLinkerTest.scala index 711564795d3c..9c851f60a1c5 100644 --- a/common/test/common/TagLinkerTest.scala +++ b/common/test/common/TagLinkerTest.scala @@ -16,7 +16,7 @@ import org.scalatestplus.play.guice.GuiceOneAppPerSuite import play.api.test.FakeRequest import views.support.TagLinker -import scala.collection.JavaConverters._ +import scala.jdk.CollectionConverters._ class TagLinkerTest extends AnyFlatSpec with Matchers with GuiceOneAppPerSuite { diff --git a/common/test/common/TrailsToShowcaseTest.scala b/common/test/common/TrailsToShowcaseTest.scala index 1f04af327646..d1f2005bd391 100644 --- a/common/test/common/TrailsToShowcaseTest.scala +++ b/common/test/common/TrailsToShowcaseTest.scala @@ -14,7 +14,7 @@ import org.scalatest.matchers.should.Matchers import play.api.test.FakeRequest import java.time.ZoneOffset -import scala.collection.JavaConverters._ +import scala.jdk.CollectionConverters._ import scala.xml.{Node, XML} class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { @@ -439,7 +439,7 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { val outcome = TrailsToShowcase.asSingleStoryPanel(withSupportingContent) outcome.left.toOption.isEmpty should be(true) - val singleStoryRelatedArticlesPanel = outcome.right.get + val singleStoryRelatedArticlesPanel = outcome.toOption.get singleStoryRelatedArticlesPanel.articleGroup.nonEmpty shouldBe (true) singleStoryRelatedArticlesPanel.articleGroup.get.role shouldBe ("RELATED_CONTENT") singleStoryRelatedArticlesPanel.articleGroup.get.articles.size shouldBe (2) @@ -482,9 +482,9 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { val outcome = TrailsToShowcase.asSingleStoryPanel(withInvalidSupportingContent) - outcome.left.toOption.nonEmpty should be(true) - outcome.left.get.contains(s"The headline '$longerThan54' is longer than 54 characters") should be(true) - outcome.left.get.contains(s"Kicker text '$longerThan54' is longer than 42 characters") should be(true) + outcome.swap.toOption.nonEmpty should be(true) + outcome.swap.contains(s"The headline '$longerThan54' is longer than 54 characters") should be(true) + outcome.swap.contains(s"Kicker text '$longerThan54' is longer than 42 characters") should be(true) } "TrailToShowcase" should "reject related articles panels with incorrect number of articles" in { @@ -506,8 +506,8 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { val outcome = TrailsToShowcase.asSingleStoryPanel(withoutEnoughSupportingContent) - outcome.left.toOption.nonEmpty should be(true) - outcome.left.get.contains("Could not find 2 valid related article trails") should be(true) + outcome.swap.toOption.nonEmpty should be(true) + outcome.swap.contains("Could not find 2 valid related article trails") should be(true) } "TrailToShowcase" can "encode single story panel bullet lists from trailtext lines" in { @@ -575,8 +575,8 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { val outcome = TrailsToShowcase.asSingleStoryPanel(bulletedContent) - outcome.right.toOption should be(None) - outcome.left.get.contains("Trail text is not formatted as a bullet list") shouldBe (true) + outcome.toOption should be(None) + outcome.swap.toOption.get.contains("Trail text is not formatted as a bullet list") shouldBe (true) } "TrailToShowcase" should "reject bullet lists with less than 2 items" in { @@ -595,8 +595,8 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { val outcome = TrailsToShowcase.asSingleStoryPanel(bulletedContent) - outcome.right.toOption should be(None) - outcome.left.get.contains("Need at least 2 valid bullet list items") shouldBe (true) + outcome.toOption should be(None) + outcome.swap.contains("Need at least 2 valid bullet list items") shouldBe (true) } "TrailToShowcase" should "trim single story bullets to 3 at most" in { @@ -684,7 +684,7 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { "rundown-container-id", Some(collectionLastUpdated), ) - .right + .toOption .get recentlyEditedRundownPanelMadeWithUnchangingContent.updated should be(collectionLastUpdated) @@ -708,7 +708,7 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { val rundownPanel = TrailsToShowcase .asRundownPanel(Seq(trail, anotherTrail, anotherTrail), "rundown-container-id") - .right + .toOption .get rundownPanel.`type` should be("RUNDOWN") @@ -752,7 +752,7 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { ) val rundownPanel = TrailsToShowcase .asRundownPanel(Seq(trail, anotherTrail, anotherTrail), "rundown-container-id") - .right + .toOption .get val entry = TrailsToShowcase.asSyndEntry(rundownPanel) @@ -801,9 +801,9 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { val outcome = TrailsToShowcase .asRundownPanel(Seq(firstTrail, anotherTrail, anotherTrail), "rundown-container-id") - outcome.right.get.panelTitle should be("My rundown panel title") - outcome.right.get.articleGroup.articles.head.title should be("My headline") - outcome.right.get.articleGroup.articles.head.overline should be(Some("A Kicker")) + outcome.toOption.get.panelTitle should be("My rundown panel title") + outcome.toOption.get.articleGroup.articles.head.title should be("My headline") + outcome.toOption.get.articleGroup.articles.head.overline should be(Some("A Kicker")) } "TrailToShowcase" should "infer the mandatory Rundown panel title from a pipe delimit in the first trail's headline" in { @@ -825,8 +825,8 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { val outcome = TrailsToShowcase .asRundownPanel(Seq(firstTrail, anotherTrail, anotherTrail), "rundown-container-id") - outcome.right.get.panelTitle should be("My rundown panel title") - outcome.right.get.articleGroup.articles.head.title should be("My headline") + outcome.toOption.get.panelTitle should be("My rundown panel title") + outcome.toOption.get.articleGroup.articles.head.title should be("My headline") } "TrailToShowcase" should "allow panel titles with pipes in them" in { @@ -849,8 +849,8 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { val outcome = TrailsToShowcase .asRundownPanel(Seq(firstTrail, anotherTrail, anotherTrail), "rundown-container-id") - outcome.right.get.panelTitle should be("Evening briefing | Tuesday 28 September") - outcome.right.get.articleGroup.articles.head.title should be( + outcome.toOption.get.panelTitle should be("Evening briefing | Tuesday 28 September") + outcome.toOption.get.articleGroup.articles.head.title should be( "PM meets with Liberal MPs worried Coalition will appease Nats", ) } @@ -874,8 +874,8 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { val outcome = TrailsToShowcase .asRundownPanel(Seq(firstTrail, anotherTrail, anotherTrail), "rundown-container-id") - outcome.right.toOption should be(None) - outcome.left.get.contains( + outcome.toOption should be(None) + outcome.swap.contains( "Could not find a panel title in the first trail headline 'My headline but I've forgotten the rundown panel title'", ) should be(true) } @@ -891,7 +891,7 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { val rundownPanel = TrailsToShowcase .asRundownPanel(Seq(withByline, withByline, withByline), "rundown-container-id") - .right + .toOption .get val firstItemInArticleGroup = rundownPanel.articleGroup.articles.head @@ -909,7 +909,7 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { val rundownPanel = TrailsToShowcase .asRundownPanel(Seq(withKicker, withKicker, withKicker), "rundown-container-id") - .right + .toOption .get val firstItemInArticleGroup = rundownPanel.articleGroup.articles.head @@ -928,7 +928,7 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { val rundownPanel = TrailsToShowcase .asRundownPanel(Seq(withAuthorAndKicker, withAuthorAndKicker, withAuthorAndKicker), "rundown-container-id") - .right + .toOption .get val firstItemInArticleGroup = rundownPanel.articleGroup.articles.head @@ -955,7 +955,7 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { val rundownPanel = TrailsToShowcase .asRundownPanel(Seq(withAuthorAndKicker, withAuthorAndKicker, withMissingKicker), "rundown-container-id") - .right + .toOption .get rundownPanel.articleGroup.articles.forall(_.author.nonEmpty) should be(true) @@ -981,8 +981,8 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { val rundownPanel = TrailsToShowcase .asRundownPanel(Seq(withKicker, withKicker, withAuthor), "rundown-container-id") - rundownPanel.right.toOption should be(None) - rundownPanel.left.get should be(Seq("Rundown trails need to have all Kickers or all Bylines")) + rundownPanel.toOption should be(None) + rundownPanel.swap should be(Seq("Rundown trails need to have all Kickers or all Bylines")) } "TrailToShowcase" can "rundown panels articles should prefer replaced images over content trail image" in { @@ -997,7 +997,7 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { val rundownPanel = TrailsToShowcase .asRundownPanel(Seq(withReplacedImage, withReplacedImage, withReplacedImage), "rundown-id") - .right + .toOption .get rundownPanel.articleGroup.articles.head.imageUrl shouldBe Some("http://localhost/replaced-image.jpg") @@ -1013,7 +1013,7 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { val rundownPanel = TrailsToShowcase .asRundownPanel(Seq(content, content, content), "rundown-container-id") - .right + .toOption .get rundownPanel.articleGroup.articles.head.updated shouldBe (wayBackWhen) @@ -1030,8 +1030,8 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { val outcome = TrailsToShowcase.asSingleStoryPanel(content) - outcome.right.get.title should be("US Open winner could become Britain’s first billion-dollar sport star") - outcome.right.get.panelTitle should be(Some("Meteoric rise")) + outcome.toOption.get.title should be("US Open winner could become Britain’s first billion-dollar sport star") + outcome.toOption.get.panelTitle should be(Some("Meteoric rise")) } "TrailToShowcase validation" should "reject single panel g:overlines longer than 30 characters" in { @@ -1048,8 +1048,8 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { val outcome = TrailsToShowcase.asSingleStoryPanel(content) - outcome.right.toOption should be(None) - outcome.left.get.contains(s"Kicker text '${longerThan30}' is longer than 30 characters") shouldBe (true) + outcome.toOption should be(None) + outcome.swap.contains(s"Kicker text '${longerThan30}' is longer than 30 characters") shouldBe (true) } "TrailToShowcase validation" should "reject single panels with titles longer than 86 characters" in { @@ -1066,8 +1066,8 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { val outcome = TrailsToShowcase.asSingleStoryPanel(withLongTitle) - outcome.right.toOption should be(None) - outcome.left.get.contains(s"The headline '$longerThan86' is longer than 86 characters") shouldBe (true) + outcome.toOption should be(None) + outcome.swap.contains(s"The headline '$longerThan86' is longer than 86 characters") shouldBe (true) } "TrailToShowcase validation" should "omit single panel author fields longer than 42 characters" in { @@ -1084,7 +1084,7 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { val outcome = TrailsToShowcase.asSingleStoryPanel(withLongByline) - outcome.right.get.author should be(None) + outcome.toOption.get.author should be(None) //outcome.left.get.contains("Author was too long and was dropped") shouldBe(true) } @@ -1096,8 +1096,8 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { val outcome = TrailsToShowcase.asSingleStoryPanel(withNoImage) - outcome.right.toOption should be(None) - outcome.left.get.contains("No image available") shouldBe (true) + outcome.toOption should be(None) + outcome.swap.contains("No image available") shouldBe (true) } "TrailToShowcase validation" should "reject single panels with images smaller than 640x320" in { @@ -1109,8 +1109,8 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { val outcome = TrailsToShowcase.asSingleStoryPanel(withTooSmallImage) - outcome.right.toOption should be(None) - outcome.left.get.contains("Could not find image bigger than the minimum required size: 640x320") shouldBe (true) + outcome.toOption should be(None) + outcome.swap.contains("Could not find image bigger than the minimum required size: 640x320") shouldBe (true) } "TrailToShowcase validation" should "reject rundown panels with less than 3 valid articles" in { @@ -1133,8 +1133,8 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { val rundownPanel = TrailsToShowcase.asRundownPanel(Seq(valid, valid, notValid), "rundown-container-id") - rundownPanel.right.toOption should be(None) - rundownPanel.left.get.head should be("Could not find 3 valid rundown trails") + rundownPanel.toOption should be(None) + rundownPanel.swap.toOption.get.head should be("Could not find 3 valid rundown trails") } "TrailToShowcase validation" should "trim rundown panels to 3 articles if too many are supplied" in { @@ -1148,7 +1148,7 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { val rundownPanel = TrailsToShowcase .asRundownPanel(Seq(content, content, content, content), "rundown-container-id") - .right + .toOption .get rundownPanel.articleGroup.articles.size should be(3) @@ -1170,7 +1170,7 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { val rundownPanel = TrailsToShowcase.asRundownPanel(Seq(trail, anotherTrail), "rundown-container-id") rundownPanel.toOption shouldBe (None) - rundownPanel.left.get.contains(s"The panel title '$longerThan74' is longer than 74 characters") shouldBe (true) + rundownPanel.swap.contains(s"The panel title '$longerThan74' is longer than 74 characters") shouldBe (true) } "TrailToShowcase validation" should "reject rundown panel article kickers longer than 30 characters" in { @@ -1188,7 +1188,7 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { .asRundownPanel(Seq(withTooLongKicker, withTooLongKicker, withTooLongKicker), "rundown-container-id") outcome.toOption should be(None) - outcome.left.get.contains(s"Kicker text '${longerThan30}' is longer than 30 characters") should be(true) + outcome.swap.contains(s"Kicker text '${longerThan30}' is longer than 30 characters") should be(true) } "TrailToShowcase validation" should "reject rundown panel articles with titles longer than 64 characters" in { @@ -1208,7 +1208,7 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { ) rundownPanel.toOption should be(None) - rundownPanel.left.get.contains(s"The headline '$longerThan64' is longer than 64 characters") should be(true) + rundownPanel.swap.contains(s"The headline '$longerThan64' is longer than 64 characters") should be(true) } "TrailToShowcase validation" should "reject rundown articles with images smaller than 1200x900" in { @@ -1222,7 +1222,7 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { .asRundownPanel(Seq(withTooSmallImage, withTooSmallImage, withTooSmallImage), "rundown-container-id") rundownPanel.toOption should be(None) - rundownPanel.left.get.contains("Could not find image bigger than the minimum required size: 1200x900") should be( + rundownPanel.swap.contains("Could not find image bigger than the minimum required size: 1200x900") should be( true, ) } @@ -1245,7 +1245,7 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { val rundownPanel = TrailsToShowcase .asRundownPanel(Seq(withKicker, withKicker, withoutKicker), "rundown-container-id") - .right + .toOption .get rundownPanel.articleGroup.articles.size should be(3) @@ -1269,8 +1269,8 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { val outcome = TrailsToShowcase .asRundownPanel(Seq(withAuthor, withAuthor, withoutAuthor), "rundown-container-id") - outcome.right.toOption should be(None) - outcome.left.get.contains("Rundown trails need to have all Kickers or all Bylines") should be(true) + outcome.toOption should be(None) + outcome.swap.contains("Rundown trails need to have all Kickers or all Bylines") should be(true) } "TrailToShowcase validation" should "choose kickers over authors" in { @@ -1285,7 +1285,7 @@ class TrailsToShowcaseTest extends AnyFlatSpec with Matchers { val rundownPanel = TrailsToShowcase .asRundownPanel(Seq(withAuthorAndKicker, withAuthorAndKicker, withAuthorAndKicker), "rundown-container-id") - .right + .toOption .get rundownPanel.articleGroup.articles.size should be(3) diff --git a/common/test/common/commercial/hosted/ColourTest.scala b/common/test/common/commercial/hosted/ColourTest.scala index 29030e8e56d9..dd983deb2d4b 100644 --- a/common/test/common/commercial/hosted/ColourTest.scala +++ b/common/test/common/commercial/hosted/ColourTest.scala @@ -11,36 +11,36 @@ class ColourTest extends AnyFlatSpec with Matchers { "isDark" should "be true for Zootropolis green" in { val zootropolisColour = Colour("#2ec869") - zootropolisColour shouldBe 'dark + zootropolisColour shouldBe Symbol("dark") } it should "be false for a bright colour e.g Renault Yellow" in { val renaultColour = Colour("#ffc421") - renaultColour should not be 'dark + renaultColour should not be Symbol("dark") } it should "be true for a dark colour" in { val brown = Colour("#6f5200") - brown shouldBe 'dark + brown shouldBe Symbol("dark") } it should "be false for white" in { val white = Colour("#ffffff") - white should not be 'dark + white should not be Symbol("dark") } it should "be true for black" in { val black = Colour("#000000") - black shouldBe 'dark + black shouldBe Symbol("dark") } it should "be true for Visit Britain colour" in { val visitBritainColour = Colour("#E41F13") - visitBritainColour shouldBe 'dark + visitBritainColour shouldBe Symbol("dark") } it should "be true for Chester Zoo colour" in { val chesterZooColour = Colour("#E31B22") - chesterZooColour shouldBe 'dark + chesterZooColour shouldBe Symbol("dark") } } diff --git a/common/test/common/dfp/GuLineItemTest.scala b/common/test/common/dfp/GuLineItemTest.scala index 36fcc5c2bab7..f579b67c90c9 100644 --- a/common/test/common/dfp/GuLineItemTest.scala +++ b/common/test/common/dfp/GuLineItemTest.scala @@ -53,36 +53,36 @@ class GuLineItemTest extends AnyFlatSpec with Matchers { "isSuitableForTopAboveNavSlot" should "be true for a line item that meets all the rules" in { - lineItem() shouldBe 'suitableForTopAboveNavSlot + lineItem() shouldBe Symbol("suitableForTopAboveNavSlot") } it should "be true for a line item that has relevant creative targeting" in { val creativePlaceholders = Seq(GuCreativePlaceholder(leaderboardSize, targeting = Some(defaultTargeting))) - lineItem(creativePlaceholders = creativePlaceholders) shouldBe 'suitableForTopAboveNavSlot + lineItem(creativePlaceholders = creativePlaceholders) shouldBe Symbol("suitableForTopAboveNavSlot") } it should "be false for a section front targeted indirectly" in { val target = targeting(Seq(GuAdUnit("id", Seq("theguardian.com"), GuAdUnit.ACTIVE))) - lineItem(targeting = target) should not be 'suitableForTopAboveNavSlot + lineItem(targeting = target) should not be Symbol("suitableForTopAboveNavSlot") } it should "be false for an untargeted section front" in { val target = targeting(Seq(GuAdUnit("id", Seq("theguardian.com", "politics"), GuAdUnit.ACTIVE))) - lineItem(targeting = target) should not be 'suitableForTopAboveNavSlot + lineItem(targeting = target) should not be Symbol("suitableForTopAboveNavSlot") } it should "be false for a front whose section is targeted but front not targeted directly" in { val target = targeting(Seq(GuAdUnit("id", Seq("theguardian.com", "business"), GuAdUnit.ACTIVE))) - lineItem(targeting = target) should not be 'suitableForTopAboveNavSlot + lineItem(targeting = target) should not be Symbol("suitableForTopAboveNavSlot") } it should "be false for a CPM campaign" in { - lineItem(costType = "CPM") should not be 'suitableForTopAboveNavSlot + lineItem(costType = "CPM") should not be Symbol("suitableForTopAboveNavSlot") } it should "be false for a completed campaign" in { - lineItem(endTime = Some(now.minusDays(1))) should not be 'suitableForTopAboveNavSlot + lineItem(endTime = Some(now.minusDays(1))) should not be Symbol("suitableForTopAboveNavSlot") } } diff --git a/common/test/conf/CachedHealthCheckTest.scala b/common/test/conf/CachedHealthCheckTest.scala index 58609b0516a3..c8db040ad3f7 100644 --- a/common/test/conf/CachedHealthCheckTest.scala +++ b/common/test/conf/CachedHealthCheckTest.scala @@ -64,7 +64,7 @@ import scala.util.Random val controller = new MockController(Helpers.stubControllerComponents()) // Populate the cache and wait for it to finish - whenReady(controller.runChecks) { _ => + whenReady(controller.runChecks()) { _ => // Call the /_healthcheck endpoint on this controller val healthCheckRequest = FakeRequest(method = "GET", path = "/_healthcheck") val response = call(controller.healthCheck(), healthCheckRequest) @@ -110,7 +110,7 @@ import scala.util.Random } "results which are never expiring" should { "200" in { - val resultDate = DateTime.now.minus(scala.util.Random.nextLong) // random date in the past + val resultDate = DateTime.now.minus(scala.util.Random.nextLong()) // random date in the past val mockResults = List(mockResult(200, resultDate, None)) getHealthCheck(mockResults, HealthCheckPolicy.All) { response => status(response) should be(200) diff --git a/common/test/conf/audio/FlagshipFrontContainerSpec.scala b/common/test/conf/audio/FlagshipFrontContainerSpec.scala index a77fc7db62bc..b25c143a4681 100644 --- a/common/test/conf/audio/FlagshipFrontContainerSpec.scala +++ b/common/test/conf/audio/FlagshipFrontContainerSpec.scala @@ -11,7 +11,7 @@ class FlagshipFrontContainerSpec extends AnyFlatSpec with Matchers with BeforeAn private val formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm").withZone(FlagshipFrontContainer.londonTimezone) - override def beforeAll: Unit = { + override def beforeAll(): Unit = { FlagshipFrontContainerSwitch.switchOn() } diff --git a/common/test/model/ContentTest.scala b/common/test/model/ContentTest.scala index c326c4ad94d4..9dc51e2fd67f 100644 --- a/common/test/model/ContentTest.scala +++ b/common/test/model/ContentTest.scala @@ -60,7 +60,7 @@ class ContentTest elements = Some(elements), ) - val trail: ContentType = Content(content) + val trail: model.ContentType = Content(content) trail.fields.linkText should be("Some article") trail.metadata.url should be("/foo/2012/jan/07/bar") @@ -162,7 +162,7 @@ class ContentTest it should "returns the correct shortUrlId (gu.com)" in { - def contentWithShortUrl(shortUrl: String): ContentType = + def contentWithShortUrl(shortUrl: String): model.ContentType = Content(article.copy(fields = Some(ContentFields(shortUrl = Some(shortUrl))))) contentWithShortUrl("http://gu.com/p/3r1b5").fields.shortUrlId should be("/p/3r1b5") @@ -171,7 +171,7 @@ class ContentTest it should "returns the correct shortUrlId (www.theguardian.com)" in { - def contentWithShortUrl(shortUrl: String): ContentType = + def contentWithShortUrl(shortUrl: String): model.ContentType = Content(article.copy(fields = Some(ContentFields(shortUrl = Some(shortUrl))))) contentWithShortUrl("http://www.theguardian.com/p/3r1b5").fields.shortUrlId should be("/p/3r1b5") @@ -282,7 +282,7 @@ class ContentTest contentType: String, elements: List[ApiElement], maybeByline: Option[String] = None, - ): ContentType = { + ): model.ContentType = { Content(contentApi(contentType, elements, maybeByline)) } diff --git a/common/test/renderers/DotcomRenderingServiceTest.scala b/common/test/renderers/DotcomRenderingServiceTest.scala index eb9226629235..7e3d2f4477c9 100644 --- a/common/test/renderers/DotcomRenderingServiceTest.scala +++ b/common/test/renderers/DotcomRenderingServiceTest.scala @@ -28,7 +28,7 @@ import org.scalatest.flatspec.AnyFlatSpec val dotcomRenderingService = DotcomRenderingService() val articleUrl = "politics/2021/oct/07/coronavirus-report-warned-of-impact-on-uk-four-years-before-pandemic" - val post = PrivateMethod[Future[Result]]('post) + val post = PrivateMethod[Future[Result]](Symbol("post")) val request = TestRequest() private val wsMock = mock[WSClient] private val wsResponseMock = mock[WSResponse] diff --git a/common/test/services/IndexPageTest.scala b/common/test/services/IndexPageTest.scala index 202cf8c8b0b1..62e61cf6b2fb 100644 --- a/common/test/services/IndexPageTest.scala +++ b/common/test/services/IndexPageTest.scala @@ -35,7 +35,7 @@ import scala.concurrent.Future item.section.map(section => IndexPage( page = Section.make(section), - contents = item.results.getOrElse(Nil).map(IndexPageItem(_)), + contents = item.results.getOrElse(Nil).map(IndexPageItem(_)).toSeq, tags = Tags(Nil), date = DateTime.now, tzOverride = None, diff --git a/common/test/views/support/TemplatesTest.scala b/common/test/views/support/TemplatesTest.scala index f818ff68647d..fda99ed8deff 100644 --- a/common/test/views/support/TemplatesTest.scala +++ b/common/test/views/support/TemplatesTest.scala @@ -18,7 +18,7 @@ import play.api.test.FakeRequest import test.TestRequest import org.scalatestplus.play.guice.GuiceOneAppPerSuite -import scala.collection.JavaConverters._ +import scala.jdk.CollectionConverters._ import scala.xml.XML class TemplatesTest extends AnyFlatSpec with Matchers with GuiceOneAppPerSuite { diff --git a/discussion/app/controllers/CommentsController.scala b/discussion/app/controllers/CommentsController.scala index 7ebba0a5fe0b..8659c45c4b11 100644 --- a/discussion/app/controllers/CommentsController.scala +++ b/discussion/app/controllers/CommentsController.scala @@ -126,41 +126,43 @@ class CommentsController( csrfCheck { Action.async { implicit request => val scGuU = request.cookies.get("SC_GU_U") - userForm.bindFromRequest.fold( - formWithErrors => - Future.successful( - BadRequest(views.html.discussionComments.reportComment(commentId, reportAbusePage, formWithErrors)), - ), - userData => { - discussionApi - .postAbuseReport(userData, scGuU) - .map { - case success if success.status == 200 => - NoCache(Redirect(routes.CommentsController.reportAbuseThankYou(commentId))) - case error => - InternalServerError( - views.html.discussionComments.reportComment( - commentId, - reportAbusePage, - userForm.fill(userData), - errorMessage = Some(ReportAbuseFormValidation.genericErrorMessage), - ), - ) - } - .recover({ - case NonFatal(e) => - InternalServerError( - views.html.discussionComments.reportComment( - commentId, - reportAbusePage, - userForm.fill(userData), - errorMessage = Some(ReportAbuseFormValidation.genericErrorMessage), - ), - ) - }) - - }, - ) + userForm + .bindFromRequest() + .fold( + formWithErrors => + Future.successful( + BadRequest(views.html.discussionComments.reportComment(commentId, reportAbusePage, formWithErrors)), + ), + userData => { + discussionApi + .postAbuseReport(userData, scGuU) + .map { + case success if success.status == 200 => + NoCache(Redirect(routes.CommentsController.reportAbuseThankYou(commentId))) + case error => + InternalServerError( + views.html.discussionComments.reportComment( + commentId, + reportAbusePage, + userForm.fill(userData), + errorMessage = Some(ReportAbuseFormValidation.genericErrorMessage), + ), + ) + } + .recover({ + case NonFatal(e) => + InternalServerError( + views.html.discussionComments.reportComment( + commentId, + reportAbusePage, + userForm.fill(userData), + errorMessage = Some(ReportAbuseFormValidation.genericErrorMessage), + ), + ) + }) + + }, + ) } } diff --git a/discussion/app/discussion/api/DiscussionApi.scala b/discussion/app/discussion/api/DiscussionApi.scala index b1287730cbb0..404e179e50e2 100644 --- a/discussion/app/discussion/api/DiscussionApi.scala +++ b/discussion/app/discussion/api/DiscussionApi.scala @@ -253,9 +253,7 @@ object AuthHeaders { val all = Set(guIdToken, cookie) def filterHeaders(headers: Headers): Map[String, String] = - headers.toSimpleMap filterKeys { - all.contains - } + headers.toSimpleMap.view.filterKeys(all.contains).toMap } case class DiscussionParams( diff --git a/discussion/app/discussion/model/Comment.scala b/discussion/app/discussion/model/Comment.scala index f6bbc830c782..0ee0b923cebc 100644 --- a/discussion/app/discussion/model/Comment.scala +++ b/discussion/app/discussion/model/Comment.scala @@ -81,7 +81,7 @@ object Comment extends implicits.Dates { (json \\ "responses").headOption map { _.asInstanceOf[JsArray].value map { Comment(_, None, discussionOpt) } } getOrElse Nil - } + }.toSeq } case class ResponseTo(displayName: String, commentId: String) diff --git a/discussion/app/discussion/model/DiscussionKey.scala b/discussion/app/discussion/model/DiscussionKey.scala index 444d3663ed9b..f28d6eebff92 100644 --- a/discussion/app/discussion/model/DiscussionKey.scala +++ b/discussion/app/discussion/model/DiscussionKey.scala @@ -18,7 +18,7 @@ object DiscussionKey { new PathBindable[DiscussionKey] { override def bind(key: String, value: String): Either[String, DiscussionKey] = { for { - keyAsString <- stringBinder.bind(key, value).right + keyAsString <- stringBinder.bind(key, value) } yield DiscussionKey(keyAsString) } diff --git a/discussion/app/discussion/model/comments.scala b/discussion/app/discussion/model/comments.scala index 7e5be6b6f908..f00d13f92681 100644 --- a/discussion/app/discussion/model/comments.scala +++ b/discussion/app/discussion/model/comments.scala @@ -28,7 +28,7 @@ object DiscussionComments { val comments = (json \ "discussion" \ "comments").as[JsArray].value map { Comment(_, None, Some(discussion)) } DiscussionComments( discussion = discussion, - comments = comments, + comments = comments.toSeq, pagination = DiscussionPagination(json), commentCount = (json \ "discussion" \ "commentCount").asOpt[Int] getOrElse 0, topLevelCommentCount = (json \ "discussion" \ "topLevelCommentCount").asOpt[Int] getOrElse 0, @@ -53,7 +53,7 @@ object ProfileComments { val comments = (json \ "comments").as[JsArray].value map { Comment(_, Some(profile), None) } ProfileComments( profile = profile, - comments = comments, + comments = comments.toSeq, pagination = DiscussionPagination(json), ) } @@ -65,7 +65,7 @@ object ProfileReplies { } ProfileComments( profile = Profile(json), - comments = comments, + comments = comments.toSeq, pagination = DiscussionPagination(json), ) } @@ -84,7 +84,7 @@ object ProfileDiscussions { val discussion = Discussion(d) DiscussionComments( discussion = discussion, - comments = (d \ "comments").as[JsArray].value.map { Comment(_, Some(profile), Some(discussion)) }, + comments = (d \ "comments").as[JsArray].value.map { Comment(_, Some(profile), Some(discussion)) }.toSeq, pagination = DiscussionPagination(json), commentCount = 0, topLevelCommentCount = 0, @@ -96,7 +96,7 @@ object ProfileDiscussions { } ProfileDiscussions( profile = profile, - discussions = discussions, + discussions = discussions.toIndexedSeq, DiscussionPagination(json), ) } diff --git a/discussion/app/views/fragments/reportCommentForm.scala.html b/discussion/app/views/fragments/reportCommentForm.scala.html index c341304bfc92..2b661975d31d 100644 --- a/discussion/app/views/fragments/reportCommentForm.scala.html +++ b/discussion/app/views/fragments/reportCommentForm.scala.html @@ -11,7 +11,7 @@ userForm.error("email"), userForm.error("reason") ) { case (emailInput: Option[String], categoryError: Option[FormError], emailError: Option[FormError], reasonError: Option[FormError]) => - @helper.form(controllers.routes.CommentsController.reportAbuseSubmission(commentId), 'class -> "form") { + @helper.form(controllers.routes.CommentsController.reportAbuseSubmission(commentId), Symbol("class") -> "form") { @helper.CSRF.formField
diff --git a/facia-press/app/frontpress/FapiFrontPress.scala b/facia-press/app/frontpress/FapiFrontPress.scala index 84db73d154ed..243c1f07b90d 100644 --- a/facia-press/app/frontpress/FapiFrontPress.scala +++ b/facia-press/app/frontpress/FapiFrontPress.scala @@ -278,7 +278,7 @@ trait FapiFrontPress extends EmailFrontPress with GuLogging { case Success(_) => val pressDuration: Long = stopWatch.elapsed log.info(s"Successfully pressed $path in $pressDuration ms") - FaciaPressMetrics.AllFrontsPressLatencyMetric.recordDuration(pressDuration) + FaciaPressMetrics.AllFrontsPressLatencyMetric.recordDuration(pressDuration.toDouble) /** We record separate metrics for each of the editions' network fronts */ val metricsByPath = Map( @@ -288,7 +288,7 @@ trait FapiFrontPress extends EmailFrontPress with GuLogging { ) if (Edition.all.map(_.id.toLowerCase).contains(path)) { metricsByPath.get(path).foreach { metric => - metric.recordDuration(pressDuration) + metric.recordDuration(pressDuration.toDouble) } } case Failure(error) => diff --git a/facia-press/app/frontpress/ToolPressQueueWorker.scala b/facia-press/app/frontpress/ToolPressQueueWorker.scala index fe20a7b32411..80fcf38a854a 100644 --- a/facia-press/app/frontpress/ToolPressQueueWorker.scala +++ b/facia-press/app/frontpress/ToolPressQueueWorker.scala @@ -70,7 +70,7 @@ class ToolPressQueueWorker(liveFapiFrontPress: LiveFapiFrontPress, draftFapiFron if (forceConfigUpdate.exists(identity)) { ConfigAgent.refreshAndReturn } else - Future.successful(Unit) + Future.successful(()) for { _ <- forceConfigUpdateFuture diff --git a/facia-press/app/lifecycle/FaciaPressLifecycle.scala b/facia-press/app/lifecycle/FaciaPressLifecycle.scala index 3abd4f2364a3..39023ee073a6 100644 --- a/facia-press/app/lifecycle/FaciaPressLifecycle.scala +++ b/facia-press/app/lifecycle/FaciaPressLifecycle.scala @@ -21,9 +21,9 @@ class FaciaPressLifecycle( } override def start(): Unit = { - toolPressQueueWorker.start + toolPressQueueWorker.start() if (Configuration.faciatool.frontPressCronQueue.isDefined) { - frontPressCron.start + frontPressCron.start() } } } diff --git a/facia/app/pages/FrontHtmlPage.scala b/facia/app/pages/FrontHtmlPage.scala index 17b9c674efd7..cfd755c13b13 100644 --- a/facia/app/pages/FrontHtmlPage.scala +++ b/facia/app/pages/FrontHtmlPage.scala @@ -54,7 +54,7 @@ object FrontHtmlPage extends HtmlPage[PressedPage] { checkModuleSupport(), inlineJSBlocking(), ), - bodyTag(classes = defaultBodyClasses)( + bodyTag(classes = defaultBodyClasses())( skipToMainContent(), pageSkin() when page.metadata.hasPageSkin(request), guardianHeaderHtml(), diff --git a/identity/app/controllers/AccountDeletionController.scala b/identity/app/controllers/AccountDeletionController.scala index f3a418db32b7..c388cff9b0c0 100644 --- a/identity/app/controllers/AccountDeletionController.scala +++ b/identity/app/controllers/AccountDeletionController.scala @@ -107,7 +107,7 @@ class AccountDeletionController( def processAccountDeletionForm: Action[AnyContent] = csrfCheck { fullAuthWithIdapiUserAction.async { implicit request => - val boundForm = accountDeletionForm.bindFromRequest + val boundForm = accountDeletionForm.bindFromRequest() boundForm.fold( formWithErrors => diff --git a/identity/app/controllers/editprofile/ConsentsJourney.scala b/identity/app/controllers/editprofile/ConsentsJourney.scala index 8d5ddfedb505..3e8bdb517b06 100644 --- a/identity/app/controllers/editprofile/ConsentsJourney.scala +++ b/identity/app/controllers/editprofile/ConsentsJourney.scala @@ -37,34 +37,36 @@ trait ConsentsJourney extends EditProfileControllerComponents { csrfCheck { consentAuthWithIdapiUserAction.async { implicit request => val returnUrlForm = Form(single("returnUrl" -> nonEmptyText)) - returnUrlForm.bindFromRequest.fold( - formWithErrors => Future.successful(BadRequest(Json.toJson(formWithErrors.errors.toList))), - returnUrl => { - val newConsents = - if (request.user.consents.isEmpty) Consent.defaultConsents - else Consent.addNewDefaults(request.user.consents) - identityApiClient - .saveUser( - request.user.id, - UserUpdateDTO( - consents = Some(newConsents), - ), - request.user.auth, - ) - .map { - case Left(idapiErrors) => - logger.error(s"Failed to set save user consents ${request.user.id}: $idapiErrors") - InternalServerError(Json.toJson(idapiErrors)) - - case Right(updatedUser) => - logger.info(s"Successfully set consents for user ${request.user.id}") - Redirect( - s"${routes.EditProfileController.displayConsentComplete().url}", - Map("returnUrl" -> Seq(returnUrl)), - ) - } - }, - ) + returnUrlForm + .bindFromRequest() + .fold( + formWithErrors => Future.successful(BadRequest(Json.toJson(formWithErrors.errors.toList))), + returnUrl => { + val newConsents = + if (request.user.consents.isEmpty) Consent.defaultConsents + else Consent.addNewDefaults(request.user.consents) + identityApiClient + .saveUser( + request.user.id, + UserUpdateDTO( + consents = Some(newConsents), + ), + request.user.auth, + ) + .map { + case Left(idapiErrors) => + logger.error(s"Failed to set save user consents ${request.user.id}: $idapiErrors") + InternalServerError(Json.toJson(idapiErrors)) + + case Right(updatedUser) => + logger.info(s"Successfully set consents for user ${request.user.id}") + Redirect( + s"${routes.EditProfileController.displayConsentComplete().url}", + Map("returnUrl" -> Seq(returnUrl)), + ) + } + }, + ) } } diff --git a/identity/app/form/DateFormData.scala b/identity/app/form/DateFormData.scala index 444ede927c84..f5aeac955cd8 100644 --- a/identity/app/form/DateFormData.scala +++ b/identity/app/form/DateFormData.scala @@ -10,7 +10,7 @@ trait DateMapping { def dateMapping(implicit messagesProvider: MessagesProvider): Mapping[DateFormData] = mapping( - "year" -> optional(number(min = 1800, max = DateTime.now.getYear)), + "year" -> optional(number(min = 1800, max = DateTime.now().getYear)), "month" -> optional(number(min = 1, max = 12)), "day" -> optional(number(min = 1, max = 31)), )(DateFormData.apply)(DateFormData.unapply) verifying ( diff --git a/identity/app/form/IdFormHelpers.scala b/identity/app/form/IdFormHelpers.scala index 04558cb9bdbc..105c14c40602 100644 --- a/identity/app/form/IdFormHelpers.scala +++ b/identity/app/form/IdFormHelpers.scala @@ -10,17 +10,35 @@ object IdFormHelpers { val nonInputFields = FieldConstructor(multiInputFieldConstructor.f) def Password(field: Field, args: (Symbol, Any)*): Input = { - val updatedArgs = updateArgs(args, 'autocomplete -> "off", 'autocapitalize -> "off", 'autocorrect -> "off") + val updatedArgs = + updateArgs( + args, + Symbol("autocomplete") -> "off", + Symbol("autocapitalize") -> "off", + Symbol("autocorrect") -> "off", + ) new Input("password", field, updatedArgs: _*) } def Email(field: Field, args: (Symbol, Any)*): Input = { - val updatedArgs = updateArgs(args, 'autocomplete -> "on", 'autocapitalize -> "off", 'autocorrect -> "off") + val updatedArgs = + updateArgs( + args, + Symbol("autocomplete") -> "on", + Symbol("autocapitalize") -> "off", + Symbol("autocorrect") -> "off", + ) new Input("email", field, updatedArgs: _*) } def Username(field: Field, args: (Symbol, Any)*): Input = { - val updatedArgs = updateArgs(args, 'autocomplete -> "off", 'autocapitalize -> "off", 'autocorrect -> "off") + val updatedArgs = + updateArgs( + args, + Symbol("autocomplete") -> "off", + Symbol("autocapitalize") -> "off", + Symbol("autocorrect") -> "off", + ) new Input("text", field, updatedArgs: _*) } @@ -37,7 +55,7 @@ object IdFormHelpers { } def Radio(field: Field, values: List[String], args: (Symbol, Any)*): Input = { - new Input("radio", field, ('_values -> values :: args.toList): _*) + new Input("radio", field, (Symbol("_values") -> values :: args.toList): _*) } def Textarea(field: Field, args: (Symbol, Any)*): Input = { @@ -55,15 +73,15 @@ object IdFormHelpers { } class Input(val inputType: String, val field: Field, initialArgs: (Symbol, Any)*) { - val cls = "text-input " + getArgOrElse('class, "", initialArgs) - val autocomplete = getArgOrElse('autocomplete, "on", initialArgs) - val autocapitalize = getArgOrElse('autocapitalize, "on", initialArgs) - val autocorrect = getArgOrElse('autocorrect, "on", initialArgs) - val spellcheck = getArgOrElse('spellcheck, "false", initialArgs) - val autofocus = getArgOrElse('autofocus, false, initialArgs) + val cls = "text-input " + getArgOrElse(Symbol("class"), "", initialArgs) + val autocomplete = getArgOrElse(Symbol("autocomplete"), "on", initialArgs) + val autocapitalize = getArgOrElse(Symbol("autocapitalize"), "on", initialArgs) + val autocorrect = getArgOrElse(Symbol("autocorrect"), "on", initialArgs) + val spellcheck = getArgOrElse(Symbol("spellcheck"), "false", initialArgs) + val autofocus = getArgOrElse(Symbol("autofocus"), false, initialArgs) val required = field.constraints.exists(constraint => constraint._1 == "constraint.required") - val args = initialArgs.filter(_._1 != 'type) ++ Seq('_showConstraints -> false) + val args = initialArgs.filter(_._1 != Symbol("type")) ++ Seq(Symbol("_showConstraints") -> false) private def getArgOrElse[T](property: Symbol, default: T, args: Seq[(Symbol, Any)]): T = args.toMap.get(property).map(_.asInstanceOf[T]).getOrElse(default) diff --git a/identity/app/jobs/TorExitNodeList.scala b/identity/app/jobs/TorExitNodeList.scala index ace896985624..e1607db51357 100644 --- a/identity/app/jobs/TorExitNodeList.scala +++ b/identity/app/jobs/TorExitNodeList.scala @@ -2,6 +2,7 @@ package jobs import common.{Box, GuLogging} +import scala.jdk.CollectionConverters._ import java.net.InetAddress import scala.io.Source @@ -18,7 +19,7 @@ object TorExitNodeList extends GuLogging { val nodes = addresses map { address => val ip = address.getHostAddress val url = s"$torNodeListUrl?ip=$ip&port=80" - Source.fromURL(url).getLines.toList.filterNot { line => line.startsWith("#") } + Source.fromURL(url).getLines().toList.filterNot { line => line.startsWith("#") } } val allNodes = nodes.toList.flatMap { x => x }.toSet diff --git a/identity/app/model/PhoneNumbers.scala b/identity/app/model/PhoneNumbers.scala index 839d552c522a..c14b74112219 100644 --- a/identity/app/model/PhoneNumbers.scala +++ b/identity/app/model/PhoneNumbers.scala @@ -1,7 +1,7 @@ package model import com.google.i18n.phonenumbers.PhoneNumberUtil -import scala.collection.JavaConverters._ +import scala.jdk.CollectionConverters._ import reflect.runtime.{universe => ru} object PhoneNumbers { diff --git a/identity/app/views/fragments/form/checkboxField.scala.html b/identity/app/views/fragments/form/checkboxField.scala.html index fa606d01f1f3..34ea66d587f9 100644 --- a/identity/app/views/fragments/form/checkboxField.scala.html +++ b/identity/app/views/fragments/form/checkboxField.scala.html @@ -6,7 +6,7 @@ @input(idInput.field, idInput.args:_*) { (id, name, value, htmlArgs) => diff --git a/identity/app/views/fragments/form/fieldConstructors/frontendFieldConstructor.scala.html b/identity/app/views/fragments/form/fieldConstructors/frontendFieldConstructor.scala.html index cb3422f88bc2..4e71167eb488 100644 --- a/identity/app/views/fragments/form/fieldConstructors/frontendFieldConstructor.scala.html +++ b/identity/app/views/fragments/form/fieldConstructors/frontendFieldConstructor.scala.html @@ -1,8 +1,8 @@ @(elements: views.html.helper.FieldElements) -@elements.args.toMap.get('type) +@elements.args.toMap.get(Symbol("type")) -
  • +
  • @if(elements.infos.nonEmpty) { diff --git a/identity/app/views/profile/deletion/accountDeletionForm.scala.html b/identity/app/views/profile/deletion/accountDeletionForm.scala.html index 380d7448af2d..1b96505b3caf 100644 --- a/identity/app/views/profile/deletion/accountDeletionForm.scala.html +++ b/identity/app/views/profile/deletion/accountDeletionForm.scala.html @@ -115,8 +115,8 @@

    Confirm account deletion

      - @inputField(Password(accountDeletionForm("password"), '_label -> "Password", 'class -> "js-register-password js-password-strength", - (Symbol("data-test-id"), "account-deletion-password"), 'required -> true)) + @inputField(Password(accountDeletionForm("password"), Symbol("_label") -> "Password", Symbol("class") -> "js-register-password js-password-strength", + (Symbol("data-test-id"), "account-deletion-password"), Symbol("required") -> true))
    • diff --git a/identity/conf/routes b/identity/conf/routes index d5a6e5f1d466..3799a18ff5a8 100644 --- a/identity/conf/routes +++ b/identity/conf/routes @@ -5,7 +5,7 @@ GET /_healthcheck controllers.HealthCheck.heal GET /google1ec7a89a27d60d47.html controllers.Assets.at(path = "/public", file = "google1ec7a89a27d60d47.html") -GET /complete-registration controllers.EmailVerificationController.completeRegistration +GET /complete-registration controllers.EmailVerificationController.completeRegistration() POST /complete-registration controllers.EmailVerificationController.resendValidationEmail(returnUrl: String) ######################################################################################################################## diff --git a/onward/app/controllers/MostPopularController.scala b/onward/app/controllers/MostPopularController.scala index 32ae029b8ad8..602ec236a3e7 100644 --- a/onward/app/controllers/MostPopularController.scala +++ b/onward/app/controllers/MostPopularController.scala @@ -202,7 +202,7 @@ class MostPopularController( // Get "Most Commented" & "Most Shared" cards for Extended "Most Read" container private def mostCards(): Map[String, Option[ContentCard]] = - mostPopularAgent.mostSingleCardsBox.get().mapValues(ContentCard.fromApiContent(_)) + mostPopularAgent.mostSingleCardsBox.get().view.mapValues(ContentCard.fromApiContent).toMap private def lookup(edition: Edition, path: String)(implicit request: RequestHeader): Future[Option[MostPopular]] = { log.info(s"Fetching most popular: $path for edition $edition") @@ -217,7 +217,7 @@ class MostPopularController( contentApiClient.getResponse(capiItemWithDate).map { response => val heading = response.section.map(s => "in " + s.webTitle).getOrElse("Across The Guardian") val popular = response.mostViewed.getOrElse(Nil) take 10 map (RelatedContentItem(_)) - if (popular.isEmpty) None else Some(MostPopular(heading, path, popular.map(_.faciaContent))) + if (popular.isEmpty) None else Some(MostPopular(heading, path, popular.map(_.faciaContent).toSeq)) } } } diff --git a/onward/app/controllers/MostViewedAudioController.scala b/onward/app/controllers/MostViewedAudioController.scala index 946f7aea507e..bf6c8602af82 100644 --- a/onward/app/controllers/MostViewedAudioController.scala +++ b/onward/app/controllers/MostViewedAudioController.scala @@ -19,7 +19,7 @@ class MostViewedAudioController( def renderMostViewed(): Action[AnyContent] = Action { implicit request => - getMostViewedAudio match { + getMostViewedAudio() match { case Nil => Cached(60) { JsonNotFound() } case audio => renderMostViewedAudio(audio, "audio") } @@ -27,7 +27,7 @@ class MostViewedAudioController( def renderMostViewedPodcast(): Action[AnyContent] = Action { implicit request => - getMostViewedPodcast match { + getMostViewedPodcast() match { case Nil => Cached(60) { JsonNotFound() } case podcast => renderMostViewedAudio(podcast, "podcast") } diff --git a/onward/app/controllers/MostViewedGalleryController.scala b/onward/app/controllers/MostViewedGalleryController.scala index 38681b270e46..e555bf15de50 100644 --- a/onward/app/controllers/MostViewedGalleryController.scala +++ b/onward/app/controllers/MostViewedGalleryController.scala @@ -39,7 +39,7 @@ class MostViewedGalleryController( def renderMostViewed(): Action[AnyContent] = Action { implicit request => - getMostViewedGallery match { + getMostViewedGallery() match { case Nil => Cached(60) { JsonNotFound() } case galleries => renderMostViewedGallery(galleries) } diff --git a/onward/app/controllers/MostViewedSocialController.scala b/onward/app/controllers/MostViewedSocialController.scala index 0bcea69f4480..a9fad06cc699 100644 --- a/onward/app/controllers/MostViewedSocialController.scala +++ b/onward/app/controllers/MostViewedSocialController.scala @@ -59,7 +59,7 @@ class MostViewedSocialController( Fixed(container), CollectionConfigWithId(dataId, config), CollectionEssentials( - items.map(FaciaContentConvert.contentToFaciaContent), + items.map(FaciaContentConvert.contentToFaciaContent).toSeq, Nil, displayName, None, diff --git a/onward/app/controllers/SeriesController.scala b/onward/app/controllers/SeriesController.scala index 3d6bc1496b1f..7239d946d1b0 100644 --- a/onward/app/controllers/SeriesController.scala +++ b/onward/app/controllers/SeriesController.scala @@ -83,7 +83,7 @@ class SeriesController( response.tag.flatMap { tag => val trails = response.results.getOrElse(Nil) filterNot isCurrentStory map (RelatedContentItem(_)) if (trails.nonEmpty) { - Some(Series(seriesId, Tag.make(tag, None), RelatedContent(trails))) + Some(Series(seriesId, Tag.make(tag, None), RelatedContent(trails.toSeq))) } else { None } } } diff --git a/onward/app/controllers/TaggedContentController.scala b/onward/app/controllers/TaggedContentController.scala index 3d95494dcbc9..1dc73f6cc0b3 100644 --- a/onward/app/controllers/TaggedContentController.scala +++ b/onward/app/controllers/TaggedContentController.scala @@ -34,7 +34,7 @@ class TaggedContentController( private def render(trails: Seq[ContentType])(implicit request: RequestHeader): Result = Cached(300) { - JsonComponent( + common.JsonComponent( "trails" -> JsArray(trails.map { trail => Json.obj( ("webTitle", trail.metadata.webTitle), diff --git a/onward/app/feed/MostPopularAgent.scala b/onward/app/feed/MostPopularAgent.scala index c133b10aa631..a4dfc084b9f6 100644 --- a/onward/app/feed/MostPopularAgent.scala +++ b/onward/app/feed/MostPopularAgent.scala @@ -103,7 +103,7 @@ class MostPopularAgent(contentApiClient: ContentApiClient, ophanApi: OphanApi, w for { mostViewedResponse <- futureMostViewed - mostViewed = mostViewedResponse.mostViewed.getOrElse(Nil).take(10).map(RelatedContentItem(_)) + mostViewed = mostViewedResponse.mostViewed.getOrElse(Nil).take(10).map(RelatedContentItem(_)).toSeq newMap <- relatedContentsBox.alter(_ + (edition.id -> mostViewed)) } yield newMap } diff --git a/onward/app/feed/MostViewedVideoAgent.scala b/onward/app/feed/MostViewedVideoAgent.scala index 4724711d1bce..26c8b7718738 100644 --- a/onward/app/feed/MostViewedVideoAgent.scala +++ b/onward/app/feed/MostViewedVideoAgent.scala @@ -27,7 +27,7 @@ class MostViewedVideoAgent(contentApiClient: ContentApiClient, ophanApi: OphanAp ophanResponse.flatMap { result => val paths: Seq[String] = for { - videoResult <- result.asOpt[JsArray].map(_.value).getOrElse(Nil) + videoResult <- result.asOpt[JsArray].map(_.value.toSeq).getOrElse(Nil) path <- videoResult.validate[QueryResult].asOpt.map(_.paths).getOrElse(Nil) if path.contains("/video/") } yield path @@ -46,7 +46,7 @@ class MostViewedVideoAgent(contentApiClient: ContentApiClient, ophanApi: OphanAp .pageSize(20), ) .map { r => - val videoContent: Seq[client.model.v1.Content] = r.results.filter(_.isVideo) + val videoContent: Seq[client.model.v1.Content] = r.results.filter(_.isVideo).toSeq log.info(s"Number of video content items from CAPI: ${videoContent.size}") videoContent.map(Content(_)).collect { case v: Video => v } } diff --git a/onward/app/services/repositories.scala b/onward/app/services/repositories.scala index 1f0fe59e7242..aed1e8498b5c 100644 --- a/onward/app/services/repositories.scala +++ b/onward/app/services/repositories.scala @@ -34,7 +34,7 @@ trait Related extends ConciergeRepository { val relatedContentItems = response.relatedContent.getOrElse(Nil) map { item => RelatedContentItem(item) } - RelatedContent(relatedContentItems) + RelatedContent(relatedContentItems.toSeq) } trails recoverApi404With RelatedContent(Nil) @@ -57,7 +57,7 @@ trait Related extends ConciergeRepository { RelatedContentItem(item) } RelatedContent( - items.sortBy(content => -mostReadAgent.getViewCount(content.content.metadata.id).getOrElse(0)).take(10), + items.sortBy(content => -mostReadAgent.getViewCount(content.content.metadata.id).getOrElse(0)).take(10).toSeq, ) } diff --git a/project/Dependencies.scala b/project/Dependencies.scala index ea37d670ca5b..aa486b50b29a 100644 --- a/project/Dependencies.scala +++ b/project/Dependencies.scala @@ -52,6 +52,7 @@ object Dependencies { val rome = "rome" % "rome" % romeVersion val romeModules = "org.rometools" % "rome-modules" % romeVersion val scalaCheck = "org.scalacheck" %% "scalacheck" % "1.16.0" % Test + val scalaCollectionPlus = "com.madgag" %% "scala-collection-plus" % "0.11" val nScalaTime = "com.github.nscala-time" %% "nscala-time" % "2.30.0" val scalaTest = "org.scalatest" %% "scalatest" % "3.2.11" % Test val scalaTestPlus = "org.scalatestplus.play" %% "scalatestplus-play" % "5.1.0" % Test diff --git a/project/ProjectSettings.scala b/project/ProjectSettings.scala index eb102dbeda34..86a5bed97d8f 100644 --- a/project/ProjectSettings.scala +++ b/project/ProjectSettings.scala @@ -10,6 +10,7 @@ import com.gu.Dependencies._ import play.sbt.{PlayAkkaHttpServer, PlayNettyServer, PlayScala} import com.typesafe.sbt.SbtNativePackager.Universal import com.typesafe.sbt.packager.Keys.packageName +import scalafix.sbt.ScalafixPlugin.autoImport.{scalafixDependencies, scalafixSemanticdb} object ProjectSettings { @@ -33,6 +34,11 @@ object ProjectSettings { Compile / doc / sources := Seq.empty, Compile / doc := target.map(_ / "none").value, scalaVersion := "2.13.8", + semanticdbEnabled := true, + semanticdbVersion := scalafixSemanticdb.revision, + ThisBuild / scalafixDependencies += "org.scala-lang.modules" %% "scala-collection-migrations" % "2.7.0", + addCompilerPlugin(scalafixSemanticdb), + scalacOptions ++= List("-Yrangepos", "-P:semanticdb:synthetics:on"), initialize := { val _ = initialize.value assert( diff --git a/project/plugins.sbt b/project/plugins.sbt index 2b290fc56f0a..dda9bae47501 100644 --- a/project/plugins.sbt +++ b/project/plugins.sbt @@ -27,4 +27,4 @@ addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.4.0") addSbtPlugin("net.virtual-void" % "sbt-dependency-graph" % "0.9.0") -addSbtPlugin("ch.epfl.scala" % "sbt-scalafix" % "0.10.1") +addSbtPlugin("ch.epfl.scala" % "sbt-scalafix" % "0.9.34") diff --git a/sport/app/cricket/feed/CricketThrottler.scala b/sport/app/cricket/feed/CricketThrottler.scala index c25aaed5e8ff..1b23526c82e7 100644 --- a/sport/app/cricket/feed/CricketThrottler.scala +++ b/sport/app/cricket/feed/CricketThrottler.scala @@ -35,7 +35,7 @@ class CricketThrottlerActor()(implicit materializer: Materializer) extends Actor .run() override def receive: PartialFunction[Any, Unit] = { - case toBeThrottled: CricketThrottledTask[Any] => throttler ! TaskWithSender(sender, toBeThrottled.task) + case toBeThrottled: CricketThrottledTask[Any] => throttler ! TaskWithSender(sender(), toBeThrottled.task) case throttled: TaskWithSender[Any] => throttled.task() pipeTo throttled.sender } } diff --git a/sport/app/cricket/feed/cricketPaFeed.scala b/sport/app/cricket/feed/cricketPaFeed.scala index 090fa2e938e6..cfc6f8750816 100644 --- a/sport/app/cricket/feed/cricketPaFeed.scala +++ b/sport/app/cricket/feed/cricketPaFeed.scala @@ -33,7 +33,7 @@ class PaFeed(wsClient: WSClient, actorSystem: ActorSystem, materializer: Materia wsClient .url(endpoint) .withHttpHeaders(header, xmlContentType) - .get + .get() .map { response => response.status match { case 200 => response.body @@ -86,7 +86,7 @@ class PaFeed(wsClient: WSClient, actorSystem: ActorSystem, materializer: Materia .url(endpoint) .withHttpHeaders(header, xmlContentType) .withQueryStringParameters(("startDate", start), ("endDate", end)) - .get + .get() .map { response => response.status match { case 200 => XML.loadString(response.body) \\ "match" map (content => (content \ "@id").text) diff --git a/sport/app/football/model/matches.scala b/sport/app/football/model/matches.scala index 9ca050f375df..45d8825a6fdd 100644 --- a/sport/app/football/model/matches.scala +++ b/sport/app/football/model/matches.scala @@ -60,6 +60,7 @@ trait MatchesList extends Football with RichList { case (d, ms) => val competitionsWithMatches = ms .groupBy(_._2) + .view .mapValues(_.map { case (matches, _) => matches }) diff --git a/sport/app/rugby/jobs/RugbyStatsJob.scala b/sport/app/rugby/jobs/RugbyStatsJob.scala index 60bcc2fe4b97..46a99772a41f 100644 --- a/sport/app/rugby/jobs/RugbyStatsJob.scala +++ b/sport/app/rugby/jobs/RugbyStatsJob.scala @@ -48,15 +48,15 @@ class RugbyStatsJob(feed: RugbyFeed) extends GuLogging { homeTeamId: String, awayTeamId: String, ): Option[Match] = { - fixturesAndResultsMatches.get.values.find { rugbyMatch => + fixturesAndResultsMatches.get().values.find { rugbyMatch => isValidMatch(year, month, day, homeTeamId, awayTeamId, rugbyMatch) } } - def getAllResults(): Seq[Match] = fixturesAndResultsMatches.get.values.toList.filter(_.status == Status.Result) + def getAllResults(): Seq[Match] = fixturesAndResultsMatches.get().values.toList.filter(_.status == Status.Result) def getMatchNavContent(rugbyMatch: Match): Option[MatchNavigation] = { - matchNavContent.get.get(rugbyMatch.key) + matchNavContent.get().get(rugbyMatch.key) } private def isValidMatch( diff --git a/sport/test/MatchFeatureTest.scala b/sport/test/MatchFeatureTest.scala index e3a38b4ec1c4..8ed6b3c18ddd 100644 --- a/sport/test/MatchFeatureTest.scala +++ b/sport/test/MatchFeatureTest.scala @@ -4,7 +4,7 @@ import org.scalatest.featurespec.AnyFeatureSpec import org.scalatest.matchers.should.Matchers import org.scalatest.{DoNotDiscover, GivenWhenThen} -import scala.collection.JavaConverters._ +import scala.jdk.CollectionConverters._ @DoNotDiscover class MatchFeatureTest extends AnyFeatureSpec with GivenWhenThen with Matchers with ConfiguredTestSuite {