Laborator 3 BlackListController.kt package com.sd.laborator.controllers import com.sd.laborator.interfaces.BlacklistInterface import com.sd.laborator.services.BlacklistService import org.springframework.stereotype.Controller import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.ResponseBody @Controller class BlacklistController { val service: BlacklistInterface = B lacklistService() @RequestMapping(value = ["/blacklist"], method = [RequestMethod.GET]) @ResponseBody fun getBlacklist() = service.getBlacklist() } BlackListInterface.kt package com.sd.laborator.interfaces interface BlacklistInterface { f un getBlacklist(): String } FilterLocationInterface.kt package com.sd.laborator.interfaces interface FilterLocationInterface { fun getPermission(): Boolean } TimeInterface.kt package com.sd.laborator.interfaces interface TimeInterface { fun getCurrentTime():String } BlacklistService.kt package com.sd.laborator.services import com.sd.laborator.interfaces.BlacklistInterface import org.springframework.stereotype.Service import java.util.* @Service class BlacklistService: BlacklistInte rface { override fun getBlacklist(): String { return "[{ \ "country \ ": \ "RO \ "},{ \ "country \ ": \ "US \ "}]" } } FilterLocationService .kt package com.sd.laborator.services import com.sd.laborator.interfaces.BlacklistInterface import com.sd.laborato r.interfaces.FilterLocationInterface import org.json.JSONArray import org.json.JSONObject import org.springframework.stereotype.Service import java.net.URL import java.util.* @Service class FilterLocationService: FilterLocationInterface { override fun getPermission(): Boolean { val locationSearchURL = URL("http://localhost:8080/blacklist/") // preluare raspuns HTTP (se face cerere GET şi se preia conţinutul răspunsului sub formă de text) val rawResponse: String = locationSearchURL.readText() val jsonArray = JSONArray(rawResponse) val userCountry = Locale.getDefault().country; for (i in 0 until jsonArray.length()) { val item = jsonArray.getJSONObject(i ) val restrictedCountry = item.getString("country") if (restrictedCountry.equals(userCountry)) return false } return true } } OrchestratorInterface .kt package com.sd.laborator .interfaces interface OrchestratorInterface { fun getData(location: String): String } OrchestratorService .kt package com.sd.laborator.services import com.sd.laborator.interfaces.FilterLocationInterface import com.sd.laborator.interfaces.LocationSear chInterface import com.sd.laborator.interfaces.OrchestratorInterface import com.sd.laborator.interfaces.WeatherForecastInterface import com.sd.laborator.pojo.WeatherForecastData import org.springframework.beans.factory.annotation.Autowired import org.sprin gframework.stereotype.Service @Service class OrchestratorService: OrchestratorInterface{ @Autowired private lateinit var locationSearchService: LocationSearchInterface @Autowired private lateinit var weatherForecastService: WeatherForecast Interface @Autowired private lateinit var filterLocationService: FilterLocationInterface override fun getData(location: String): String { val locationId = locationSearchService.getLocationId(location) if (locationId == - 1) { return "Nu s - au putut gasi date meteo pentru cuvintele cheie \ "$location \ "!" } if (!filterLocationService.getPermission()) { return "Nu aveti dreptul sa accesati aceste resurse!" } val rawF orecastData: WeatherForecastData = weatherForecastService.getForecastData(locationId) return rawForecastData.toString() } } Laborator 4 Ex 1 LibraryAppComponent.kt package com.sd.laborator.components import com.sd.laborator.interfaces.BasicLibraryPrinter import com.sd.laborator.interfaces.LibraryDAO import com.sd.laborator.interfaces.LibraryPrinter import com.sd.laborator .model.Book import com.sd.laborator.model.Content import com.sd.laborator.services.CustomLibraryPrinterService import org.springframework.amqp.core.AmqpTemplate import org.springframework.amqp.rabbit.annotation.RabbitListener import org.springframework.bea ns.factory.annotation.Autowired import org.springframework.stereotype.Component import java.lang.Exception @Component class LibraryAppComponent { @Autowired private lateinit var libraryDAO: LibraryDAO @Autowired private lateinit var libra ryPrinter: BasicLibraryPrinter @Autowired private lateinit var connectionFactory: RabbitMqConnectionFactoryComponent private lateinit var amqpTemplate: AmqpTemplate @Autowired fun initTemplate() { this.amqpTemplate = connectionFactory.rabbitTemplate() } fun sendMessage(msg: String) { this.amqpTemplate.convertAndSend(connectionFactory.getExchange(), connectionFactory.getRoutingKey(), msg) } @RabbitListener(queues = [" \ ${libraryapp.rabbitmq.queue}"]) fun recieveMessage(msg: String) { // the result needs processing val processedMsg = (msg.split(",").map { it.toInt().toChar() }) .joinToString(separator="") print("Processed msg: $processedMsg \ n") if (processedMsg.contains('~')) { val commands = processedMsg.split('~') try { val (function, parameter) = commands[0].split(":") val format = commands[1].split(":")[1] val result: String? = when(function) { "find" - > customFind(parameter, format) else - > null } if (result != null) sendMessage(result) print("Result: $result \ n") } catch (e: Exception) { println(e) } } else { try { val (function, parameter) = processedMsg.split(":") val result: String? = when (function) { "print" - > customPrint(parameter) "find" - > customFind(parameter, "json") "add" - > { val par ameters = parameter.split(',') val title=parameters[0].split('=')[1] val author=parameters[1].split('=')[1] val publisher=parameters[2].split('=')[1] val conte nt=parameters[3].split('=')[1] addBook(Book(Content(author, content, title, publisher))) "Added book." } else - > null } if (result != null) sendMessage(result) print("Result: $result \ n") } catch (e: Exception) { println(e) } } } fun customPrint(format: String): String { return libraryPrinter.printBooks(libraryDAO.getBooks(), format) } fun customFind(searchParameter: String, format: String): String { val (field, value) = searchParameter.split("=") return when(field) { "author" - > this.libraryP rinter.printBooks(this.libraryDAO.findAllByAuthor(value), format) "title" - > this.libraryPrinter.printBooks(this.libraryDAO.findAllByTitle(value), format) "publisher" - > this.libraryPrinter.printBooks(this.libraryDAO.findAllByPublis her(value), format) else - > "Not a valid field" } } fun addBook(book: Book): Boolean { return try { this.libraryDAO.addBook(book) true } catch (e: Exception) { false } } } BasicLibraryPrinter .kt package com.sd.laborator.interfaces import com.sd.laborator.model.Book interface BasicLibraryPrinter { fun printBooks(books: Set<Book>, format: String): String fun printRaw(books: Set<Book>): String } XMLPrinter .kt package com.sd.laborator.interfaces import com.sd.laborator.model.Book interface XMLPrinter { fun printXML(books: Set<Book>): String } BasicLibraryPrinterService.kt package com.sd.laborator.services import com.sd.laborator.interfaces. BasicLibraryPrinter import com.sd.laborator.interfaces.LibraryPrinter import com.sd.laborator.model.Book import org.springframework.stereotype.Service @Service open class BasicLibraryPrinterService: BasicLibraryPrinter { override fun printBooks(books: Set<Book>, format: String): String { return when(format) { "raw" - > printRaw(books) else - > "Not implemented" } } override fun printRaw(books: Set<Book>): String { var content: String = "" books.forEach { content += "${it.name} \ n${it.author} \ n${it.publisher} \ n${it.content} \ n \ n" } return content } } CustomLibraryPrinterService.kt package com.sd.laborator.services impor t com.sd.laborator.interfaces.* import com.sd.laborator.model.Book import org.springframework.context.annotation.Primary import org.springframework.stereotype.Service @Service @Primary class CustomLibraryPrinterService: BasicLibraryPrinterService(), JSONP rinter, HTMLPrinter, XMLPrinter { override fun printBooks(books: Set<Book>, format: String): String { return when(format) { "raw" - > printRaw(books) "json" - > printJSON(books) "html" - > printHTML (books) "xml" - > printXML(books) else - > "Not implemented" } } override fun printRaw(books: Set<Book>): String { var content: String = "" books.forEach { content += "${it.name} \ n${it.auth or} \ n${it.publisher} \ n${it.content} \ n \ n" } return content } override fun printHTML(books: Set<Book>): String { var content: String = "<html><head><title>Libraria mea HTML</title></head><body>" books.forEach { content += "<p><h3>${it.name}</h3><h4>${it.author}</h4><h5>${it.publisher}</h5>${it.content}</p><br/>" } content += "</body></html>" return content } override fun printJSON(books: Set<Book>): String { var cont ent: String = "[ \ n" books.forEach { if (it != books.last()) content += " { \ "Titlu \ ": \ "${it.name} \ ", \ "Autor \ ": \ "${it.author} \ ", \ "Editura \ ": \ "${it.publisher} \ ", \ "Text \ ": \ "${it.content} \ "}, \ n" else content += " { \ "Titlu \ ": \ "${it.name} \ ", \ "Autor \ ": \ "${it.author} \ ", \ "Editura \ ": \ "${it.publisher} \ ", \ "Text \ ": \ "${it.content} \ "} \ n" } content += "] \ n" return content } override fun printXML(books: Set<Bo ok>): String { var content: String = "<bookstore> \ n" books.forEach { content += " \ t<book> \ n \ t \ t<title>${it.name}</title> \ n \ t \ t<author>${it.author}</author> \ n \ t \ t<publisher>${it.publis her}</publisher> \ n \ t \ t<content>${it.content}< /content> \ n \ t<book/> \ n" } content += "</bookstore>" return content } } Laborat or 6 LibraryPrinterController .kt package com.sd.laborator.presentation.controllers import com.sd.laborator.business.interfaces.ILibraryDAOService import com.sd.laborator.business.interfaces.ILibraryPrinterService import com.sd.laborator.business.models.Book import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Controller import org.springframework.web.bind.anno tation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.ResponseBody @Controller class LibraryPrinterController { @Au towired private lateinit var _libraryDAOService: ILibraryDAOService @Autowired private lateinit var _libraryPrinterService: ILibraryPrinterService @RequestMapping("/print", method = [RequestMethod.GET]) @ResponseBody fun customPr int(@RequestParam(required = true, name = "format", defaultValue = "") format: String): String { return when (format) { "html" - > _libraryPrinterService.printHTML(_libraryDAOService.getBooks() as Set<Book>) "json" - > _librar yPrinterService.printJSON(_libraryDAOService.getBooks() as Set<Book>) "raw" - > _libraryPrinterService.printRaw(_libraryDAOService.getBooks() as Set<Book>) else - > "Not implemented" } } @RequestMapping("/find", method = [RequestMethod.GET]) @ResponseBody fun customFind( @RequestParam(required = false, name = "author", defaultValue = "") author: String, @RequestParam(required = false, name = "title", defaultValu e = "") title: String, @RequestParam(required = false, name = "publisher", defaultValue = "") publisher: String ): String { if (author != "") { return this._libraryPrinterService.printJSON(this._libraryDAOService.findAllByAu thor(author) as Set<Book>) } if (title != "") { return this._libraryPrinterService.printJSON(this._libraryDAOService.findAllByTitle(title) as Set<Book>) } if (publisher != "") { return this._libraryPr interService.printJSON(this._libraryDAOService.findAllByPublisher(publisher) as Set<Book>) } return "Not a valid field" } @RequestMapping("/find - and - print", method = [RequestMethod.GET]) @ResponseBody fun findAndPrint( @RequestParam(required = false, name = "author", defaultValue = "") author: String, @RequestParam(required = false, name = "title", defaultValue = "") title: String, @RequestParam(required = false, name = "publisher", defaultValue = "") publisher: String, @RequestParam(required = true, name = "format", defaultValue = "") format: String ): String { if (author != "") { return when (format){ "json" - > this._libraryPrinterService.printJSON(this._libraryDAOService.findAllByAuthor(author) as Set<Book>) "html" - > this._libraryPrinterService.printHTML(this._libraryDAOService.findAllByAuthor(author) as Set<Book>) "raw" - > this. _libraryPrinterService.printRaw(this._libraryDAOService.findAllByAuthor(author) as Set<Book>) else - > return "" } } if (title != "") { return when (format){ "json" - > this._libraryPrin terService.printJSON(this._libraryDAOService.findAllByTitle(title) as Set<Book>) "html" - > this._libraryPrinterService.printHTML(this._libraryDAOService.findAllByTitle(title) as Set<Book>) "raw" - > this._libraryPrinterServic e.printRaw(this._libraryDAOService.findAllByTitle(title) as Set<Book>) else - > return "" } } if (publisher != "") { return when (format){ "json" - > this._libraryPrinterService.printJSO N(this._libraryDAOService.findAllByPublisher(publisher) as Set<Book>) "html" - > this._libraryPrinterService.printHTML(this._libraryDAOService.findAllByPublisher(publisher) as Set<Book>) "raw" - > this._libraryPrinterService.p rintRaw(this._libraryDAOService.findAllByPublisher(publisher) as Set<Book>) else - > return "" } } return "Not a valid field" } } Persistence Interfaces IBookRepository .kt package com.sd.laborator.persistence.interfaces import com.sd.laborator.business.models.Book interface IBookRepository { // Create fun createTable() fun add(book: Book) // Retrieve fun getAll(): MutableList<Book?> fun getByName(name: Str ing): MutableList<Book?> fun getByAuthor(author: String): MutableList<Book?> fun getByPublisher(publisher: String): MutableList<Book?> // Update fun update(book: Book) // Delete fun delete(name: String) } Mappers BookRowMapper .kt package com.sd.laborator.persistence.mappers import com.sd.laborator.business.models.Book import com.sd.laborator.business.models.Content import org.springframework.jdbc.core.RowMapper import java.sql.ResultSet import java.sql.SQLExceptio n class BookRowMapper : RowMapper<Book?> { @Throws(SQLException::class) override fun mapRow(rs: ResultSet, rowNum: Int): Book { return Book(rs.getInt("id"), Content(rs.getString("author"), rs.getString("text"),rs.getString("tit le"),rs.getString("publisher"), )) } } Repositories BookRepository .kt package com.sd.laborator.persistence.repositories import com.sd.laborator.business.models.Book import com.sd.laborator.persistence.interfaces.IBookRepository import com.sd.laborat or.persistence.mappers.BookRowMapper import org.springframework.beans.factory.annotation.Autowired import org.springframework.dao.EmptyResultDataAccessException import org.springframework.jdbc.UncategorizedSQLException import org.springframework.jdbc.core.JdbcTemplate import org.springframework.jdbc.core.RowMapper import org.springframework.stereotype.Repository @Repository class BookRepository: IBookRepository { @A utowired private lateinit var _jdbcTemplate: JdbcTemplate private var _rowMapper: RowMapper<Book?> = BookRowMapper() override fun createTable() { _jdbcTemplate.execute("""CREATE TABLE IF NOT EXISTS books( id INTEGER PRIMARY KEY AUTOINCREMENT, author VARCHAR(100), title VARCHAR(100) UNIQUE, publisher VARCHAR(100), text VARCHAR(100))""") } override fun add(book: Book) { try { _jdbcTemplate.update("INSERT INTO books(author, title, publisher, text) VALUES (?, ?, ?, ?)", book.author, book.name, book.publisher, book.co ntent) } catch (e: UncategorizedSQLException){ println("An error has occurred in ${this.javaClass.name}.add") } } override fun getAll(): MutableList<Book?> { return _jdbcTemplate.query("SELECT * FROM books", _rowMapper) } override fun getByName(name: String): MutableList<Book?> { return _jdbcTemplate.query("SELECT * FROM books WHERE title = '$name'", _rowMapper) } override fun getByAuthor(author: String): MutableList<Book?> { return _jdbcTemplate.query("SELECT * FROM books WHERE author = '$author'", _rowMapper) } override fun getByPublisher(publisher: String): MutableList<Book?> { return _jdbcTemplate.query("SELECT * FROM books WHERE publisher = '$publi sher'", _rowMapper) } override fun update(book: Book) { try {