Skip to content

Commit

Permalink
Merge pull request #553 from NDLANO/some-scala3-updates
Browse files Browse the repository at this point in the history
Fix scala3 warnings
  • Loading branch information
gunnarvelle authored Dec 5, 2024
2 parents 625b464 + af46fbb commit ab69e82
Show file tree
Hide file tree
Showing 28 changed files with 85 additions and 91 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ trait ArticleControllerV2 {
ContentValidator & Props & ErrorHandling & TapirController =>
val articleControllerV2: ArticleControllerV2

import props._
import props.*

class ArticleControllerV2() extends TapirController {
class ArticleControllerV2 extends TapirController {
protected val applicationDescription = "Services for accessing articles from NDLA."

override val serviceName: String = "articles"
Expand Down Expand Up @@ -97,7 +97,7 @@ trait ArticleControllerV2 {
searchContext: Option[String]
)

/** Does a scroll with [[AudioSearchService]] If no scrollId is specified execute the function @orFunction in the
/** Does a scroll with [[ArticleSearchService]] If no scrollId is specified execute the function @orFunction in the
* second parameter list.
*
* @param orFunction
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ trait InternController {
.out(stringBody)
.errorOut(stringInternalServerError)
.serverLogicPure(numShards => {
implicit val ec = ExecutionContext.fromExecutorService(Executors.newSingleThreadExecutor)
implicit val ec: ExecutionContextExecutorService =
ExecutionContext.fromExecutorService(Executors.newSingleThreadExecutor)
val articleIndex = Future { articleIndexService.indexDocuments(numShards) }

Await.result(articleIndex, Duration(10, TimeUnit.MINUTES)) match {
Expand All @@ -71,7 +72,8 @@ trait InternController {
.out(stringBody)
.errorOut(stringInternalServerError)
.serverLogicPure { _ =>
implicit val ec = ExecutionContext.fromExecutorService(Executors.newSingleThreadExecutor)
implicit val ec: ExecutionContextExecutorService =
ExecutionContext.fromExecutorService(Executors.newSingleThreadExecutor)
def pluralIndex(n: Int) = if (n == 1) "1 index" else s"$n indexes"

val articleIndex = Future { articleIndexService.findAllIndexes(props.ArticleSearchIndex) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import sttp.client3.quick.*
import scala.util.Try

trait FrontpageApiClient {
this: NdlaClient with ConverterService with Props =>
this: NdlaClient & ConverterService & Props =>
val frontpageApiClient: FrontpageApiClient

class FrontpageApiClient(FrontpageApiBaseUrl: String = props.FrontpageApiUrl) extends StrictLogging {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import scala.concurrent.{ExecutionContext, ExecutionContextExecutorService, Futu
import scala.util.{Failure, Success, Try}

trait SearchApiClient {
this: NdlaClient with ConverterService with Props =>
this: NdlaClient & ConverterService & Props =>
val searchApiClient: SearchApiClient

class SearchApiClient(SearchApiBaseUrl: String = props.SearchApiUrl) extends StrictLogging {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ package no.ndla.articleapi.model.api

import io.circe.generic.semiauto.{deriveDecoder, deriveEncoder}
import io.circe.{Decoder, Encoder}
import no.ndla.common.implicits._
import no.ndla.common.implicits.*
import no.ndla.common.model.NDLADate
import no.ndla.common.model.api.{Copyright, RelatedContent, RelatedContentLink}
import sttp.tapir.Schema.annotations.description
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ import no.ndla.search.{IndexNotFoundException, NdlaSearchException}
import org.postgresql.util.PSQLException

trait ErrorHandling extends TapirErrorHandling with StrictLogging {
this: Props with Clock with DataSource =>
this: Props & Clock & DataSource =>

import ErrorHelpers._
import ErrorHelpers.*

override def handleErrors: PartialFunction[Throwable, AllErrors] = {
case a: AccessDeniedException if a.unauthorized =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@ object TSTypes {
implicit val nullAlias: TSNamedType[Null] =
TSType.alias[Null]("NullAlias", TSNull) // https://github.com/scala-tsi/scala-tsi/issues/172

// Type-aliases referencing generics doesn't not work without this in scala-tsi. See: https://github.com/scala-tsi/scala-tsi/issues/184
// Type-aliases referencing generics does not work without this in scala-tsi. See: https://github.com/scala-tsi/scala-tsi/issues/184
implicit val relatedContent: TSIType[RelatedContentLink] = TSType.fromCaseClass[RelatedContentLink]
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@ case class ValidationError(
@description("Code stating the type of error") code: String,
@description("Description of the error") description: String,
@description("List of validation messages") messages: Seq[ValidationMessage],
@description("When the error occured") occuredAt: LocalDateTime = LocalDateTime.now()
@description("When the error occurred") occuredAt: LocalDateTime = LocalDateTime.now()
)
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,6 @@ object Sort extends Enum[Sort] with CirceEnum[Sort] {
private val tsEnumValues: Seq[(String, String)] = values.map(e => e.toString -> e.entryName)
implicit val enumTsType: TSNamedType[Sort] = TSType.alias[Sort](
"Sort",
TSEnum.string("ArticleSortEnum", tsEnumValues: _*)
TSEnum.string("ArticleSortEnum", tsEnumValues*)
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import scalikejdbc.*
import scala.util.{Failure, Success, Try}

trait ArticleRepository {
this: DataSource with DBArticle =>
this: DataSource & DBArticle =>
val articleRepository: ArticleRepository

class ArticleRepository extends StrictLogging {
Expand Down Expand Up @@ -64,7 +64,7 @@ trait ArticleRepository {
update ${Article.table}
set document=null
where article_id=$articleId
and revision=(select max(revision) from ${Article.table} where article_id=${articleId})
and revision=(select max(revision) from ${Article.table} where article_id=$articleId)
""".update()
if (numRows == 1) {
Success(articleId)
Expand Down Expand Up @@ -93,7 +93,7 @@ trait ArticleRepository {
sql"""
delete from ${Article.table}
where article_id = $articleId
and revision=(select max(revision) from ${Article.table} where article_id=${articleId})
and revision=(select max(revision) from ${Article.table} where article_id=$articleId)
""".update()
if (numRows == 1) {
Success(articleId)
Expand Down Expand Up @@ -135,7 +135,7 @@ trait ArticleRepository {
articleWhere(
sqls"""
ar.article_id=${articleId.toInt}
and ar.revision=${revision}
and ar.revision=$revision
"""
)
}
Expand Down Expand Up @@ -178,7 +178,7 @@ trait ArticleRepository {
sql"""
select revision
from ${Article.table}
where article_id=${articleId}
where article_id=$articleId
and document is not NULL;
"""
.map(rs => rs.int("revision"))
Expand Down Expand Up @@ -266,11 +266,11 @@ trait ArticleRepository {
val tags = sql"""select tags from
(select distinct JSONB_ARRAY_ELEMENTS_TEXT(tagObj->'tags') tags from
(select JSONB_ARRAY_ELEMENTS(document#>'{tags}') tagObj from ${Article.table}) _
where tagObj->>'language' like ${langOrAll}
where tagObj->>'language' like $langOrAll
order by tags) sorted_tags
where sorted_tags.tags ilike ${sanitizedInput + '%'}
offset ${offset}
limit ${pageSize}
offset $offset
limit $pageSize
"""
.map(rs => rs.string("tags"))
.list()
Expand All @@ -280,7 +280,7 @@ trait ArticleRepository {
select count(*) from
(select distinct JSONB_ARRAY_ELEMENTS_TEXT(tagObj->'tags') tags from
(select JSONB_ARRAY_ELEMENTS(document#>'{tags}') tagObj from ${Article.table}) _
where tagObj->>'language' like ${langOrAll}) all_tags
where tagObj->>'language' like $langOrAll) all_tags
where all_tags.tags ilike ${sanitizedInput + '%'};
"""
.map(rs => rs.int("count"))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,10 @@ import org.jsoup.Jsoup
import scala.util.{Failure, Success, Try}

trait ConverterService {
this: Clock with ArticleRepository with Props =>
this: Clock & ArticleRepository & Props =>
val converterService: ConverterService

import props._
import props.*

class ConverterService extends StrictLogging {

Expand All @@ -70,7 +70,7 @@ trait ConverterService {
.lastOption
}

val highlightKeys: Option[Map[String, _]] = Option(result.highlight)
val highlightKeys: Option[Map[String, ?]] = Option(result.highlight)
val matchLanguage = keyToLanguage(highlightKeys.getOrElse(Map()).keys)

matchLanguage match {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,7 @@ import no.ndla.common.model.domain.article.Article
import scala.util.{Failure, Success, Try}

trait WriteService {
this: ArticleRepository
with ConverterService
with ContentValidator
with ArticleIndexService
with ReadService
with SearchApiClient =>
this: ArticleRepository & ConverterService & ContentValidator & ArticleIndexService & ReadService & SearchApiClient =>
val writeService: WriteService

class WriteService extends StrictLogging {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,36 +8,31 @@

package no.ndla.articleapi.service.search

import com.sksamuel.elastic4s.ElasticDsl._
import com.sksamuel.elastic4s.ElasticDsl.*
import com.sksamuel.elastic4s.requests.searches.queries.compound.BoolQuery
import com.typesafe.scalalogging.StrictLogging
import no.ndla.articleapi.Props
import no.ndla.articleapi.model.api
import no.ndla.articleapi.model.api.{ArticleSummaryV2, ErrorHandling}
import no.ndla.articleapi.model.domain._
import no.ndla.articleapi.model.domain.*
import no.ndla.articleapi.model.search.SearchResult
import no.ndla.articleapi.service.ConverterService
import no.ndla.common.implicits._
import no.ndla.common.implicits.*
import no.ndla.common.model.domain.Availability
import no.ndla.language.Language
import no.ndla.mapping.License
import no.ndla.search.Elastic4sClient

import java.util.concurrent.Executors
import scala.concurrent.{ExecutionContext, Future}
import scala.concurrent.{ExecutionContext, ExecutionContextExecutorService, Future}
import scala.util.{Failure, Success, Try}

trait ArticleSearchService {
this: Elastic4sClient
with SearchConverterService
with SearchService
with ArticleIndexService
with ConverterService
with Props
with ErrorHandling =>
this: Elastic4sClient & SearchConverterService & SearchService & ArticleIndexService & ConverterService & Props &
ErrorHandling =>
val articleSearchService: ArticleSearchService

import props._
import props.*

class ArticleSearchService extends StrictLogging with SearchService[api.ArticleSummaryV2] {
private val noCopyright = boolQuery().not(termQuery("license", License.Copyrighted.toString))
Expand Down Expand Up @@ -158,7 +153,8 @@ trait ArticleSearchService {
}

override def scheduleIndexDocuments(): Unit = {
implicit val ec = ExecutionContext.fromExecutorService(Executors.newSingleThreadExecutor)
implicit val ec: ExecutionContextExecutorService =
ExecutionContext.fromExecutorService(Executors.newSingleThreadExecutor)
val f = Future {
articleIndexService.indexDocuments(None)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import scala.collection.mutable.ListBuffer
import scala.util.{Failure, Success, Try}

trait IndexService {
this: Elastic4sClient with BaseIndexService with Props with ArticleRepository =>
this: Elastic4sClient & BaseIndexService & Props & ArticleRepository =>

trait IndexService extends BaseIndexService with StrictLogging {
override val MaxResultWindowOption: Int = props.ElasticSearchIndexMaxResultWindow
Expand Down Expand Up @@ -124,20 +124,19 @@ trait IndexService {
* Sequence of FieldDefinitions for a field.
*/
protected def generateLanguageSupportedFieldList(fieldName: String, keepRaw: Boolean = false): Seq[ElasticField] = {
keepRaw match {
case true =>
languageAnalyzers.map(langAnalyzer =>
textField(s"$fieldName.${langAnalyzer.languageTag.toString}")
.fielddata(false)
.analyzer(langAnalyzer.analyzer)
.fields(keywordField("raw"))
)
case false =>
languageAnalyzers.map(langAnalyzer =>
textField(s"$fieldName.${langAnalyzer.languageTag.toString}")
.fielddata(false)
.analyzer(langAnalyzer.analyzer)
)
if (keepRaw) {
languageAnalyzers.map(langAnalyzer =>
textField(s"$fieldName.${langAnalyzer.languageTag.toString}")
.fielddata(false)
.analyzer(langAnalyzer.analyzer)
.fields(keywordField("raw"))
)
} else {
languageAnalyzers.map(langAnalyzer =>
textField(s"$fieldName.${langAnalyzer.languageTag.toString}")
.fielddata(false)
.analyzer(langAnalyzer.analyzer)
)
}
}

Expand Down Expand Up @@ -167,13 +166,13 @@ trait IndexService {
pathMatch = Some(name)
)
})
val catchAlltemplate = DynamicTemplateRequest(
val catchAllTemplate = DynamicTemplateRequest(
name = fieldName,
mapping = textField(fieldName).analyzer(SearchLanguage.standardAnalyzer).fields(fields.toList),
matchMappingType = Some("string"),
pathMatch = Some(s"$fieldName.*")
)
languageTemplates ++ Seq(catchAlltemplate)
languageTemplates ++ Seq(catchAllTemplate)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ package no.ndla.articleapi.service.search

import com.typesafe.scalalogging.StrictLogging
import no.ndla.articleapi.model.api.{ArticleSummaryV2, SearchResultV2}
import no.ndla.articleapi.model.search._
import no.ndla.articleapi.model.search.*
import no.ndla.articleapi.service.ConverterService
import no.ndla.common.model.domain.article.Article
import no.ndla.search.SearchLanguage.languageAnalyzers
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@

package no.ndla.articleapi.service.search

import com.sksamuel.elastic4s.ElasticDsl._
import com.sksamuel.elastic4s.ElasticDsl.*
import com.sksamuel.elastic4s.RequestFailure
import com.sksamuel.elastic4s.requests.searches.SearchResponse
import com.sksamuel.elastic4s.requests.searches.sort.{FieldSort, SortOrder}
import com.typesafe.scalalogging.StrictLogging
import no.ndla.articleapi.Props
import no.ndla.articleapi.model.domain._
import no.ndla.articleapi.model.domain.*
import no.ndla.articleapi.model.search.SearchResult
import no.ndla.articleapi.service.ConverterService
import no.ndla.language.Language.{AllLanguages, NoLanguage}
Expand All @@ -24,7 +24,7 @@ import java.lang.Math.max
import scala.util.{Failure, Success, Try}

trait SearchService {
this: Elastic4sClient with ConverterService with Props =>
this: Elastic4sClient & ConverterService & Props =>

trait SearchService[T] extends StrictLogging {
val searchIndex: String
Expand Down Expand Up @@ -126,7 +126,7 @@ trait SearchService {
case NdlaSearchException(_, Some(RequestFailure(status, _, _, _)), _, _) if status == 404 =>
logger.error(s"Index $searchIndex not found. Scheduling a reindex.")
scheduleIndexDocuments()
Failure(new IndexNotFoundException(s"Index $searchIndex not found. Scheduling a reindex"))
Failure(IndexNotFoundException(s"Index $searchIndex not found. Scheduling a reindex"))
case e: NdlaSearchException[?] =>
logger.error(e.getMessage)
Failure(NdlaSearchException(s"Unable to execute search in $searchIndex", e))
Expand Down
4 changes: 2 additions & 2 deletions article-api/src/test/scala/no/ndla/articleapi/TestData.scala
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@
package no.ndla.articleapi

import no.ndla.articleapi.model.api
import no.ndla.articleapi.model.domain._
import no.ndla.articleapi.model.domain.*
import no.ndla.common.configuration.Constants.EmbedTagName
import no.ndla.common.model
import no.ndla.common.model.NDLADate
import no.ndla.common.model.domain.article.{Article, Copyright}
import no.ndla.common.model.domain._
import no.ndla.common.model.domain.*
import no.ndla.mapping.License

trait TestData {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ trait TestEnvironment
val internController: InternController = mock[InternController]
val articleControllerV2: ArticleControllerV2 = mock[ArticleControllerV2]

val healthController = mock[TapirHealthController]
val healthController: TapirHealthController = mock[TapirHealthController]

val dataSource: HikariDataSource = mock[HikariDataSource]
val articleRepository: ArticleRepository = mock[ArticleRepository]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ package no.ndla.articleapi.controller

import no.ndla.articleapi.{TestEnvironment, UnitSuite}
import no.ndla.tapirtesting.TapirControllerTest
import sttp.client3.quick._
import sttp.client3.quick.*

class HealthControllerTest extends UnitSuite with TestEnvironment with TapirControllerTest {
override val controller: TapirHealthController = new TapirHealthController()
Expand Down
Loading

0 comments on commit ab69e82

Please sign in to comment.