Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

[feature] ERT news #11

Merged
merged 13 commits into from
Feb 14, 2024
49 changes: 49 additions & 0 deletions backend/src/main/kotlin/org/hikit/er/client/EventClient.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package org.hikit.er.client

import io.swagger.annotations.ApiParam
import org.apache.logging.log4j.LogManager
import org.ert.api.EventsApi
import org.openapitools.model.EventResponse
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.web.client.RestTemplateBuilder
import org.springframework.http.ResponseEntity
import org.springframework.stereotype.Component
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.client.RestClientException
import java.net.SocketTimeoutException
import javax.validation.Valid
import javax.validation.constraints.Max
import javax.validation.constraints.Min
import javax.validation.constraints.Size

@Component
class EventClient @Autowired constructor(
private val restTemplateBuilder: RestTemplateBuilder) : EventsApi {
private val logger = LogManager.getLogger(EventClient::class.java)

@Value("\${endpoint.event:https://emiliaromagnaturismo.it/opendata/v1/events}") lateinit var endPointUrl: String
override fun eventsGet(@Size(max = 2) @ApiParam(value = "Lingua") @Valid @RequestParam(required = false, value = "lang") lang: @Size(max = 2) @Valid String?,
@Size(max = 6) @ApiParam(value = "Codice Istat identificativo del comune") @Valid @RequestParam(required = false, value = "istat") istat: @Size(max = 6) @Valid String?,
@Size(max = 255) @ApiParam(value = "Filtro per nome della città, consulta l'endpoint dei comuni per l'elenco di province e comuni supportati") @Valid @RequestParam(required = false, value = "city") query: @Size(max = 255) @Valid String?,
@Size(max = 2) @ApiParam(value = "Filtro per nome della provincia, consulta l'endpoint dei comuni per l'elenco di province e comuni supportati") @Valid @RequestParam(required = false, value = "prov") prov: @Size(max = 2) @Valid String?,
@Size(max = 6) @ApiParam(value = "Codice del tematismo per il quale filtrare") @Valid @RequestParam(required = false, value = "theme") theme: @Size(max = 6) @Valid String?,
@Size(max = 6) @ApiParam(value = "Codice della categoria per la quale filtrare") @Valid @RequestParam(required = false, value = "category") category: @Size(max = 6) @Valid String?,
@Min(value = 1) @Max(value = 99999999) @ApiParam(value = "Numero di pagina da interrogare") @Valid @RequestParam(required = false, value = "page") page: @Min(value = 1) @Max(value = 99999999) @Valid Int?,
@Min(value = -1) @Max(value = 1000) @ApiParam(value = "Numero di risultati da restituire per ogni pagina") @Valid @RequestParam(required = false, value = "limit") limit: @Min(value = -1) @Max(value = 1000) @Valid Int?,
@Size(max = 23) @ApiParam(value = "Data di aggiornamento. Vengono restituiti tutti i contenuti che siano stati modificati dopo la data inserita. La data va inserita in formato [rfc3339](https://www.ietf.org/rfc/rfc3339.txt)") @Valid @RequestParam(required = false, value = "updated") updated: @Size(max = 23) @Valid String?): ResponseEntity<EventResponse>? {
try {
logger.info("Fetching PROV=${prov} LIMIT=${limit} PAGE=${page}")
return restTemplateBuilder.build()
.getForEntity(
endPointUrl.plus("?prov=${prov}&limit=${limit}&page=${page}"),
org.openapitools.model.EventResponse::class.java
)
} catch (socketConnectionTimeout: SocketTimeoutException) {
logger.warn("The remote API timed-out, will retry on the next run")
} catch (restClientException : RestClientException) {
logger.warn("The remote locality API responded with an error", restClientException.cause)
}
return null
}
}
4 changes: 2 additions & 2 deletions backend/src/main/kotlin/org/hikit/er/client/LocalityClient.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package org.hikit.er.client

import org.apache.logging.log4j.LogManager
import org.ert.api.LocalitiesApi
import org.openapitools.model.LocalityResponse
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.web.client.RestTemplateBuilder
Expand All @@ -25,7 +26,7 @@ class LocalityClient @Autowired constructor(
page: Int?,
updated: String?,
query: String?
): ResponseEntity<org.openapitools.model.LocalityResponse>? {
): ResponseEntity<LocalityResponse>? {
try {
logger.info("Fetching PROV=${prov} LIMIT=${limit} PAGE=${page}")
return restTemplateBuilder.build()
Expand All @@ -38,7 +39,6 @@ class LocalityClient @Autowired constructor(

} catch (restClientException : RestClientException) {
logger.error("The remote locality API responded with an error", restClientException.cause)

}
return null
}
Expand Down
59 changes: 59 additions & 0 deletions backend/src/main/kotlin/org/hikit/er/controller/EventController.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package org.hikit.er.controller

import io.swagger.v3.oas.annotations.Operation
import org.hikit.common.ControllerConstants.*
import org.hikit.er.controller.response.EventsResponseHelper
import org.hikit.er.rest.response.EventResponse
import org.hikit.er.service.EventService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*

@RestController
@RequestMapping(EventController.PREFIX)
class EventController @Autowired constructor(
private val eventService: EventService,
private val eventResponseHelper: EventsResponseHelper
) {
companion object {
const val PREFIX = "/event"
}

@Operation(summary = "Retrieve events by ISTAT code")
@GetMapping("/{istatCode}")
fun getByIstat(
@PathVariable istatCode: String,
@RequestParam(required = false, defaultValue = MIN_DOCS_ON_READ) skip: Int,
@RequestParam(required = false, defaultValue = MAX_DOCS_ON_READ) limit: Int
):
EventResponse {
val internalResponse = eventService.getByIstat(istatCode, skip, limit)
return eventResponseHelper.constructResponse(
emptySet(),
internalResponse.data,
internalResponse.totalCount,
skip, limit
)
}


// @Operation(summary = "Retrieve localities by distance from a point")
// @GetMapping
// operator fun get(
// @RequestParam(required = false, defaultValue = MIN_DOCS_ON_READ) skip: Int,
// @RequestParam(required = false, defaultValue = MAX_DOCS_ON_READ) limit: Int,
// @RequestParam(required = true) latitude: Double,
// @RequestParam(required = true) longitude: Double,
// @RequestParam(required = true) distance: Double
// ): LocalityResponse {
// val internalResponse = localityService.get(skip, limit, Coordinates(latitude, longitude), distance)
// return localityResponseHelper
// .constructResponse(
// emptySet(),
// internalResponse.data,
// internalResponse.totalCount,
// skip, limit
// )
// }


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package org.hikit.er.controller.response

import org.hikit.common.response.ControllerPagination
import org.hikit.er.rest.EventDto
import org.hikit.er.rest.response.EventResponse
import org.hikit.er.rest.response.Status
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

@Component
class EventsResponseHelper @Autowired constructor(private val controllerPagination: ControllerPagination) {
fun constructResponse(
errors: Set<String>,
dtos: List<EventDto>,
totalCount: Int,
skip: Int,
limit: Int
): EventResponse {
val totalCountLong = totalCount.toLong()
return if (errors.isNotEmpty()) {
EventResponse(
Status.ERROR, errors, dtos, 1L,
1, limit.toLong(), totalCountLong
)
} else EventResponse(
Status.OK, errors, dtos,
controllerPagination.getCurrentPage(skip, limit),
controllerPagination.getTotalPages(totalCountLong, limit),
limit.toLong(),
totalCountLong
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import org.springframework.stereotype.Component

@Component
class LocalityResponseHelper @Autowired constructor(private val controllerPagination: ControllerPagination){

fun constructResponse(
errors: Set<String>,
dtos: List<LocalityDto>,
Expand Down
47 changes: 47 additions & 0 deletions backend/src/main/kotlin/org/hikit/er/data/dao/EventDao.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package org.hikit.er.data.dao

import com.mongodb.client.MongoCollection
import com.mongodb.client.model.FindOneAndReplaceOptions
import com.mongodb.client.model.ReturnDocument
import org.bson.Document
import org.hikit.common.datasource.Datasource
import org.hikit.common.datasource.DocumentListMapperHelper
import org.hikit.er.data.CityRef
import org.hikit.er.data.Event
import org.hikit.er.data.mapper.EventEntityMapper
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

@Component
class EventDao @Autowired constructor(
private val eventEntityMapper: EventEntityMapper,
private val documentListMapperHelper: DocumentListMapperHelper<Event>,
dataSource: Datasource
) {
private val collection: MongoCollection<Document> = dataSource.db.getCollection(Event.COLLECTION_NAME)

fun upsertOnRemoteId(events: List<Event>): List<Event> = events.map {
val eventDocument = eventEntityMapper.mapToDocument(it)
collection.findOneAndReplace(
Document(Event.REMOTE_ID, it.remoteId),
eventDocument,
FindOneAndReplaceOptions()
.upsert(true)
.returnDocument(ReturnDocument.AFTER)
)
}.map {
eventEntityMapper.mapToObject(it!!)
}

fun getByIstatCode(istat: String, skip: Int, limit: Int): List<Event> {
val documents = collection.find(Document(Event.MUNICIPALITY + "." + CityRef.ISTAT, istat))
.limit(limit).skip(skip)
return documentListMapperHelper.toEntries(documents, eventEntityMapper)
}

fun countByIstat(istat: String): Int =
collection.countDocuments(
Document(Event.MUNICIPALITY + "." + CityRef.ISTAT, istat))
.toInt()

}
2 changes: 0 additions & 2 deletions backend/src/main/kotlin/org/hikit/er/data/dao/LocalityDao.kt
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,4 @@ class LocalityDao @Autowired constructor(
distance
),
).count()


}
20 changes: 20 additions & 0 deletions backend/src/main/kotlin/org/hikit/er/data/dao/MunicipalityDao.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import org.bson.Document
import org.hikit.common.datasource.Datasource
import org.hikit.common.datasource.DocumentListMapperHelper
import org.hikit.er.controller.request.LineRequest
import org.hikit.er.data.Coordinates
import org.hikit.er.data.Municipality
import org.hikit.er.data.mapper.MunicipalityEntityMapper
import org.springframework.beans.factory.annotation.Autowired
Expand Down Expand Up @@ -56,4 +57,23 @@ class MunicipalityDao @Autowired constructor(
)
return documentListMapperHelper.toEntries(documents, municipalityEntityMapper)
}

fun getByPoint(point: Coordinates): List<Municipality> {
val query = Document(
Municipality.GEOMETRY,
Document(
"\$geoIntersects",
Document(
"\$geometry",
Document(
"type", "Point"
).append("coordinates", listOf(point.longitude, point.latitude))
)
)
)
val documents = collection.find(
query
)
return documentListMapperHelper.toEntries(documents, municipalityEntityMapper)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package org.hikit.er.data.mapper

import org.hikit.er.data.CityRef
import org.hikit.er.rest.CityRefDto
import org.hikit.er.rest.ContactDto
import org.hikit.er.rest.CoordinatesDto
import org.hikit.er.rest.IatDto
import org.springframework.stereotype.Component

@Component
class CityRefMapperDto {
fun map(cityRef: CityRef) =
CityRefDto(
istat = cityRef.istat,
city = cityRef.city,
province = cityRef.province,
province_short = cityRef.province_short,
iat = cityRef.iat.map {
IatDto(
name = it.name,
address = it.address,
number = it.number,
CoordinatesDto(
it.coordinates.longitude,
it.coordinates.latitude
),
it.contacts.map { c -> ContactDto(c.label, c.type, c.value) }
)
}
)
}
56 changes: 56 additions & 0 deletions backend/src/main/kotlin/org/hikit/er/data/mapper/EventMapperDto.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package org.hikit.er.data.mapper

import org.hikit.er.data.Event
import org.hikit.er.rest.*
import org.springframework.stereotype.Component

@Component
class EventMapperDto constructor(private val cityRefMapperDto: CityRefMapperDto){
fun map(ev: Event): EventDto =
EventDto(
ev.remoteId,
ev.title,
ev.description,
ev.locations.map {
EventLocationDto(
it.title,
it.city,
it.province,
it.address,
CoordinatesDto(
it.coordinates.longitude,
it.coordinates.latitude
)
)
},
ev.date_from,
ev.date_to,
TicketDto(
ev.ticketing.website,
ev.ticketing.subscriptions,
ev.ticketing.full_rate,
ev.ticketing.gratuity,
ev.ticketing.type,
ev.ticketing.entrance
),
ev.category.map {
CategoryDto(
it._id,
it.name,
it.parent
)
},
cityRefMapperDto.map(ev.municipality),
ev.attachments.map {
ImageDto(
it.url,
it.title,
it.name,
it.width,
it.height,
it.license,
it.licenseUrl
)
}
)
}
Loading
Loading