1. Laborator 4 cacheAgeda Service.kt package com.sd.laborator.interfaces import com.sd.laborator.pojo.Person interface cacheAgendaService { fun getPerson(id: Int) : Person? fun createPerson(person: Person) fun deletePerson(id: Int) fun updatePerson(id: Int, person: Person) } P e rson. kt package com.sd.laborator.pojo import java.sql.Time import java.time.LocalDateTime data class Person( var id: Int = 0, var lastName: String = "", var firstName: Strin g = "", var telephoneNumber: String = "", var date_created: LocalDateTime = LocalDateTime.now() ) cacheAgendaServiceImpl.kt package com.sd.laborator.services; import com.sd.laborator.interfaces.cacheAgendaService import com.sd.laborator.pojo.Person import org.springframework.stereotype.Service import java.time.LocalDateTime import java.time.temporal.ChronoUnit import java.util.concurrent.ConcurrentHashMap @Service class cacheAgendaServiceImpl : cacheAgendaService { companion object { val initialAgenda = arrayOf( Person(1, "Hello", "Kotlin", "1234"), Person(2, "Hello", "Spring", "5678"), Person(3, "Hello", "Microservice", "9101112") ) } private val age nda = ConcurrentHashMap<Int, Person>( initialAgenda.associateBy { person: Person - > person.id } ) override fun getPerson(id: Int): Person? { for(contact in agenda) // verificare cache si stergere daca { if(conta ct.value.date_created.until(LocalDateTime.now(), ChronoUnit.MINUTES) >= 1) deletePerson(contact.value.id) } agenda[id]?.date_created = LocalDateTime.now() return agenda[id] } override fun createPerson(person: Person) { for(contact in agenda) // verificare cache si stergere daca { if(contact.value.date_created.until(LocalDateTime.now(), ChronoUnit.MINUTES) >= 1) deletePerson(contac t.value.id) } agenda[person.id]?.date_created = LocalDateTime.now() agenda[person.id] = person } override fun deletePerson(id: Int) { agenda.remove(id) } override fun updatePerson(id: Int, person: Person) { for(contact in agenda) // verificare cache si stergere daca { if(contact.value.date_created.until(LocalDateTime.now(), ChronoUnit.MINUTES) >= 1) deletePerson(contact.value.id) } deletePerson(id ) createPerson(person) } } 2. Laborator 8 Heartbeat.kt package com.sd.laborator import java.io.BufferedReader import java.io.InputStreamReader import java.lang.Exception import java.lang.RuntimeException import java.net.ServerSocket import java.net.Socket import kotlin.concurrent.thread import kotlin.system.exitProcess class Heartbeat{ private lateinit var messageManagerSocket: Socket companion object Constants{ val MESSAGE_MANAGER_HOST = System.getenv("MESSAGE_MANA GER_HOST") ?: "localhost" const val MESSAGE_MANAGER_PORT = 1500 } private fun subscribeToMessageManager(){ try{ messageManagerSocket = Socket(MESSAGE_MANAGER_HOST, MESSAGE_MANAGER_PORT) messageManagerSocket. soTimeout = 3000 //pt a nu sta mai mult de 3 sec socket - ul println("M - am conectat la Message Manager!") }catch(e: Exception){ println("Nu m - am putut conecta la Message Manager!") exitProcess(1) } } fun run(){ subscribeToMessageManager() println("Se testeaza...") while(true){ try{ messageManagerSocket.getOutputStream().write(("ping \ n").toByteArray()) val messageManagerBufferedRead er = BufferedReader(InputStreamReader(messageManagerSocket.inputStream)) val receivedResponse = messageManagerBufferedReader.readLine() println("Am primit raspunsul: \ "$receivedResponse \ "") }catch (e:Exception){ println(e.message) println("Nu a venit niciun raspuns in timp util.") //Runtime.getRuntime().exec("java - jar F:/ManagerMicroservice/MessageManagerMicroservice - 1.0 - SNAPSHOT - jar - with - dependencies.jar") val serviceCallerSocket = Socket("localhost", 1777) serviceCallerSocket.getOutputStream().write("message_manager \ n".toByteArray()) serviceCallerSocket.close() println("Relansare MessageManager") Thread.sleep(3000) subscribeToMessageManager() } Thread.sleep(1000) } } } fun main(args: Array<String>){ val heartbeat = Heartbeat() heartbeat.run() } ServiceCaller.kt package com.sd.laborator import java.io.BufferedReader import java.io.InputStreamReader import java.lang.Exception import java.lang.RuntimeException import java.net.ServerSocket import java.net.Socket import kotlin.concurrent.thread import kotlin.system.e xitProcess class ServiceCaller{ private lateinit var serviceCallerServerSocket: ServerSocket companion object Constants{ const val SERVICE_CALLER_PORT = 1777 } fun run() { serviceCallerServerSocket = ServerSocket(1777) while (true) { try { println("Astept conexiunea cu heartbeat.") val heartbeatConnection = serviceCallerServerSocket.accept() println("Am facut conexiunea cu heartbeat.") val serviceCallerBufferedReader = BufferedReader(InputStreamReader(heartbeatConnection.inputStream)) val request = serviceCallerBufferedReader.readLine() println("Request de replicare: \ "$request \ "") if (request.contains("message_manager")) Runtime.getRuntime() .exec("java - jar /home/stefan/Documents/MessageManagerMicroservice - 1.0 - SNAPSHOT - jar - with - dependencies.jar") } catch (e: Exception) { println(e.message) } } } } fun main(args: Array<String>){ val serviceCaller = ServiceCaller() serviceCaller.run() } 3. Laborator 11 Service.kt package com.sd.laborator import java.util.* import javax.inject.Singleton @Singleton class Service { private val random_vect = Vector<Int>(100) fun calcul(seed: Long): List<Int> { val adt = Vector<Int>(100) for (i in 0 until 99) { random_vect.add((Math.random()*100).toInt()) adt.add(random_vect[i]*random_v ect[i]) } return adt } } 4. Laboratorul 11 S ervice.kt package com.sd.laborator import java.util.* import javax.inject.Singleton @Singleton class Service { private val random_vect1 = Vector<Int>(100) private val random_vect2 = Vector<Int>(100) fun calcul(seed: Long): Set<Int> { for (i in 0 until 99) { random_vect1.add((Math.random()*100).toInt()) random_vect2.add((Math.random()*100).toInt()) } val adt = random_vect1.union(random_vect2) return adt } } 5. Laboratorul 3 Controller.kt package com.sd.laborator.controllers import com.sd.laborator.interfaces.CityFileReaderInterface import com.sd.laborator.interfaces.FilterInterface import com.sd.laborator.interfaces.LocationSearchInterface impo rt com.sd.laborator.interfaces.WeatherForecastInterface import com.sd.laborator.pojo.WeatherForecastData import com.sd.laborator.services.* import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Controller import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestMapping import org.springframew ork.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.ResponseBody import java.io.File @Controller class WeatherAppController { @Autowired private lateinit var locationSearchService: LocationSearchInterface @Aut owired private lateinit var weatherForecastService: WeatherForecastInterface @RequestMapping("/getforecast/{location}", method = [RequestMethod.GET]) @ResponseBody fun getForecast(@PathVariable location: String): String { // se inc earca preluarea WOEID - ului locaţiei primite in URL val locationId = locationSearchService.getLocationId(location) // dacă locaţia nu a fost găsită, răspunsul va fi corespunzător if (locationId == - 1) { return "Nu s - au p utut gasi date meteo pentru cuvintele cheie \ "$location \ "!" } // pe baza ID - ului de locaţie, se interoghează al doilea serviciu care returnează datele meteo // încapsulate într - un obiect POJO val rawForecastData: WeatherForecastData = weatherForecastService.getForecastData(locationId) // fiind obiect POJO, funcţia toString() este suprascrisă pentru o afişare mai prietenoasă return rawForecastData.toString() } @ RequestMapping("/getforecast/file", method = [RequestMethod.GET]) @ResponseBody fun getForecastFromFile(): String { val filteredListGetterService = FilteredListGetterService(locationSearchService as LocationSearchService, weathe rForecastService as WeatherForecastService) return filteredListGetterService.get() + "<br><br><hr>" + LinearRegression(filteredListGetterService).getSlope() } } CityFileReaderI nterface .kt package com.sd.laborator.interfaces import java.io.File interface CityFileReaderI nterface { fun read(file: File): MutableList<String> } FilterInterface t.kt package com.sd.laborator.interfaces import com.sd.laborator.pojo.WeatherForecastData interface FilterInterface { fun execute(data: WeatherForecastData): Boolean } GetterServiceInterface .kt package com.sd.laborator.inter faces interface GetterServiceInterface { fun get(): String } TimeServiceInterface .kt package com.sd.laborator.interfaces interface TimeServiceInterface { fun getCurrentTime(): String } SERVICES CityFileReader.kt package com.sd.laborator.services import com.sd.laborator.interfaces.CityFileReaderInterface import java.io.File class CityFileReader : CityFileReaderInterface { var cities: MutableList<String> = mutableListOf() override fun read(file: File): MutableList<String> { file.fo rEachLine { cities.add(it) } return cities } } FilteredListGetterService .kt package com.sd.laborator.services import com.sd.laborator.interfaces.FilterInterface import com.sd.laborator.interfaces.GetterServiceInterface import com.sd.laborator.pojo.WeatherForecastData impor t java.io.File class FilteredListGetterService(var locationSearchService: LocationSearchService, var weatherForecastService: WeatherForecastService): GetterServiceInterface { val fileToRead = File("/home/stefan/Documents/Rezolvari Subiecte/5/citie s.txt") val citiesList = CityFileReader().read(fileToRead) val filteredCitiesList: MutableList<WeatherForecastData> = mutableListOf() val filtersList: List<FilterInterface> = listOf() // DE ADAUGAT FILTRE @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ override fun get(): String { citiesList.forEach{location - > val locationId = locationSearchService.getLocationId(loca tion) // dacă locaţia nu a fost găsită, răspunsul va fi corespunzător if (locationId == - 1) { return "Nu s - au putut gasi date meteo pentru cuvintele cheie \ "$location \ "!" } val rawForecastDa ta: WeatherForecastData = weatherForecastService.getForecastData(locationId) //se verifica fiecare filtru sa fie indeplinit var ok = 1 filtersList.forEach { filter - > if(!filter.execute(rawForecastData)) ok=0 } if(ok==1) filteredCitiesList.add(rawForecastData) } return filteredCitiesList.toString() } } LinearRegression.kt package com.sd.laborator.services class LinearRegression(var getterService: FilteredListGetterService) { fun getSlope(): Double { val n = getterService.filteredCitiesList.size var sumXY: Double = 0.0 var sumX: Double = 0.0 var sumY: Double = 0.0 var sumXsquare: Double = 0.0 getterService.filteredCitiesList.forEach { sumXY += it.minTemp*it.maxTemp sumX += it.minTemp sumY += it.maxTemp sumXsquare += it.minTemp * it.minTemp } return ((n*sumXY) - (sumX*sumY)) / ((n*sumXsquare) - sumXsquare) } } MaxTemp Filter.kt package com.sd.laborator.services import com.sd.laborator.interfaces.FilterInterface import com.sd.laborator.pojo.WeatherForecastData class MaxTempFilter: FilterInterface { overri de fun execute(data: WeatherForecastData): Boolean { if(data.maxTemp<25) return true return false } } MinTempFilter.kt package com.sd.laborator.services import com.sd.laborator.interfaces.FilterInterface import com.sd.laborator.pojo.WeatherForecastData class MinTempFilter: FilterInterface { override fun execute(data: WeatherForecastData): Boolean { if(data.minTemp>10) return true return false } } 6. Laboratorul 7 import java.io.BufferedReader import java.io.File import java.io.FileOutputStream import java.io.InputStreamReader import java.net.ServerSocket import java.net.Socket import java.net.SocketTimeoutException class ErrorKeeperServ ice { private var serverSocket: ServerSocket private val serviceConnections: MutableList<Socket> = mutableListOf() companion object Constants { const val PROCESSOR_PORT = 1750 } init { serverSocket = ServerSocket(PROCESSOR_PORT) serverSocket.setSoTimeout(30_000) println("NumberOfMessagesMicroservice se executa pe portul: ${serverSocket.localPort}") println("Se asteapta celelalte servicii sa se conecteze... ") while (true) { try { val serviceConnection = serverSocket.accept() serviceConnections.add(serviceConnection) // se citeste mesajul de la service de pe socketul TCP val bufferReader = BufferedReader(InputStreamReader(serviceConnection.inputStream)) val receivedMessage = bufferReader.readLine() // daca se primeste un mesaj gol (NULL), atunci inseamna ca cealalta parte a socket - ului a fost i nchisa if (receivedMessage == null) { // deci subscriber - ul respectiv a fost deconectat bufferReader.close() serviceConnection.close() println("Eroare: Bidder - u l ${serviceConnection.port} a fost deconectat.") } else { File("/home/stefan/Documents/Rezolvari Subiecte/6 okazii L7 de revenit/Okazii/statistici.txt").appendText(receivedMessage.toString() + ' \ n') } } catch (e: SocketTimeoutException) { // daca au trecut cele 20 secunde de la pornirea licitatiei, inseamna ca licitatia s - a incheiat // se emite semnalul Complete pentru a incheia fluxul de oferte println("finalul licitatiei") break } } } } fun main(args: Array<String>) { val errorKeeperMicroservice = ErrorKeeperService() } 7. L aborator 6