├── .gitignore ├── LICENSE ├── README.md ├── build.gradle ├── buildSrc └── src │ ├── build.gradle │ └── main │ └── java │ └── Versions.java ├── cbrRate ├── HttpRequests.http ├── build.gradle ├── jib.gradle └── src │ ├── main │ ├── java │ │ └── ru │ │ │ └── cbrrate │ │ │ ├── CbrRate.java │ │ │ ├── config │ │ │ ├── ApplicationConfig.java │ │ │ ├── CbrConfig.java │ │ │ └── JsonConfig.java │ │ │ ├── controller │ │ │ └── CurrencyRateController.java │ │ │ ├── model │ │ │ ├── CachedCurrencyRates.java │ │ │ └── CurrencyRate.java │ │ │ ├── parser │ │ │ ├── CurrencyRateParser.java │ │ │ ├── CurrencyRateParserXml.java │ │ │ └── CurrencyRateParsingException.java │ │ │ ├── requester │ │ │ ├── CbrRequester.java │ │ │ ├── CbrRequesterImpl.java │ │ │ └── RequesterException.java │ │ │ └── services │ │ │ ├── CurrencyRateNotFoundException.java │ │ │ └── CurrencyRateService.java │ └── resources │ │ └── application.yml │ └── test │ ├── java │ └── ru │ │ └── cbrrate │ │ ├── controller │ │ └── CurrencyRateControllerTest.java │ │ └── parser │ │ └── CurrencyRateParserXmlTest.java │ └── resources │ └── cbr_response.xml ├── currencyRateBotRequestConsumer ├── HttpRequests.http ├── build.gradle ├── jib.gradle └── src │ ├── main │ ├── java │ │ └── ru │ │ │ └── cbrrate │ │ │ ├── CurrencyRateBotRequestConsumer.java │ │ │ ├── clients │ │ │ ├── HttpClient.java │ │ │ ├── HttpClientException.java │ │ │ ├── HttpClientJdk.java │ │ │ ├── TelegramClient.java │ │ │ └── TelegramClientImpl.java │ │ │ ├── config │ │ │ ├── ApplicationConfig.java │ │ │ ├── JsonConfig.java │ │ │ ├── KafkaConfig.java │ │ │ ├── SchedulingConfig.java │ │ │ └── TelegramClientConfig.java │ │ │ ├── model │ │ │ ├── GetUpdatesRequest.java │ │ │ └── GetUpdatesResponse.java │ │ │ └── services │ │ │ ├── BotException.java │ │ │ ├── DateTimeProvider.java │ │ │ ├── DateTimeProviderCurrent.java │ │ │ ├── KafkaMessageSender.java │ │ │ ├── LastUpdateIdKeeper.java │ │ │ ├── LastUpdateIdKeeperImpl.java │ │ │ ├── MessageSender.java │ │ │ ├── TelegramException.java │ │ │ ├── TelegramService.java │ │ │ └── TelegramServiceImpl.java │ └── resources │ │ └── application.yml │ └── test │ └── java │ └── ru │ └── cbrrate │ └── services │ ├── KafkaBase.java │ ├── TelegramClientTest.java │ └── TelegramServiceImplTest.java ├── currencyRateBotResponseProvider ├── HttpRequests.http ├── build.gradle ├── jib.gradle └── src │ ├── main │ ├── java │ │ └── ru │ │ │ └── cbrrate │ │ │ ├── CurrencyRateBotResponseProvider.java │ │ │ ├── clients │ │ │ ├── CurrencyRateClient.java │ │ │ ├── CurrencyRateClientException.java │ │ │ ├── CurrencyRateClientImpl.java │ │ │ ├── HttpClient.java │ │ │ ├── HttpClientException.java │ │ │ ├── HttpClientJdk.java │ │ │ ├── HttpClientReactive.java │ │ │ ├── HttpClientReactiveWeb.java │ │ │ ├── TelegramClient.java │ │ │ └── TelegramClientImpl.java │ │ │ ├── config │ │ │ ├── ApplicationConfig.java │ │ │ ├── CurrencyRateClientConfig.java │ │ │ ├── JsonConfig.java │ │ │ ├── KafkaConfig.java │ │ │ └── TelegramClientConfig.java │ │ │ ├── model │ │ │ ├── CurrencyRate.java │ │ │ ├── GetUpdatesResponse.java │ │ │ ├── MessageTextProcessorResult.java │ │ │ └── SendMessageRequest.java │ │ │ └── services │ │ │ ├── BotException.java │ │ │ ├── DateTimeProvider.java │ │ │ ├── DateTimeProviderCurrent.java │ │ │ ├── TelegramException.java │ │ │ ├── TelegramMessageProcessor.java │ │ │ ├── TelegramMessageProcessorImpl.java │ │ │ └── processors │ │ │ ├── CmdRegistry.java │ │ │ ├── MessageTextProcessor.java │ │ │ ├── MessageTextProcessorGeneral.java │ │ │ ├── MessageTextProcessorRate.java │ │ │ ├── MessageTextProcessorStart.java │ │ │ └── Messages.java │ └── resources │ │ ├── application-local.yml │ │ ├── application-prod.yml │ │ └── application.yml │ └── test │ └── java │ └── ru │ └── cbrrate │ └── services │ ├── KafkaBase.java │ ├── MessageTextProcessorRateTest.java │ ├── TelegramClientTest.java │ └── TelegramMessageProcessorImplTest.java ├── currencyRateBotStatistics ├── HttpRequests.http ├── build.gradle ├── jib.gradle └── src │ ├── main │ ├── java │ │ └── ru │ │ │ └── cbrrate │ │ │ ├── CurrencyRateBotStatistics.java │ │ │ ├── config │ │ │ ├── JsonConfig.java │ │ │ └── KafkaConfig.java │ │ │ ├── model │ │ │ ├── CurrencyRate.java │ │ │ ├── GetUpdatesResponse.java │ │ │ ├── MessageTextProcessorResult.java │ │ │ └── SendMessageRequest.java │ │ │ └── services │ │ │ ├── BotException.java │ │ │ ├── DateTimeProvider.java │ │ │ ├── DateTimeProviderCurrent.java │ │ │ ├── TelegramRequestStatisticsProcessor.java │ │ │ └── TelegramRequestStatisticsProcessorImpl.java │ └── resources │ │ └── application.yml │ └── test │ └── java │ └── ru │ └── cbrrate │ └── services │ ├── KafkaBase.java │ └── TelegramRequestStatisticsProcessorImplTest.java ├── currencyRateClient ├── HttpRequests.http ├── build.gradle ├── jib.gradle └── src │ ├── main │ ├── java │ │ └── ru │ │ │ └── cbrrate │ │ │ ├── CurrencyRateClient.java │ │ │ ├── clients │ │ │ ├── CbrRateClient.java │ │ │ ├── HttpClient.java │ │ │ ├── HttpClientException.java │ │ │ ├── HttpClientJdk.java │ │ │ ├── RateClient.java │ │ │ └── RateClientException.java │ │ │ ├── config │ │ │ ├── ApplicationConfig.java │ │ │ ├── CbrRateClientConfig.java │ │ │ └── JsonConfig.java │ │ │ ├── controller │ │ │ ├── CurrencyRateEndpointController.java │ │ │ └── ExceptionHandlingController.java │ │ │ ├── model │ │ │ ├── CurrencyRate.java │ │ │ └── RateType.java │ │ │ └── services │ │ │ ├── CurrencyRateEndpointService.java │ │ │ └── CurrencyRateNotFoundException.java │ └── resources │ │ ├── application-local.yml │ │ ├── application-prod.yml │ │ └── application.yml │ └── test │ └── java │ └── ru │ └── cbrrate │ └── controller │ └── CurrencyRateEndpointControllerTest.java ├── docker └── docker-compose.yml ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── kube ├── cbrRate │ ├── deployment_cbr-rate.yaml │ └── service_cbr-rate.yaml ├── config │ └── currency-rate-config.yaml ├── currencyRateBot │ ├── deployment_currency-rate-bot.yaml │ └── service_currency-rate-bot.yaml └── currencyRateClient │ ├── deployment_currency-rate-client.yaml │ ├── ingress_currency-rate-client.yaml │ └── service_currency-rate-client.yaml └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | !gradle-wrapper.jar 16 | *.war 17 | *.nar 18 | *.ear 19 | *.zip 20 | *.tar.gz 21 | *.rar 22 | 23 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 24 | hs_err_pid* 25 | 26 | # Ignore Gradle project-specific cache directory 27 | .gradle 28 | /buildSrc/.gradle/ 29 | 30 | # Ignore Gradle build output directory 31 | build 32 | out 33 | 34 | #Idea 35 | *.iml 36 | *.iws 37 | *.ipr 38 | *.idea 39 | 40 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Sergey Petrelevich 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # currency-rate -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'idea' 3 | id 'io.spring.dependency-management' version "1.0.11.RELEASE" 4 | id 'org.springframework.boot' version '2.6.1' apply false 5 | id 'com.google.cloud.tools.jib' version '3.1.4' apply false 6 | } 7 | 8 | idea { 9 | project { 10 | languageLevel = 17 11 | } 12 | module { 13 | downloadJavadoc = true 14 | downloadSources = true 15 | } 16 | } 17 | 18 | allprojects { 19 | group "ru.petrelevich" 20 | 21 | repositories { 22 | mavenCentral() 23 | } 24 | 25 | apply plugin: "io.spring.dependency-management" 26 | dependencyManagement { 27 | dependencies { 28 | imports { 29 | mavenBom("org.springframework.boot:spring-boot-dependencies:2.6.1") 30 | } 31 | dependency "io.projectreactor:reactor-test:${Versions.reactorTest}" 32 | dependency "org.testcontainers:junit-jupiter:${Versions.testcontainers}" 33 | dependency "org.testcontainers:kafka:${Versions.testcontainers}" 34 | } 35 | } 36 | 37 | configurations.all { 38 | resolutionStrategy { 39 | failOnVersionConflict() 40 | } 41 | } 42 | 43 | task managedVersions { 44 | doLast { 45 | dependencyManagement.managedVersions.each { 46 | println it 47 | } 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /buildSrc/src/build.gradle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/petrelevich/currency-rate/021573f97874016576e30e4c0d4fafb315b4efa9/buildSrc/src/build.gradle -------------------------------------------------------------------------------- /buildSrc/src/main/java/Versions.java: -------------------------------------------------------------------------------- 1 | public interface Versions { 2 | String reactorTest = "3.1.0.RELEASE"; 3 | String testcontainers = "1.16.2"; 4 | } 5 | -------------------------------------------------------------------------------- /cbrRate/HttpRequests.http: -------------------------------------------------------------------------------- 1 | ### 2 | GET http://localhost:8081/api/v1/currencyRate/EUR/02-03-2021 3 | Accept: */* 4 | Content-Type: application/json 5 | Cache-Control: no-cache 6 | 7 | ### 8 | GET http://localhost:8091/actuator/health 9 | Accept: */* 10 | Content-Type: application/json 11 | Cache-Control: no-cache 12 | 13 | ### 14 | GET http://localhost:8091/actuator/health/liveness 15 | Accept: */* 16 | Content-Type: application/json 17 | Cache-Control: no-cache 18 | 19 | ### 20 | GET http://localhost:8091/actuator/health/readiness 21 | Accept: */* 22 | Content-Type: application/json 23 | Cache-Control: no-cache 24 | -------------------------------------------------------------------------------- /cbrRate/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.springframework.boot' 4 | id 'com.google.cloud.tools.jib' 5 | } 6 | 7 | apply from: 'jib.gradle' 8 | 9 | sourceCompatibility = JavaVersion.VERSION_17 10 | targetCompatibility = JavaVersion.VERSION_17 11 | 12 | dependencies { 13 | implementation 'org.springframework.boot:spring-boot-starter-webflux' 14 | implementation 'org.springframework.boot:spring-boot-starter-actuator' 15 | implementation 'ch.qos.logback:logback-classic' 16 | implementation 'org.ehcache:ehcache' 17 | 18 | 19 | compileOnly 'org.projectlombok:lombok' 20 | testCompileOnly 'org.projectlombok:lombok' 21 | annotationProcessor 'org.projectlombok:lombok' 22 | 23 | testImplementation('org.springframework.boot:spring-boot-starter-test') 24 | } 25 | 26 | test { 27 | useJUnitPlatform() 28 | testLogging { 29 | events "passed", "skipped", "failed" 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /cbrRate/jib.gradle: -------------------------------------------------------------------------------- 1 | jib { 2 | container.creationTime = 'USE_CURRENT_TIMESTAMP' 3 | from { 4 | image = 'bellsoft/liberica-openjdk-alpine-musl:17.0.1-12' 5 | } 6 | to { 7 | tags = ['v1', 'latest'] 8 | image = 'registry.gitlab.com/petrelevich/dockerregistry/cbr-rate' 9 | auth { 10 | username = gitlabUser 11 | password = gitlabPassword 12 | } 13 | } 14 | } 15 | // ./gradlew jibDockerBuild 16 | 17 | //docker login registry.gitlab.com 18 | //docker run -p 8080:8080 registry.gitlab.com/petrelevich/dockerregistry/cbr-rate 19 | 20 | //docker push registry.gitlab.com/petrelevich/dockerregistry/cbr-rate:latest 21 | -------------------------------------------------------------------------------- /cbrRate/src/main/java/ru/cbrrate/CbrRate.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate; 2 | 3 | 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.boot.builder.SpringApplicationBuilder; 6 | 7 | 8 | 9 | @SpringBootApplication 10 | public class CbrRate { 11 | public static void main(String[] args) { 12 | new SpringApplicationBuilder().sources(CbrRate.class).run(args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /cbrRate/src/main/java/ru/cbrrate/config/ApplicationConfig.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.config; 2 | 3 | import org.ehcache.Cache; 4 | import org.ehcache.CacheManager; 5 | import org.ehcache.config.builders.CacheConfigurationBuilder; 6 | import org.ehcache.config.builders.CacheManagerBuilder; 7 | import org.ehcache.config.builders.ResourcePoolsBuilder; 8 | import org.springframework.beans.factory.annotation.Value; 9 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 10 | import org.springframework.context.annotation.Bean; 11 | import org.springframework.context.annotation.Configuration; 12 | import ru.cbrrate.model.CachedCurrencyRates; 13 | 14 | import java.time.LocalDate; 15 | 16 | @Configuration 17 | @EnableConfigurationProperties(CbrConfig.class) 18 | public class ApplicationConfig { 19 | private final CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build(true); 20 | 21 | @Bean 22 | public Cache currencyRateCache(@Value("${app.cache.size}") int cacheSize) { 23 | return cacheManager.createCache("CurrencyRate-Cache", 24 | CacheConfigurationBuilder.newCacheConfigurationBuilder(LocalDate.class, CachedCurrencyRates.class, 25 | ResourcePoolsBuilder.heap(cacheSize)) 26 | .build()); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /cbrRate/src/main/java/ru/cbrrate/config/CbrConfig.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.config; 2 | 3 | import lombok.Data; 4 | import org.springframework.boot.context.properties.ConfigurationProperties; 5 | 6 | @Data 7 | @ConfigurationProperties(prefix = "cbr") 8 | public class CbrConfig { 9 | String url; 10 | } 11 | -------------------------------------------------------------------------------- /cbrRate/src/main/java/ru/cbrrate/config/JsonConfig.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.config; 2 | 3 | import com.fasterxml.jackson.annotation.JsonInclude; 4 | import com.fasterxml.jackson.databind.DeserializationFeature; 5 | import com.fasterxml.jackson.databind.ObjectMapper; 6 | import com.fasterxml.jackson.databind.SerializationFeature; 7 | import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | 11 | @Configuration 12 | public class JsonConfig { 13 | 14 | @Bean 15 | public ObjectMapper objectMapper() { 16 | var objectMapper = new ObjectMapper(); 17 | objectMapper.registerModule(new JavaTimeModule()); 18 | objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); 19 | objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); 20 | objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 21 | objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); 22 | objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); 23 | return objectMapper; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /cbrRate/src/main/java/ru/cbrrate/controller/CurrencyRateController.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.controller; 2 | 3 | import lombok.RequiredArgsConstructor; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.springframework.format.annotation.DateTimeFormat; 6 | import org.springframework.web.bind.annotation.GetMapping; 7 | import org.springframework.web.bind.annotation.PathVariable; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | import reactor.core.publisher.Mono; 11 | import ru.cbrrate.model.CurrencyRate; 12 | import ru.cbrrate.services.CurrencyRateService; 13 | 14 | import java.time.LocalDate; 15 | 16 | 17 | @RestController 18 | @Slf4j 19 | @RequiredArgsConstructor 20 | @RequestMapping(path = "${app.rest.api.prefix}/v1") 21 | public class CurrencyRateController { 22 | 23 | public final CurrencyRateService currencyRateService; 24 | 25 | @GetMapping("/currencyRate/{currency}/{date}") 26 | public Mono getCurrencyRate(@PathVariable("currency") String currency, 27 | @DateTimeFormat(pattern = "dd-MM-yyyy") @PathVariable("date") LocalDate date) { 28 | log.info("getCurrencyRate, currency:{}, date:{}", currency, date); 29 | 30 | var rate = currencyRateService.getCurrencyRate(currency, date); 31 | log.info("rate:{}", rate); 32 | return Mono.just(rate); 33 | } 34 | } -------------------------------------------------------------------------------- /cbrRate/src/main/java/ru/cbrrate/model/CachedCurrencyRates.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.model; 2 | 3 | import lombok.Value; 4 | 5 | import java.util.List; 6 | 7 | @Value 8 | public class CachedCurrencyRates { 9 | List currencyRates; 10 | } 11 | -------------------------------------------------------------------------------- /cbrRate/src/main/java/ru/cbrrate/model/CurrencyRate.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonCreator; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.Value; 7 | 8 | @Value 9 | @AllArgsConstructor(onConstructor = @__(@JsonCreator)) 10 | @Builder 11 | public class CurrencyRate { 12 | String numCode; 13 | String charCode; 14 | String nominal; 15 | String name; 16 | String value; 17 | } 18 | -------------------------------------------------------------------------------- /cbrRate/src/main/java/ru/cbrrate/parser/CurrencyRateParser.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.parser; 2 | 3 | import ru.cbrrate.model.CurrencyRate; 4 | 5 | import java.util.List; 6 | 7 | public interface CurrencyRateParser { 8 | 9 | List parse(String ratesAsString); 10 | } 11 | -------------------------------------------------------------------------------- /cbrRate/src/main/java/ru/cbrrate/parser/CurrencyRateParserXml.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.parser; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.stereotype.Service; 5 | import org.w3c.dom.Document; 6 | import org.w3c.dom.Element; 7 | import org.w3c.dom.Node; 8 | import org.w3c.dom.NodeList; 9 | import org.xml.sax.InputSource; 10 | import ru.cbrrate.model.CurrencyRate; 11 | 12 | import javax.xml.XMLConstants; 13 | import javax.xml.parsers.DocumentBuilderFactory; 14 | import java.io.StringReader; 15 | import java.util.ArrayList; 16 | import java.util.List; 17 | 18 | @Service 19 | @Slf4j 20 | public class CurrencyRateParserXml implements CurrencyRateParser { 21 | @Override 22 | public List parse(String ratesAsString) { 23 | var rates = new ArrayList(); 24 | 25 | var dbf = DocumentBuilderFactory.newInstance(); 26 | dbf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); 27 | dbf.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); 28 | try { 29 | dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); 30 | var db = dbf.newDocumentBuilder(); 31 | 32 | try (var reader = new StringReader(ratesAsString)) { 33 | Document doc = db.parse(new InputSource(reader)); 34 | doc.getDocumentElement().normalize(); 35 | 36 | NodeList list = doc.getElementsByTagName("Valute"); 37 | 38 | for (var valuteIdx = 0; valuteIdx < list.getLength(); valuteIdx++) { 39 | var node = list.item(valuteIdx); 40 | if (node.getNodeType() == Node.ELEMENT_NODE) { 41 | var element = (Element) node; 42 | 43 | var rate = CurrencyRate.builder() 44 | .numCode(element.getElementsByTagName("NumCode").item(0).getTextContent()) 45 | .charCode(element.getElementsByTagName("CharCode").item(0).getTextContent()) 46 | .nominal(element.getElementsByTagName("Nominal").item(0).getTextContent()) 47 | .name(element.getElementsByTagName("Name").item(0).getTextContent()) 48 | .value(element.getElementsByTagName("Value").item(0).getTextContent()) 49 | .build(); 50 | rates.add(rate); 51 | } 52 | } 53 | } 54 | } catch (Exception ex) { 55 | log.error("xml parsing error, xml:{}", ratesAsString, ex); 56 | throw new CurrencyRateParsingException(ex); 57 | } 58 | return rates; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /cbrRate/src/main/java/ru/cbrrate/parser/CurrencyRateParsingException.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.parser; 2 | 3 | public class CurrencyRateParsingException extends RuntimeException { 4 | public CurrencyRateParsingException(Throwable cause) { 5 | super(cause); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /cbrRate/src/main/java/ru/cbrrate/requester/CbrRequester.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.requester; 2 | 3 | public interface CbrRequester { 4 | String getRatesAsXml(String url); 5 | } 6 | -------------------------------------------------------------------------------- /cbrRate/src/main/java/ru/cbrrate/requester/CbrRequesterImpl.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.requester; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.stereotype.Service; 5 | 6 | import java.net.URI; 7 | import java.net.http.HttpClient; 8 | import java.net.http.HttpRequest; 9 | import java.net.http.HttpResponse; 10 | 11 | @Service 12 | @Slf4j 13 | public class CbrRequesterImpl implements CbrRequester { 14 | 15 | @Override 16 | public String getRatesAsXml(String url) { 17 | try { 18 | log.info("request for url:{}", url); 19 | var client = HttpClient.newHttpClient(); 20 | HttpRequest request = HttpRequest.newBuilder() 21 | .uri(URI.create(url)) 22 | .build(); 23 | 24 | HttpResponse response = 25 | client.send(request, HttpResponse.BodyHandlers.ofString()); 26 | return response.body(); 27 | } catch (Exception ex) { 28 | if (ex instanceof InterruptedException) { 29 | Thread.currentThread().interrupt(); 30 | } 31 | log.error("cbr request error, url:{}", url, ex); 32 | throw new RequesterException(ex); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /cbrRate/src/main/java/ru/cbrrate/requester/RequesterException.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.requester; 2 | 3 | public class RequesterException extends RuntimeException { 4 | public RequesterException(Throwable cause) { 5 | super(cause); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /cbrRate/src/main/java/ru/cbrrate/services/CurrencyRateNotFoundException.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | public class CurrencyRateNotFoundException extends RuntimeException { 4 | public CurrencyRateNotFoundException(String message) { 5 | super(message); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /cbrRate/src/main/java/ru/cbrrate/services/CurrencyRateService.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | import lombok.RequiredArgsConstructor; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.ehcache.Cache; 6 | import org.springframework.stereotype.Service; 7 | import ru.cbrrate.model.CachedCurrencyRates; 8 | import ru.cbrrate.config.CbrConfig; 9 | import ru.cbrrate.model.CurrencyRate; 10 | import ru.cbrrate.parser.CurrencyRateParser; 11 | import ru.cbrrate.requester.CbrRequester; 12 | 13 | import java.time.LocalDate; 14 | import java.time.format.DateTimeFormatter; 15 | import java.util.List; 16 | 17 | @Service 18 | @Slf4j 19 | @RequiredArgsConstructor 20 | public class CurrencyRateService { 21 | public static final String DATE_FORMAT = "dd/MM/yyyy"; 22 | private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern(DATE_FORMAT); 23 | 24 | private final CbrRequester cbrRequester; 25 | private final CurrencyRateParser currencyRateParser; 26 | private final CbrConfig cbrConfig; 27 | private final Cache currencyRateCache; 28 | 29 | public CurrencyRate getCurrencyRate(String currency, LocalDate date) { 30 | log.info("getCurrencyRate. currency:{}, date:{}", currency, date); 31 | List rates; 32 | 33 | var cachedCurrencyRates = currencyRateCache.get(date); 34 | if (cachedCurrencyRates == null) { 35 | var urlWithParams = String.format("%s?date_req=%s", cbrConfig.getUrl(), DATE_FORMATTER.format(date)); 36 | var ratesAsXml = cbrRequester.getRatesAsXml(urlWithParams); 37 | rates = currencyRateParser.parse(ratesAsXml); 38 | currencyRateCache.put(date, new CachedCurrencyRates(rates)); 39 | } else { 40 | rates = cachedCurrencyRates.getCurrencyRates(); 41 | } 42 | 43 | return rates.stream().filter(rate -> currency.equals(rate.getCharCode())) 44 | .findFirst() 45 | .orElseThrow(() -> new CurrencyRateNotFoundException("Currency Rate not found. Currency:" + currency + ", date:" + date)); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /cbrRate/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8081 3 | 4 | management: 5 | server: 6 | port: 8091 7 | endpoints: 8 | enabled-by-default: false 9 | endpoint: 10 | health: 11 | enabled: true 12 | probes: 13 | enabled: true 14 | 15 | app: 16 | cache: 17 | size: 365 18 | rest: 19 | api: 20 | prefix: /api 21 | 22 | cbr: 23 | url: "https://cbr.ru/scripts/XML_daily.asp" 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /cbrRate/src/test/java/ru/cbrrate/controller/CurrencyRateControllerTest.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.controller; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.boot.test.mock.mockito.MockBean; 7 | import org.springframework.http.MediaType; 8 | import org.springframework.test.annotation.DirtiesContext; 9 | import org.springframework.test.web.reactive.server.WebTestClient; 10 | import ru.cbrrate.config.CbrConfig; 11 | import ru.cbrrate.requester.CbrRequester; 12 | 13 | import java.io.IOException; 14 | import java.net.URISyntaxException; 15 | import java.nio.charset.Charset; 16 | import java.nio.file.Files; 17 | import java.nio.file.Paths; 18 | import java.time.LocalDate; 19 | import java.time.format.DateTimeFormatter; 20 | 21 | import static org.assertj.core.api.Assertions.assertThat; 22 | import static org.mockito.ArgumentMatchers.any; 23 | import static org.mockito.Mockito.*; 24 | 25 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 26 | class CurrencyRateControllerTest { 27 | public static final String DATE_FORMAT = "dd/MM/yyyy"; 28 | private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern(DATE_FORMAT); 29 | 30 | @Autowired 31 | private WebTestClient webTestClient; 32 | 33 | @Autowired 34 | CbrConfig cbrConfig; 35 | 36 | @MockBean 37 | CbrRequester cbrRequester; 38 | 39 | @Test 40 | @DirtiesContext 41 | void getCurrencyRateTest() throws Exception { 42 | //given 43 | var currency = "EUR"; 44 | var date = "02-03-2021"; 45 | prepareCbrRequesterMock(date); 46 | 47 | //when 48 | var result = webTestClient 49 | .get().uri(String.format("/api/v1/currencyRate/%s/%s", currency, date)) 50 | .accept(MediaType.APPLICATION_JSON) 51 | .exchange() 52 | .expectStatus().isOk() 53 | .returnResult(String.class) 54 | .getResponseBody() 55 | .blockLast(); 56 | 57 | 58 | assertThat(result).isEqualTo("{\"numCode\":\"978\",\"charCode\":\"EUR\",\"nominal\":\"1\",\"name\":\"Евро\",\"value\":\"89,4461\"}"); 59 | } 60 | 61 | @Test 62 | @DirtiesContext 63 | void cacheUseTest() throws Exception { 64 | //given 65 | prepareCbrRequesterMock(null); 66 | 67 | var currency = "EUR"; 68 | var date = "02-03-2021"; 69 | 70 | //when 71 | webTestClient.get().uri(String.format("/api/v1/currencyRate/%s/%s", currency, date)).exchange().expectStatus().isOk(); 72 | webTestClient.get().uri(String.format("/api/v1/currencyRate/%s/%s", currency, date)).exchange().expectStatus().isOk(); 73 | 74 | currency = "USD"; 75 | webTestClient.get().uri(String.format("/api/v1/currencyRate/%s/%s", currency, date)).exchange().expectStatus().isOk(); 76 | 77 | date = "03-03-2021"; 78 | webTestClient.get().uri(String.format("/api/v1/currencyRate/%s/%s", currency, date)).exchange().expectStatus().isOk(); 79 | 80 | //then 81 | verify(cbrRequester, times(2)).getRatesAsXml(any()); 82 | } 83 | 84 | private void prepareCbrRequesterMock(String date) throws IOException, URISyntaxException { 85 | var uri = ClassLoader.getSystemResource("cbr_response.xml").toURI(); 86 | var ratesXml = Files.readString(Paths.get(uri), Charset.forName("Windows-1251")); 87 | 88 | if (date == null) { 89 | when(cbrRequester.getRatesAsXml(any())).thenReturn(ratesXml); 90 | } else { 91 | var dateParam = LocalDate.parse(date, DateTimeFormatter.ofPattern("dd-MM-yyyy")); 92 | var cbrUrl = String.format("%s?date_req=%s", cbrConfig.getUrl(), DATE_FORMATTER.format(dateParam)); 93 | when(cbrRequester.getRatesAsXml(cbrUrl)).thenReturn(ratesXml); 94 | } 95 | } 96 | } -------------------------------------------------------------------------------- /cbrRate/src/test/java/ru/cbrrate/parser/CurrencyRateParserXmlTest.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.parser; 2 | 3 | 4 | import org.junit.jupiter.api.Test; 5 | import ru.cbrrate.model.CurrencyRate; 6 | 7 | import java.io.IOException; 8 | import java.net.URISyntaxException; 9 | import java.nio.charset.Charset; 10 | import java.nio.file.Files; 11 | import java.nio.file.Paths; 12 | 13 | import static org.assertj.core.api.AssertionsForClassTypes.assertThat; 14 | 15 | class CurrencyRateParserXmlTest { 16 | 17 | @Test 18 | void parseTest() throws IOException, URISyntaxException { 19 | //given 20 | var parser = new CurrencyRateParserXml(); 21 | var uri = ClassLoader.getSystemResource("cbr_response.xml").toURI(); 22 | var ratesXml = Files.readString(Paths.get(uri), Charset.forName("Windows-1251")); 23 | 24 | //when 25 | var rates = parser.parse(ratesXml); 26 | 27 | //then 28 | assertThat(rates.size()).isEqualTo(34); 29 | assertThat(rates.contains(getUSDrate())).isTrue(); 30 | assertThat(rates.contains(getEURrate())).isTrue(); 31 | assertThat(rates.contains(getJPYrate())).isTrue(); 32 | } 33 | 34 | CurrencyRate getUSDrate() { 35 | return CurrencyRate.builder() 36 | .numCode("840") 37 | .charCode("USD") 38 | .nominal("1") 39 | .name("Доллар США") 40 | .value("74,0448") 41 | .build(); 42 | } 43 | 44 | CurrencyRate getEURrate() { 45 | return CurrencyRate.builder() 46 | .numCode("978") 47 | .charCode("EUR") 48 | .nominal("1") 49 | .name("Евро") 50 | .value("89,4461") 51 | .build(); 52 | } 53 | 54 | CurrencyRate getJPYrate() { 55 | return CurrencyRate.builder() 56 | .numCode("392") 57 | .charCode("JPY") 58 | .nominal("100") 59 | .name("Японских иен") 60 | .value("69,4702") 61 | .build(); 62 | } 63 | } -------------------------------------------------------------------------------- /cbrRate/src/test/resources/cbr_response.xml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/petrelevich/currency-rate/021573f97874016576e30e4c0d4fafb315b4efa9/cbrRate/src/test/resources/cbr_response.xml -------------------------------------------------------------------------------- /currencyRateBotRequestConsumer/HttpRequests.http: -------------------------------------------------------------------------------- 1 | ### 2 | POST https://api.telegram.org/bot[token]/getUpdates 3 | Accept: */* 4 | Content-Type: application/json 5 | Cache-Control: no-cache 6 | 7 | { 8 | "offset": 953141214 9 | } 10 | 11 | ### 12 | POST https://api.telegram.org/bot[token]/sendMessage 13 | Accept: */* 14 | Content-Type: application/json 15 | Cache-Control: no-cache 16 | 17 | { 18 | "chat_id": "506783844", 19 | "text": "testOk2", 20 | "reply_to_message_id": "4" 21 | } 22 | ############################################### 23 | ### 24 | GET http://localhost:8092/actuator/health 25 | Accept: */* 26 | Content-Type: application/json 27 | Cache-Control: no-cache 28 | 29 | ### 30 | GET http://localhost:8092/actuator/health/liveness 31 | Accept: */* 32 | Content-Type: application/json 33 | Cache-Control: no-cache 34 | 35 | ### 36 | GET http://localhost:8092/actuator/health/readiness 37 | Accept: */* 38 | Content-Type: application/json 39 | Cache-Control: no-cache 40 | -------------------------------------------------------------------------------- /currencyRateBotRequestConsumer/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.springframework.boot' 4 | id 'com.google.cloud.tools.jib' 5 | } 6 | 7 | apply from: 'jib.gradle' 8 | 9 | sourceCompatibility = JavaVersion.VERSION_17 10 | targetCompatibility = JavaVersion.VERSION_17 11 | 12 | dependencies { 13 | implementation 'org.springframework.boot:spring-boot-starter-webflux' 14 | implementation 'org.springframework.boot:spring-boot-starter-actuator' 15 | implementation 'org.springframework.kafka:spring-kafka' 16 | implementation 'ch.qos.logback:logback-classic' 17 | 18 | compileOnly 'org.projectlombok:lombok' 19 | testCompileOnly 'org.projectlombok:lombok' 20 | annotationProcessor 'org.projectlombok:lombok' 21 | 22 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 23 | testImplementation 'io.projectreactor:reactor-test' 24 | testImplementation 'org.testcontainers:junit-jupiter' 25 | testImplementation 'org.testcontainers:kafka' 26 | } 27 | 28 | test { 29 | useJUnitPlatform() 30 | testLogging { 31 | events "passed", "skipped", "failed" 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /currencyRateBotRequestConsumer/jib.gradle: -------------------------------------------------------------------------------- 1 | jib { 2 | container.creationTime = 'USE_CURRENT_TIMESTAMP' 3 | from { 4 | image = 'bellsoft/liberica-openjdk-alpine-musl:17.0.1-12' 5 | } 6 | to { 7 | tags = ['v1', 'latest'] 8 | image = 'registry.gitlab.com/petrelevich/dockerregistry/currency-rate-bot-request-consumer' 9 | auth { 10 | username = gitlabUser 11 | password = gitlabPassword 12 | } 13 | } 14 | } 15 | // ./gradlew jibDockerBuild 16 | 17 | //docker login registry.gitlab.com 18 | //docker run -p 8080:8080 registry.gitlab.com/petrelevich/dockerregistry/currency-rate-bot-request-consumer 19 | 20 | //docker push registry.gitlab.com/petrelevich/dockerregistry/currency-rate-bot-request-consumer:latest 21 | -------------------------------------------------------------------------------- /currencyRateBotRequestConsumer/src/main/java/ru/cbrrate/CurrencyRateBotRequestConsumer.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate; 2 | 3 | 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.boot.builder.SpringApplicationBuilder; 6 | 7 | 8 | 9 | @SpringBootApplication 10 | public class CurrencyRateBotRequestConsumer { 11 | public static void main(String[] args) { 12 | new SpringApplicationBuilder().sources(CurrencyRateBotRequestConsumer.class).run(args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /currencyRateBotRequestConsumer/src/main/java/ru/cbrrate/clients/HttpClient.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.clients; 2 | 3 | public interface HttpClient { 4 | 5 | String performRequest(String url, String params); 6 | 7 | } 8 | -------------------------------------------------------------------------------- /currencyRateBotRequestConsumer/src/main/java/ru/cbrrate/clients/HttpClientException.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.clients; 2 | 3 | public class HttpClientException extends RuntimeException { 4 | public HttpClientException(String msg) { 5 | super(msg); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /currencyRateBotRequestConsumer/src/main/java/ru/cbrrate/clients/HttpClientJdk.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.clients; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.stereotype.Service; 5 | 6 | import java.net.URI; 7 | import java.net.http.HttpRequest; 8 | import java.net.http.HttpResponse; 9 | 10 | @Service 11 | @Slf4j 12 | public class HttpClientJdk implements HttpClient { 13 | 14 | @Override 15 | public String performRequest(String url, String params) { 16 | var request = HttpRequest.newBuilder() 17 | .uri(URI.create(url)) 18 | .header("Content-Type", "application/json") 19 | .POST(HttpRequest.BodyPublishers.ofString(params)) 20 | .build(); 21 | return doRequest(url, request); 22 | } 23 | 24 | private String doRequest(String url, HttpRequest request) { 25 | try { 26 | var client = java.net.http.HttpClient.newHttpClient(); 27 | var response = client.send(request, HttpResponse.BodyHandlers.ofString()); 28 | return response.body(); 29 | } catch (Exception ex) { 30 | if (ex instanceof InterruptedException) { 31 | Thread.currentThread().interrupt(); 32 | } 33 | log.error("Http request error, url:{}", url, ex); 34 | throw new HttpClientException(ex.getMessage()); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /currencyRateBotRequestConsumer/src/main/java/ru/cbrrate/clients/TelegramClient.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.clients; 2 | 3 | import ru.cbrrate.model.GetUpdatesRequest; 4 | import ru.cbrrate.model.GetUpdatesResponse; 5 | 6 | public interface TelegramClient { 7 | 8 | GetUpdatesResponse getUpdates(GetUpdatesRequest request); 9 | } 10 | -------------------------------------------------------------------------------- /currencyRateBotRequestConsumer/src/main/java/ru/cbrrate/clients/TelegramClientImpl.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.clients; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import lombok.RequiredArgsConstructor; 6 | import lombok.extern.slf4j.Slf4j; 7 | import org.springframework.stereotype.Service; 8 | import ru.cbrrate.config.TelegramClientConfig; 9 | import ru.cbrrate.model.GetUpdatesRequest; 10 | import ru.cbrrate.model.GetUpdatesResponse; 11 | import ru.cbrrate.services.TelegramException; 12 | 13 | 14 | @Service 15 | @Slf4j 16 | @RequiredArgsConstructor 17 | public class TelegramClientImpl implements TelegramClient { 18 | 19 | private final HttpClient httpClientJdk; 20 | private final ObjectMapper objectMapper; 21 | private final TelegramClientConfig clientConfig; 22 | 23 | @Override 24 | public GetUpdatesResponse getUpdates(GetUpdatesRequest request) { 25 | try { 26 | var params = objectMapper.writeValueAsString(request); 27 | log.info("getUpdates params:{}", params); 28 | 29 | var updatesAsString = httpClientJdk.performRequest(makeUrl(), params); 30 | log.info("updatesAsString:{}", updatesAsString); 31 | var updates = objectMapper.readValue(updatesAsString, GetUpdatesResponse.class); 32 | log.info("updates:{}", updates); 33 | 34 | return updates; 35 | } catch (JsonProcessingException ex) { 36 | log.error("request:{}", request, ex); 37 | throw new TelegramException(ex); 38 | } 39 | } 40 | 41 | private String makeUrl() { 42 | return String.format("%s/bot%s/%s", clientConfig.getUrl(), clientConfig.getToken(), "getUpdates"); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /currencyRateBotRequestConsumer/src/main/java/ru/cbrrate/config/ApplicationConfig.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.config; 2 | 3 | import lombok.RequiredArgsConstructor; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.springframework.beans.factory.annotation.Value; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import ru.cbrrate.services.LastUpdateIdKeeper; 9 | import ru.cbrrate.clients.TelegramClient; 10 | import ru.cbrrate.services.MessageSender; 11 | import ru.cbrrate.services.TelegramException; 12 | import ru.cbrrate.services.TelegramService; 13 | import ru.cbrrate.services.TelegramServiceImpl; 14 | 15 | 16 | import java.io.IOException; 17 | import java.nio.file.Files; 18 | import java.nio.file.Path; 19 | import java.util.concurrent.Executors; 20 | import java.util.concurrent.ScheduledExecutorService; 21 | import java.util.concurrent.TimeUnit; 22 | 23 | @Configuration 24 | @RequiredArgsConstructor 25 | @Slf4j 26 | public class ApplicationConfig { 27 | public static final String TELEGRAM_TOKEN_ENV_NAME = "TELEGRAM_TOKEN"; 28 | public static final String TOKEN_FILE = "TOKEN_FILE"; 29 | 30 | @Bean 31 | public TelegramClientConfig telegramClientConfig(@Value("${app.telegram.url}") String url, 32 | @Value("${app.telegram.refresh-rate-ms}") int refreshRateMs) { 33 | var token = System.getProperty(TELEGRAM_TOKEN_ENV_NAME); 34 | if (token == null) { 35 | token = System.getenv(TELEGRAM_TOKEN_ENV_NAME); 36 | } 37 | if (token == null) { 38 | var tokenFile = System.getenv(TOKEN_FILE); 39 | token = readFile(tokenFile); 40 | } 41 | if (token == null) { 42 | log.error("telegram token not found"); 43 | throw new TelegramException("telegram token not found"); 44 | } 45 | return new TelegramClientConfig(url, token, refreshRateMs); 46 | } 47 | 48 | @Bean 49 | public TelegramImporterScheduled telegramImporterScheduled(TelegramClient telegramClient, 50 | TelegramClientConfig telegramClientConfig, 51 | MessageSender messageSender, 52 | LastUpdateIdKeeper lastUpdateIdKeeper) { 53 | var telegramService = new TelegramServiceImpl(telegramClient, lastUpdateIdKeeper, messageSender); 54 | return new TelegramImporterScheduled(telegramService, telegramClientConfig); 55 | } 56 | 57 | public static class TelegramImporterScheduled { 58 | public TelegramImporterScheduled(TelegramService telegramService, TelegramClientConfig telegramClientConfig) { 59 | ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); 60 | executor.scheduleAtFixedRate(telegramService::getUpdates, 1000, telegramClientConfig.getRefreshRateMs(), TimeUnit.MILLISECONDS); 61 | } 62 | } 63 | 64 | private String readFile(String tokenFile) { 65 | try { 66 | if (tokenFile != null) { 67 | return Files.readString(Path.of(tokenFile)); 68 | } 69 | return null; 70 | } catch (IOException e) { 71 | throw new TelegramException("can't read file:" + tokenFile); 72 | } 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /currencyRateBotRequestConsumer/src/main/java/ru/cbrrate/config/JsonConfig.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.config; 2 | 3 | import com.fasterxml.jackson.annotation.JsonInclude; 4 | import com.fasterxml.jackson.databind.DeserializationFeature; 5 | import com.fasterxml.jackson.databind.ObjectMapper; 6 | import com.fasterxml.jackson.databind.SerializationFeature; 7 | import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | 11 | @Configuration 12 | public class JsonConfig { 13 | 14 | @Bean 15 | public ObjectMapper objectMapper() { 16 | var objectMapper = new ObjectMapper(); 17 | objectMapper.registerModule(new JavaTimeModule()); 18 | objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); 19 | objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); 20 | objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 21 | objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); 22 | objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); 23 | return objectMapper; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /currencyRateBotRequestConsumer/src/main/java/ru/cbrrate/config/KafkaConfig.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.config; 2 | 3 | import lombok.RequiredArgsConstructor; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.apache.kafka.clients.admin.NewTopic; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | 9 | import org.springframework.kafka.config.TopicBuilder; 10 | 11 | 12 | @Configuration 13 | @RequiredArgsConstructor 14 | @Slf4j 15 | public class KafkaConfig { 16 | 17 | public static final String TOPIC_RATE_REQUESTS = "RATE_REQUESTS"; 18 | 19 | @Bean 20 | public NewTopic topic() { 21 | return TopicBuilder 22 | .name(TOPIC_RATE_REQUESTS) 23 | .partitions(1) 24 | .replicas(1) 25 | .build(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /currencyRateBotRequestConsumer/src/main/java/ru/cbrrate/config/SchedulingConfig.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.config; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.scheduling.annotation.EnableScheduling; 5 | 6 | @Configuration 7 | @EnableScheduling 8 | public class SchedulingConfig { 9 | } 10 | -------------------------------------------------------------------------------- /currencyRateBotRequestConsumer/src/main/java/ru/cbrrate/config/TelegramClientConfig.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.config; 2 | 3 | import lombok.Value; 4 | 5 | @Value 6 | public class TelegramClientConfig { 7 | String url; 8 | String token; 9 | int refreshRateMs; 10 | } 11 | -------------------------------------------------------------------------------- /currencyRateBotRequestConsumer/src/main/java/ru/cbrrate/model/GetUpdatesRequest.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | import lombok.Value; 5 | 6 | @Value 7 | public class GetUpdatesRequest { 8 | 9 | @JsonProperty("offset") 10 | long offset; 11 | } 12 | -------------------------------------------------------------------------------- /currencyRateBotRequestConsumer/src/main/java/ru/cbrrate/model/GetUpdatesResponse.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonCreator; 4 | import com.fasterxml.jackson.annotation.JsonProperty; 5 | import lombok.Builder; 6 | import lombok.Value; 7 | 8 | import java.util.List; 9 | 10 | @Value 11 | @Builder 12 | public class GetUpdatesResponse { 13 | boolean ok; 14 | List result; 15 | 16 | @JsonCreator 17 | public GetUpdatesResponse(@JsonProperty("ok")boolean ok, @JsonProperty("result") List result) { 18 | this.ok = ok; 19 | this.result = result; 20 | } 21 | 22 | @Value 23 | public static class Response { 24 | long updateId; 25 | Message message; 26 | 27 | public Response(long updateId, Message message) { 28 | this.updateId = updateId; 29 | this.message = message; 30 | } 31 | @JsonCreator 32 | public Response(@JsonProperty("update_id") long updateId, @JsonProperty("message") Message message, @JsonProperty("edited_message") Message editedMessage) { 33 | this.updateId = updateId; 34 | this.message = message != null ? message : editedMessage; 35 | } 36 | } 37 | 38 | @Value 39 | public static class Message { 40 | long messageId; 41 | From from; 42 | Chat chat; 43 | long date; 44 | String text; 45 | 46 | @JsonCreator 47 | public Message(@JsonProperty("message_id") long messageId, 48 | @JsonProperty("from") From from, 49 | @JsonProperty("chat") Chat chat, 50 | @JsonProperty("date") long date, 51 | @JsonProperty("text") String text) { 52 | this.messageId = messageId; 53 | this.from = from; 54 | this.chat = chat; 55 | this.date = date; 56 | this.text = text; 57 | } 58 | } 59 | 60 | @Value 61 | public static class From { 62 | long id; 63 | boolean isBot; 64 | String firstName; 65 | String lastName; 66 | String languageCode; 67 | 68 | @JsonCreator 69 | public From(@JsonProperty("id") long id, 70 | @JsonProperty("is_bot") boolean isBot, 71 | @JsonProperty("first_name") String firstName, 72 | @JsonProperty("last_name") String lastName, 73 | @JsonProperty("language_code") String languageCode) { 74 | this.id = id; 75 | this.isBot = isBot; 76 | this.firstName = firstName; 77 | this.lastName = lastName; 78 | this.languageCode = languageCode; 79 | } 80 | } 81 | 82 | @Value 83 | public static class Chat { 84 | long id; 85 | String firstName; 86 | String lastName; 87 | String type; 88 | 89 | @JsonCreator 90 | public Chat(@JsonProperty("id") long id, 91 | @JsonProperty("first_name") String firstName, 92 | @JsonProperty("last_name") String lastName, 93 | @JsonProperty("type") String type) { 94 | this.id = id; 95 | this.firstName = firstName; 96 | this.lastName = lastName; 97 | this.type = type; 98 | } 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /currencyRateBotRequestConsumer/src/main/java/ru/cbrrate/services/BotException.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | public class BotException extends RuntimeException { 4 | public BotException(String message, Throwable cause) { 5 | super(message, cause); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /currencyRateBotRequestConsumer/src/main/java/ru/cbrrate/services/DateTimeProvider.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | import java.time.LocalDateTime; 4 | 5 | public interface DateTimeProvider { 6 | LocalDateTime get(); 7 | } 8 | -------------------------------------------------------------------------------- /currencyRateBotRequestConsumer/src/main/java/ru/cbrrate/services/DateTimeProviderCurrent.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | import org.springframework.stereotype.Service; 4 | 5 | import java.time.LocalDateTime; 6 | 7 | @Service 8 | public class DateTimeProviderCurrent implements DateTimeProvider { 9 | @Override 10 | public LocalDateTime get() { 11 | return LocalDateTime.now(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /currencyRateBotRequestConsumer/src/main/java/ru/cbrrate/services/KafkaMessageSender.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import lombok.RequiredArgsConstructor; 6 | import lombok.extern.slf4j.Slf4j; 7 | import org.springframework.kafka.core.KafkaTemplate; 8 | import org.springframework.stereotype.Service; 9 | import ru.cbrrate.model.GetUpdatesResponse; 10 | 11 | import static ru.cbrrate.config.KafkaConfig.TOPIC_RATE_REQUESTS; 12 | 13 | @Service 14 | @Slf4j 15 | @RequiredArgsConstructor 16 | public class KafkaMessageSender implements MessageSender { 17 | 18 | private final KafkaTemplate kafkaTemplate; 19 | private final ObjectMapper objectMapper; 20 | 21 | @Override 22 | public void send(GetUpdatesResponse.Message message) { 23 | log.info("send message:{}", message); 24 | String messageAsString; 25 | try { 26 | messageAsString = objectMapper.writeValueAsString(message); 27 | } catch (JsonProcessingException ex) { 28 | log.error("can't serialize message:{}", message, ex); 29 | throw new BotException("can't send message:" + message, ex); 30 | } 31 | kafkaTemplate.send(TOPIC_RATE_REQUESTS, messageAsString); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /currencyRateBotRequestConsumer/src/main/java/ru/cbrrate/services/LastUpdateIdKeeper.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | public interface LastUpdateIdKeeper { 4 | long get(); 5 | 6 | void set(long lastUpdateId); 7 | } 8 | -------------------------------------------------------------------------------- /currencyRateBotRequestConsumer/src/main/java/ru/cbrrate/services/LastUpdateIdKeeperImpl.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | import org.springframework.stereotype.Component; 4 | 5 | @Component 6 | public class LastUpdateIdKeeperImpl implements LastUpdateIdKeeper { 7 | 8 | private long lastUpdateId = 0; 9 | 10 | @Override 11 | public synchronized long get() { 12 | return lastUpdateId; 13 | } 14 | 15 | @Override 16 | public synchronized void set(long lastUpdateId) { 17 | this.lastUpdateId = lastUpdateId; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /currencyRateBotRequestConsumer/src/main/java/ru/cbrrate/services/MessageSender.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | import ru.cbrrate.model.GetUpdatesResponse; 4 | 5 | public interface MessageSender { 6 | void send(GetUpdatesResponse.Message message); 7 | } 8 | -------------------------------------------------------------------------------- /currencyRateBotRequestConsumer/src/main/java/ru/cbrrate/services/TelegramException.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | public class TelegramException extends RuntimeException { 4 | public TelegramException(Throwable cause) { 5 | super(cause); 6 | } 7 | 8 | public TelegramException(String message) { 9 | super(message); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /currencyRateBotRequestConsumer/src/main/java/ru/cbrrate/services/TelegramService.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | public interface TelegramService { 4 | void getUpdates(); 5 | } 6 | -------------------------------------------------------------------------------- /currencyRateBotRequestConsumer/src/main/java/ru/cbrrate/services/TelegramServiceImpl.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import ru.cbrrate.clients.TelegramClient; 5 | import ru.cbrrate.model.GetUpdatesRequest; 6 | import ru.cbrrate.model.GetUpdatesResponse; 7 | 8 | 9 | @Slf4j 10 | public class TelegramServiceImpl implements TelegramService { 11 | 12 | private final TelegramClient telegramClient; 13 | private final LastUpdateIdKeeper lastUpdateIdKeeper; 14 | private final MessageSender messageSender; 15 | 16 | public TelegramServiceImpl(TelegramClient telegramClient, 17 | LastUpdateIdKeeper lastUpdateIdKeeper, 18 | MessageSender messageSender) { 19 | this.telegramClient = telegramClient; 20 | this.lastUpdateIdKeeper = lastUpdateIdKeeper; 21 | this.messageSender = messageSender; 22 | } 23 | 24 | @Override 25 | public void getUpdates() { 26 | try { 27 | log.info("getUpdates begin"); 28 | var offset = lastUpdateIdKeeper.get(); 29 | var request = new GetUpdatesRequest(offset); 30 | var response = telegramClient.getUpdates(request); 31 | var lastUpdateId = processResponse(response); 32 | lastUpdateId = lastUpdateId == 0 ? offset : lastUpdateId + 1; 33 | lastUpdateIdKeeper.set(lastUpdateId); 34 | log.info("getUpdates end, lastUpdateId:{}", lastUpdateId); 35 | } catch (Exception ex) { 36 | log.error("unhandled exception", ex); 37 | } 38 | } 39 | 40 | private long processResponse(GetUpdatesResponse response) { 41 | log.info("response.getResult().size:{}", response.getResult().size()); 42 | long lastUpdateId = 0; 43 | for (var responseMsg : response.getResult()) { 44 | lastUpdateId = Math.max(lastUpdateId, responseMsg.getUpdateId()); 45 | messageSender.send(responseMsg.getMessage()); 46 | } 47 | log.info("lastUpdateId:{}", lastUpdateId); 48 | return lastUpdateId; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /currencyRateBotRequestConsumer/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8082 3 | 4 | spring: 5 | kafka: 6 | bootstrap-servers: "localhost:9092" 7 | consumer: 8 | auto-offset-reset: earliest 9 | 10 | management: 11 | server: 12 | port: 8092 13 | endpoints: 14 | enabled-by-default: false 15 | endpoint: 16 | health: 17 | enabled: true 18 | probes: 19 | enabled: true 20 | 21 | app: 22 | rest: 23 | api: 24 | prefix: /api 25 | telegram: 26 | url: https://api.telegram.org 27 | refresh-rate-ms: 3000 28 | -------------------------------------------------------------------------------- /currencyRateBotRequestConsumer/src/test/java/ru/cbrrate/services/KafkaBase.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | import org.apache.kafka.clients.admin.AdminClient; 4 | import org.apache.kafka.clients.admin.NewTopic; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.boot.test.util.TestPropertyValues; 8 | import org.springframework.context.ApplicationContextInitializer; 9 | import org.springframework.context.ConfigurableApplicationContext; 10 | import org.testcontainers.containers.KafkaContainer; 11 | import org.testcontainers.utility.DockerImageName; 12 | 13 | import java.util.Collection; 14 | import java.util.Map; 15 | import java.util.concurrent.ExecutionException; 16 | import java.util.concurrent.TimeUnit; 17 | import java.util.concurrent.TimeoutException; 18 | 19 | import static org.apache.kafka.clients.CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG; 20 | 21 | class KafkaBase { 22 | private static final Logger log = LoggerFactory.getLogger(KafkaBase.class); 23 | 24 | private final static KafkaContainer kafka = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:7.0.0")); 25 | private static boolean started = false; 26 | 27 | public static void start(Collection topics) throws ExecutionException, InterruptedException, TimeoutException { 28 | if (!started) { 29 | kafka.start(); 30 | 31 | log.info("topics creation..."); 32 | try (var admin = AdminClient.create(Map.of(BOOTSTRAP_SERVERS_CONFIG, kafka.getBootstrapServers()))) { 33 | var result = admin.createTopics(topics); 34 | 35 | for(var topicResult: result.values().values()) { 36 | topicResult.get(10, TimeUnit.SECONDS); 37 | } 38 | } 39 | log.info("topics created"); 40 | started = true; 41 | } 42 | } 43 | 44 | public static class Initializer implements ApplicationContextInitializer { 45 | @Override 46 | public void initialize(ConfigurableApplicationContext applicationContext) { 47 | if (started) { 48 | TestPropertyValues.of( 49 | "spring.kafka.bootstrap-servers:" + kafka.getBootstrapServers() 50 | ).applyTo(applicationContext.getEnvironment()); 51 | } 52 | } 53 | } 54 | } -------------------------------------------------------------------------------- /currencyRateBotRequestConsumer/src/test/java/ru/cbrrate/services/TelegramClientTest.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import ru.cbrrate.clients.HttpClientJdk; 5 | import ru.cbrrate.clients.TelegramClientImpl; 6 | import ru.cbrrate.config.JsonConfig; 7 | import ru.cbrrate.config.TelegramClientConfig; 8 | import ru.cbrrate.model.GetUpdatesRequest; 9 | import ru.cbrrate.model.GetUpdatesResponse; 10 | 11 | import static org.assertj.core.api.Assertions.assertThat; 12 | import static org.mockito.Mockito.*; 13 | 14 | class TelegramClientTest { 15 | 16 | @Test 17 | void getUpdatesTest() { 18 | //given 19 | var clientConfig = new TelegramClientConfig("https://api.telegram.org", "G23FD", 100); 20 | var request = new GetUpdatesRequest(11); 21 | 22 | var expectedUrl = String.format("%s/bot%s/getUpdates", clientConfig.getUrl(), clientConfig.getToken()); 23 | var expectedParams = String.format("{\"offset\":%d}", request.getOffset()); 24 | var httpClientJdk = mock(HttpClientJdk.class); 25 | when(httpClientJdk.performRequest(expectedUrl, expectedParams)).thenReturn(getResponseForUpdates()); 26 | 27 | var objectMapper = new JsonConfig().objectMapper(); 28 | var client = new TelegramClientImpl(httpClientJdk, objectMapper, clientConfig); 29 | 30 | 31 | //when 32 | var getUpdatesResponse = client.getUpdates(request); 33 | 34 | //then 35 | assertThat(getUpdatesResponse.getResult()).hasSize(2); 36 | 37 | var from1 = new GetUpdatesResponse.From(506L, false, "Ivan" ,"Petrov","en"); 38 | var chat1 = new GetUpdatesResponse.Chat(506L,"Ivan" ,"Petrov","private"); 39 | var message1 = new GetUpdatesResponse.Message(3, from1, chat1,1631970287,"/help"); 40 | var response1 = new GetUpdatesResponse.Response(953141213L, message1); 41 | 42 | var from2 = new GetUpdatesResponse.From(506L, false, "Ivan" ,"Petrov","en"); 43 | var chat2 = new GetUpdatesResponse.Chat(506L,"Ivan" ,"Petrov","private"); 44 | var message2 = new GetUpdatesResponse.Message(4, from2, chat2,1631973072,"gggg"); 45 | var response2 = new GetUpdatesResponse.Response(953141214L, message2); 46 | 47 | assertThat(getUpdatesResponse.getResult()).contains(response1, response2); 48 | } 49 | 50 | private String getResponseForUpdates() { 51 | return """ 52 | {"ok":true,"result":[{"update_id":953141213, 53 | "message":{"message_id":3,"from":{"id":506,"is_bot":false,"first_name":"Ivan","last_name":"Petrov","language_code":"en"},"chat":{"id":506,"first_name":"Ivan","last_name":"Petrov","type":"private"},"date":1631970287,"text":"/help","entities":[{"offset":0,"length":5,"type":"bot_command"}]}},{"update_id":953141214, 54 | "message":{"message_id":4,"from":{"id":506,"is_bot":false,"first_name":"Ivan","last_name":"Petrov","language_code":"en"},"chat":{"id":506,"first_name":"Ivan","last_name":"Petrov","type":"private"},"date":1631973072,"text":"gggg"}}]} 55 | """; 56 | } 57 | } -------------------------------------------------------------------------------- /currencyRateBotRequestConsumer/src/test/java/ru/cbrrate/services/TelegramServiceImplTest.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | import com.fasterxml.jackson.core.JacksonException; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import org.apache.kafka.clients.admin.NewTopic; 6 | import org.apache.kafka.clients.consumer.ConsumerRecord; 7 | import org.apache.kafka.clients.consumer.ConsumerRecords; 8 | import org.assertj.core.util.Streams; 9 | import org.junit.jupiter.api.BeforeAll; 10 | import org.junit.jupiter.api.Test; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.boot.test.context.SpringBootTest; 13 | import org.springframework.boot.test.mock.mockito.MockBean; 14 | import org.springframework.kafka.core.ConsumerFactory; 15 | import org.springframework.test.context.ContextConfiguration; 16 | import ru.cbrrate.clients.TelegramClient; 17 | import ru.cbrrate.model.GetUpdatesRequest; 18 | import ru.cbrrate.model.GetUpdatesResponse; 19 | 20 | import java.time.Duration; 21 | import java.util.ArrayList; 22 | import java.util.List; 23 | import java.util.Random; 24 | import java.util.concurrent.ExecutionException; 25 | import java.util.concurrent.TimeoutException; 26 | 27 | import static org.assertj.core.api.Assertions.assertThat; 28 | import static org.mockito.Mockito.*; 29 | import static ru.cbrrate.config.ApplicationConfig.TELEGRAM_TOKEN_ENV_NAME; 30 | import static ru.cbrrate.config.KafkaConfig.TOPIC_RATE_REQUESTS; 31 | 32 | @SpringBootTest 33 | @ContextConfiguration(initializers = {KafkaBase.Initializer.class}) 34 | class TelegramServiceImplTest { 35 | 36 | static { 37 | System.setProperty(TELEGRAM_TOKEN_ENV_NAME, "test"); 38 | } 39 | 40 | @Autowired 41 | private MessageSender messageSender; 42 | 43 | @Autowired 44 | private ObjectMapper objectMapper; 45 | 46 | @Autowired 47 | private ConsumerFactory consumerFactory; 48 | 49 | @MockBean 50 | private TelegramClient telegramClient; 51 | 52 | @BeforeAll 53 | public static void init() throws ExecutionException, InterruptedException, TimeoutException { 54 | KafkaBase.start(List.of(new NewTopic(TOPIC_RATE_REQUESTS, 1, (short) 1))); 55 | } 56 | 57 | @Test 58 | void getUpdatesTest() { 59 | var text = "text"; 60 | var lastUpdateIdKeeper = spy(new LastUpdateIdKeeperImpl()); 61 | var telegramService = new TelegramServiceImpl(telegramClient, lastUpdateIdKeeper, messageSender); 62 | 63 | //first run 64 | //given 65 | var request1 = new GetUpdatesRequest(0); 66 | var response1 = makeGetUpdatesResponse(1, text); 67 | when(telegramClient.getUpdates(request1)).thenReturn(response1); 68 | var expectedSentMessages = new ArrayList<>(response1.getResult().stream() 69 | .map(GetUpdatesResponse.Response::getMessage).toList()); 70 | 71 | //when 72 | telegramService.getUpdates(); 73 | 74 | //then 75 | verify(lastUpdateIdKeeper).set(response1.getResult().get(1).getUpdateId() + 1); 76 | 77 | //second run 78 | //given 79 | var request2 = new GetUpdatesRequest(response1.getResult().get(1).getUpdateId() + 1); 80 | var response2 = makeGetUpdatesResponse(2, text); 81 | when(telegramClient.getUpdates(request2)).thenReturn(response2); 82 | expectedSentMessages.addAll(response2.getResult().stream() 83 | .map(GetUpdatesResponse.Response::getMessage).toList()); 84 | 85 | //when 86 | telegramService.getUpdates(); 87 | 88 | verify(lastUpdateIdKeeper).set(response2.getResult().get(1).getUpdateId()); 89 | 90 | var kafkaConsumer = consumerFactory.createConsumer(TOPIC_RATE_REQUESTS, "clientId"); 91 | kafkaConsumer.subscribe(List.of(TOPIC_RATE_REQUESTS)); 92 | 93 | ConsumerRecords records = kafkaConsumer.poll(Duration.ofMillis(10_000)); 94 | 95 | var factSentMessages = Streams.stream(records).map(this::parse).toList(); 96 | assertThat(factSentMessages).hasSameElementsAs(expectedSentMessages); 97 | } 98 | 99 | private GetUpdatesResponse makeGetUpdatesResponse(long updateId, String text) { 100 | var from = new GetUpdatesResponse.From(506L, false, "Ivan", "Petrov", "en"); 101 | var chat = new GetUpdatesResponse.Chat(506L, "Ivan", "Petrov", "private"); 102 | var random = new Random(); 103 | var message1 = new GetUpdatesResponse.Message(random.nextLong(), from, chat, 1631970287, text); 104 | var message2 = new GetUpdatesResponse.Message(random.nextLong(), from, chat, 1631970287, text); 105 | 106 | return new GetUpdatesResponse(true, List.of(new GetUpdatesResponse.Response(updateId, message1), 107 | new GetUpdatesResponse.Response(updateId + 1, message2))); 108 | } 109 | 110 | private GetUpdatesResponse.Message parse(ConsumerRecord kafkaRecord) { 111 | try { 112 | return objectMapper.readValue(kafkaRecord.value(), GetUpdatesResponse.Message.class); 113 | } catch (JacksonException ex) { 114 | throw new RuntimeException(ex); 115 | } 116 | } 117 | } -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/HttpRequests.http: -------------------------------------------------------------------------------- 1 | ### 2 | POST https://api.telegram.org/bot[token]/getUpdates 3 | Accept: */* 4 | Content-Type: application/json 5 | Cache-Control: no-cache 6 | 7 | { 8 | "offset": 953141214 9 | } 10 | 11 | ### 12 | POST https://api.telegram.org/bot[token]/sendMessage 13 | Accept: */* 14 | Content-Type: application/json 15 | Cache-Control: no-cache 16 | 17 | { 18 | "chat_id": "506783844", 19 | "text": "testOk2", 20 | "reply_to_message_id": "4" 21 | } 22 | ############################################### 23 | ### 24 | GET http://localhost:8092/actuator/health 25 | Accept: */* 26 | Content-Type: application/json 27 | Cache-Control: no-cache 28 | 29 | ### 30 | GET http://localhost:8092/actuator/health/liveness 31 | Accept: */* 32 | Content-Type: application/json 33 | Cache-Control: no-cache 34 | 35 | ### 36 | GET http://localhost:8092/actuator/health/readiness 37 | Accept: */* 38 | Content-Type: application/json 39 | Cache-Control: no-cache 40 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.springframework.boot' 4 | id 'com.google.cloud.tools.jib' 5 | } 6 | 7 | apply from: 'jib.gradle' 8 | 9 | sourceCompatibility = JavaVersion.VERSION_17 10 | targetCompatibility = JavaVersion.VERSION_17 11 | 12 | dependencies { 13 | implementation 'org.springframework.boot:spring-boot-starter-webflux' 14 | implementation 'org.springframework.boot:spring-boot-starter-actuator' 15 | implementation 'org.springframework.kafka:spring-kafka' 16 | implementation 'ch.qos.logback:logback-classic' 17 | 18 | compileOnly 'org.projectlombok:lombok' 19 | testCompileOnly 'org.projectlombok:lombok' 20 | annotationProcessor 'org.projectlombok:lombok' 21 | 22 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 23 | testImplementation 'io.projectreactor:reactor-test' 24 | testImplementation 'org.testcontainers:junit-jupiter' 25 | testImplementation 'org.testcontainers:kafka' 26 | } 27 | 28 | test { 29 | useJUnitPlatform() 30 | testLogging { 31 | events "passed", "skipped", "failed" 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/jib.gradle: -------------------------------------------------------------------------------- 1 | jib { 2 | container.creationTime = 'USE_CURRENT_TIMESTAMP' 3 | from { 4 | image = 'bellsoft/liberica-openjdk-alpine-musl:17.0.1-12' 5 | } 6 | to { 7 | tags = ['v1', 'latest'] 8 | image = 'registry.gitlab.com/petrelevich/dockerregistry/currency-rate-bot-response-provider' 9 | auth { 10 | username = gitlabUser 11 | password = gitlabPassword 12 | } 13 | } 14 | } 15 | // ./gradlew jibDockerBuild 16 | 17 | //docker login registry.gitlab.com 18 | //docker run -p 8080:8080 registry.gitlab.com/petrelevich/dockerregistry/currency-rate-bot-response-provider 19 | 20 | //docker push registry.gitlab.com/petrelevich/dockerregistry/currency-rate-bot-response-provider:latest 21 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/CurrencyRateBotResponseProvider.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate; 2 | 3 | 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.boot.builder.SpringApplicationBuilder; 6 | 7 | 8 | @SpringBootApplication 9 | public class CurrencyRateBotResponseProvider { 10 | public static void main(String[] args) { 11 | new SpringApplicationBuilder().sources(CurrencyRateBotResponseProvider.class).run(args); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/clients/CurrencyRateClient.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.clients; 2 | 3 | import reactor.core.publisher.Mono; 4 | import ru.cbrrate.model.CurrencyRate; 5 | 6 | import java.time.LocalDate; 7 | 8 | public interface CurrencyRateClient { 9 | 10 | Mono getCurrencyRate(String rateType, String currency, LocalDate date); 11 | } 12 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/clients/CurrencyRateClientException.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.clients; 2 | 3 | public class CurrencyRateClientException extends RuntimeException { 4 | public CurrencyRateClientException(String msg) { 5 | super(msg); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/clients/CurrencyRateClientImpl.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.clients; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import lombok.RequiredArgsConstructor; 5 | import lombok.extern.slf4j.Slf4j; 6 | import org.springframework.stereotype.Service; 7 | import reactor.core.publisher.Mono; 8 | import ru.cbrrate.config.CurrencyRateClientConfig; 9 | import ru.cbrrate.model.CurrencyRate; 10 | 11 | import java.time.LocalDate; 12 | import java.time.format.DateTimeFormatter; 13 | 14 | @Service 15 | @RequiredArgsConstructor 16 | @Slf4j 17 | public class CurrencyRateClientImpl implements CurrencyRateClient { 18 | public static final String DATE_FORMAT = "dd-MM-yyyy"; 19 | private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern(DATE_FORMAT); 20 | 21 | private final CurrencyRateClientConfig config; 22 | 23 | private final HttpClientReactive httpClient; 24 | private final ObjectMapper objectMapper; 25 | 26 | @Override 27 | public Mono getCurrencyRate(String rateType, String currency, LocalDate date) { 28 | log.info("getCurrencyRate rateType:{}, currency:{}, date:{}", rateType, currency, date); 29 | var urlWithParams = String.format("%s/%s/%s/%s", config.getUrl(), rateType, currency, DATE_FORMATTER.format(date)); 30 | 31 | try { 32 | return httpClient.performRequest(urlWithParams) 33 | .map(this::parse); 34 | } catch (HttpClientException ex) { 35 | throw new CurrencyRateClientException("Error from Cbr Client host:" + ex.getMessage()); 36 | } catch (Exception ex) { 37 | log.error("Getting currencyRate error, currency:{}, date:{}", currency, date, ex); 38 | throw new CurrencyRateClientException("Can't get currencyRate. currency:" + currency + ", date:" + date); 39 | } 40 | } 41 | 42 | private CurrencyRate parse(String rateAsString) { 43 | try { 44 | return objectMapper.readValue(rateAsString, CurrencyRate.class); 45 | } catch (Exception ex) { 46 | throw new CurrencyRateClientException("Can't parse string:" + rateAsString); 47 | } 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/clients/HttpClient.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.clients; 2 | 3 | public interface HttpClient { 4 | 5 | String performRequest(String url, String params); 6 | 7 | } 8 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/clients/HttpClientException.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.clients; 2 | 3 | public class HttpClientException extends RuntimeException { 4 | public HttpClientException(String msg) { 5 | super(msg); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/clients/HttpClientJdk.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.clients; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.stereotype.Service; 5 | 6 | import java.net.URI; 7 | import java.net.http.HttpRequest; 8 | import java.net.http.HttpResponse; 9 | 10 | @Service 11 | @Slf4j 12 | public class HttpClientJdk implements HttpClient { 13 | 14 | @Override 15 | public String performRequest(String url, String params) { 16 | var request = HttpRequest.newBuilder() 17 | .uri(URI.create(url)) 18 | .header("Content-Type", "application/json") 19 | .POST(HttpRequest.BodyPublishers.ofString(params)) 20 | .build(); 21 | return doRequest(url, request); 22 | } 23 | 24 | private String doRequest(String url, HttpRequest request) { 25 | try { 26 | var client = java.net.http.HttpClient.newHttpClient(); 27 | var response = client.send(request, HttpResponse.BodyHandlers.ofString()); 28 | return response.body(); 29 | } catch (Exception ex) { 30 | if (ex instanceof InterruptedException) { 31 | Thread.currentThread().interrupt(); 32 | } 33 | log.error("Http request error, url:{}", url, ex); 34 | throw new HttpClientException(ex.getMessage()); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/clients/HttpClientReactive.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.clients; 2 | 3 | import reactor.core.publisher.Mono; 4 | 5 | public interface HttpClientReactive { 6 | 7 | Mono performRequest(String url); 8 | } 9 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/clients/HttpClientReactiveWeb.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.clients; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.http.MediaType; 5 | import org.springframework.stereotype.Service; 6 | import org.springframework.web.reactive.function.client.WebClient; 7 | import reactor.core.publisher.Mono; 8 | 9 | 10 | @Service 11 | @Slf4j 12 | public class HttpClientReactiveWeb implements HttpClientReactive { 13 | 14 | private final WebClient.Builder webBuilder; 15 | 16 | public HttpClientReactiveWeb(WebClient.Builder webBuilder) { 17 | this.webBuilder = webBuilder; 18 | } 19 | 20 | @Override 21 | public Mono performRequest(String url) { 22 | log.info("http request, url:{}", url); 23 | var client = webBuilder.baseUrl(url).build(); 24 | return client.get() 25 | .accept(MediaType.APPLICATION_JSON) 26 | .retrieve() 27 | .bodyToMono(String.class) 28 | .doOnError(error -> log.error("Http request error, url:{}", url, error)) 29 | .doOnNext(val -> log.info("val:{}", val)); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/clients/TelegramClient.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.clients; 2 | 3 | import ru.cbrrate.model.SendMessageRequest; 4 | 5 | 6 | public interface TelegramClient { 7 | 8 | void sendMessage(SendMessageRequest request); 9 | } 10 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/clients/TelegramClientImpl.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.clients; 2 | 3 | import com.fasterxml.jackson.core.JsonProcessingException; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | import lombok.RequiredArgsConstructor; 6 | import lombok.extern.slf4j.Slf4j; 7 | import org.springframework.stereotype.Service; 8 | import ru.cbrrate.config.TelegramClientConfig; 9 | import ru.cbrrate.model.SendMessageRequest; 10 | import ru.cbrrate.services.TelegramException; 11 | 12 | 13 | @Service 14 | @Slf4j 15 | @RequiredArgsConstructor 16 | public class TelegramClientImpl implements TelegramClient { 17 | 18 | private final HttpClient httpClientJdk; 19 | private final ObjectMapper objectMapper; 20 | private final TelegramClientConfig clientConfig; 21 | 22 | @Override 23 | public void sendMessage(SendMessageRequest request) { 24 | try { 25 | var params = objectMapper.writeValueAsString(request); 26 | log.info("params:{}", params); 27 | 28 | var responseAsString = httpClientJdk.performRequest(makeUrl(), params); 29 | log.info("responseAsString:{}", responseAsString); 30 | } catch (JsonProcessingException ex) { 31 | log.error("request:{}", request, ex); 32 | throw new TelegramException(ex); 33 | } 34 | } 35 | 36 | private String makeUrl() { 37 | return String.format("%s/bot%s/%s", clientConfig.getUrl(), clientConfig.getToken(), "sendMessage"); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/config/ApplicationConfig.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.config; 2 | 3 | import lombok.RequiredArgsConstructor; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.springframework.beans.factory.annotation.Value; 6 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | import ru.cbrrate.services.TelegramException; 10 | 11 | 12 | import java.io.IOException; 13 | import java.nio.file.Files; 14 | import java.nio.file.Path; 15 | 16 | @Configuration 17 | @RequiredArgsConstructor 18 | @Slf4j 19 | @EnableConfigurationProperties(CurrencyRateClientConfig.class) 20 | public class ApplicationConfig { 21 | public static final String TELEGRAM_TOKEN_ENV_NAME = "TELEGRAM_TOKEN"; 22 | public static final String TOKEN_FILE = "TOKEN_FILE"; 23 | 24 | @Bean 25 | public TelegramClientConfig telegramClientConfig(@Value("${app.telegram.url}") String url, 26 | @Value("${app.telegram.refresh-rate-ms}") int refreshRateMs) { 27 | var token = System.getProperty(TELEGRAM_TOKEN_ENV_NAME); 28 | if (token == null) { 29 | token = System.getenv(TELEGRAM_TOKEN_ENV_NAME); 30 | } 31 | if (token == null) { 32 | var tokenFile = System.getenv(TOKEN_FILE); 33 | token = readFile(tokenFile); 34 | } 35 | if (token == null) { 36 | log.error("telegram token not found"); 37 | throw new TelegramException("telegram token not found"); 38 | } 39 | return new TelegramClientConfig(url, token, refreshRateMs); 40 | } 41 | 42 | private String readFile(String tokenFile) { 43 | try { 44 | if (tokenFile != null) { 45 | return Files.readString(Path.of(tokenFile)); 46 | } 47 | return null; 48 | } catch (IOException e) { 49 | throw new TelegramException("can't read file:" + tokenFile); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/config/CurrencyRateClientConfig.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.config; 2 | 3 | import lombok.Data; 4 | import org.springframework.boot.context.properties.ConfigurationProperties; 5 | 6 | @Data 7 | @ConfigurationProperties(prefix = "currency-rate-client") 8 | public class CurrencyRateClientConfig { 9 | String url; 10 | } 11 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/config/JsonConfig.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.config; 2 | 3 | import com.fasterxml.jackson.annotation.JsonInclude; 4 | import com.fasterxml.jackson.databind.DeserializationFeature; 5 | import com.fasterxml.jackson.databind.ObjectMapper; 6 | import com.fasterxml.jackson.databind.SerializationFeature; 7 | import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | 11 | @Configuration 12 | public class JsonConfig { 13 | 14 | @Bean 15 | public ObjectMapper objectMapper() { 16 | var objectMapper = new ObjectMapper(); 17 | objectMapper.registerModule(new JavaTimeModule()); 18 | objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); 19 | objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); 20 | objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 21 | objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); 22 | objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); 23 | return objectMapper; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/config/KafkaConfig.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.config; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import lombok.RequiredArgsConstructor; 5 | import lombok.extern.slf4j.Slf4j; 6 | import org.apache.kafka.clients.admin.NewTopic; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.kafka.annotation.EnableKafka; 10 | import org.springframework.kafka.annotation.KafkaListener; 11 | import org.springframework.kafka.config.TopicBuilder; 12 | import ru.cbrrate.model.GetUpdatesResponse; 13 | import ru.cbrrate.services.BotException; 14 | import ru.cbrrate.services.TelegramMessageProcessor; 15 | 16 | @Configuration 17 | @RequiredArgsConstructor 18 | @Slf4j 19 | @EnableKafka 20 | public class KafkaConfig { 21 | 22 | public static final String TOPIC_RATE_REQUESTS = "RATE_REQUESTS"; 23 | public static final String GROUP_ID = "currencyRateBotResponseProvider"; 24 | private final TelegramMessageProcessor telegramMessageProcessor; 25 | private final ObjectMapper objectMapper; 26 | 27 | @Bean 28 | public NewTopic topic() { 29 | return TopicBuilder 30 | .name(TOPIC_RATE_REQUESTS) 31 | .partitions(1) 32 | .replicas(1) 33 | .build(); 34 | } 35 | 36 | @KafkaListener(groupId = GROUP_ID, topics = TOPIC_RATE_REQUESTS) 37 | public void rateRequestListen(String msgAsString) { 38 | GetUpdatesResponse.Message message; 39 | try { 40 | message = objectMapper.readValue(msgAsString, GetUpdatesResponse.Message.class); 41 | } catch (Exception ex) { 42 | log.error("can't parse message:{}", msgAsString, ex); 43 | throw new BotException("can't parse message:" + msgAsString, ex); 44 | } 45 | telegramMessageProcessor.processMessage(message); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/config/TelegramClientConfig.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.config; 2 | 3 | import lombok.Value; 4 | 5 | @Value 6 | public class TelegramClientConfig { 7 | String url; 8 | String token; 9 | int refreshRateMs; 10 | } 11 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/model/CurrencyRate.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonCreator; 4 | import com.fasterxml.jackson.annotation.JsonProperty; 5 | import lombok.Builder; 6 | import lombok.Value; 7 | 8 | @Value 9 | @Builder 10 | public class CurrencyRate { 11 | String charCode; 12 | String nominal; 13 | String value; 14 | 15 | @JsonCreator 16 | public CurrencyRate(@JsonProperty("charCode") String charCode, 17 | @JsonProperty("nominal") String nominal, 18 | @JsonProperty("value") String value) { 19 | this.charCode = charCode; 20 | this.nominal = nominal; 21 | this.value = value; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/model/GetUpdatesResponse.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonCreator; 4 | import com.fasterxml.jackson.annotation.JsonProperty; 5 | import lombok.Builder; 6 | import lombok.Value; 7 | 8 | import java.util.List; 9 | 10 | @Value 11 | @Builder 12 | public class GetUpdatesResponse { 13 | boolean ok; 14 | List result; 15 | 16 | @JsonCreator 17 | public GetUpdatesResponse(@JsonProperty("ok")boolean ok, @JsonProperty("result") List result) { 18 | this.ok = ok; 19 | this.result = result; 20 | } 21 | 22 | @Value 23 | public static class Response { 24 | long updateId; 25 | Message message; 26 | 27 | public Response(long updateId, Message message) { 28 | this.updateId = updateId; 29 | this.message = message; 30 | } 31 | @JsonCreator 32 | public Response(@JsonProperty("update_id") long updateId, @JsonProperty("message") Message message, @JsonProperty("edited_message") Message editedMessage) { 33 | this.updateId = updateId; 34 | this.message = message != null ? message : editedMessage; 35 | } 36 | } 37 | 38 | @Value 39 | public static class Message { 40 | long messageId; 41 | From from; 42 | Chat chat; 43 | long date; 44 | String text; 45 | 46 | @JsonCreator 47 | public Message(@JsonProperty("message_id") long messageId, 48 | @JsonProperty("from") From from, 49 | @JsonProperty("chat") Chat chat, 50 | @JsonProperty("date") long date, 51 | @JsonProperty("text") String text) { 52 | this.messageId = messageId; 53 | this.from = from; 54 | this.chat = chat; 55 | this.date = date; 56 | this.text = text; 57 | } 58 | } 59 | 60 | @Value 61 | public static class From { 62 | long id; 63 | boolean isBot; 64 | String firstName; 65 | String lastName; 66 | String languageCode; 67 | 68 | @JsonCreator 69 | public From(@JsonProperty("id") long id, 70 | @JsonProperty("is_bot") boolean isBot, 71 | @JsonProperty("first_name") String firstName, 72 | @JsonProperty("last_name") String lastName, 73 | @JsonProperty("language_code") String languageCode) { 74 | this.id = id; 75 | this.isBot = isBot; 76 | this.firstName = firstName; 77 | this.lastName = lastName; 78 | this.languageCode = languageCode; 79 | } 80 | } 81 | 82 | @Value 83 | public static class Chat { 84 | long id; 85 | String firstName; 86 | String lastName; 87 | String type; 88 | 89 | @JsonCreator 90 | public Chat(@JsonProperty("id") long id, 91 | @JsonProperty("first_name") String firstName, 92 | @JsonProperty("last_name") String lastName, 93 | @JsonProperty("type") String type) { 94 | this.id = id; 95 | this.firstName = firstName; 96 | this.lastName = lastName; 97 | this.type = type; 98 | } 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/model/MessageTextProcessorResult.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.model; 2 | 3 | import lombok.Value; 4 | 5 | @Value 6 | public class MessageTextProcessorResult { 7 | String okReply; 8 | String failReply; 9 | } 10 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/model/SendMessageRequest.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | import lombok.Value; 5 | 6 | @Value 7 | public class SendMessageRequest { 8 | 9 | @JsonProperty("chat_id") 10 | long chatId; 11 | 12 | @JsonProperty("text") 13 | String text; 14 | 15 | @JsonProperty("reply_to_message_id") 16 | long replyToMessageId; 17 | } 18 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/services/BotException.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | public class BotException extends RuntimeException { 4 | public BotException(String message, Throwable cause) { 5 | super(message, cause); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/services/DateTimeProvider.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | import java.time.LocalDateTime; 4 | 5 | public interface DateTimeProvider { 6 | LocalDateTime get(); 7 | } 8 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/services/DateTimeProviderCurrent.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | import org.springframework.stereotype.Service; 4 | 5 | import java.time.LocalDateTime; 6 | 7 | @Service 8 | public class DateTimeProviderCurrent implements DateTimeProvider { 9 | @Override 10 | public LocalDateTime get() { 11 | return LocalDateTime.now(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/services/TelegramException.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | public class TelegramException extends RuntimeException { 4 | public TelegramException(Throwable cause) { 5 | super(cause); 6 | } 7 | 8 | public TelegramException(String message) { 9 | super(message); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/services/TelegramMessageProcessor.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | import ru.cbrrate.model.GetUpdatesResponse; 4 | 5 | public interface TelegramMessageProcessor { 6 | void processMessage(GetUpdatesResponse.Message message); 7 | } 8 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/services/TelegramMessageProcessorImpl.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.beans.factory.annotation.Qualifier; 5 | import org.springframework.stereotype.Service; 6 | import ru.cbrrate.clients.TelegramClient; 7 | import ru.cbrrate.model.GetUpdatesResponse; 8 | import ru.cbrrate.model.SendMessageRequest; 9 | import ru.cbrrate.services.processors.MessageTextProcessor; 10 | 11 | 12 | @Slf4j 13 | @Service 14 | public class TelegramMessageProcessorImpl implements TelegramMessageProcessor { 15 | 16 | private final TelegramClient telegramClient; 17 | private final MessageTextProcessor messageTextProcessor; 18 | 19 | public TelegramMessageProcessorImpl(TelegramClient telegramClient, 20 | @Qualifier("messageTextProcessorGeneral") 21 | MessageTextProcessor messageTextProcessor) { 22 | this.telegramClient = telegramClient; 23 | this.messageTextProcessor = messageTextProcessor; 24 | } 25 | 26 | @Override 27 | public void processMessage(GetUpdatesResponse.Message message) { 28 | log.info("message:{}", message); 29 | 30 | var chatId = message.getChat().getId(); 31 | var messageId = message.getMessageId(); 32 | 33 | messageTextProcessor.process(message.getText()) 34 | .doOnNext(result -> { 35 | var replay = result.getFailReply() == null ? result.getOkReply() : result.getFailReply(); 36 | var sendMessageRequest = new SendMessageRequest(chatId, replay, messageId); 37 | telegramClient.sendMessage(sendMessageRequest); 38 | } 39 | ).subscribe(); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/services/processors/CmdRegistry.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services.processors; 2 | 3 | public enum CmdRegistry { 4 | START("/start", "messageTextProcessorStart"); 5 | 6 | private final String cmd; 7 | private final String handlerName; 8 | 9 | CmdRegistry(String cmd, String handlerName) { 10 | this.cmd = cmd; 11 | this.handlerName = handlerName; 12 | } 13 | 14 | public String getCmd() { 15 | return cmd; 16 | } 17 | 18 | public String getHandlerName() { 19 | return handlerName; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/services/processors/MessageTextProcessor.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services.processors; 2 | 3 | import reactor.core.publisher.Mono; 4 | import ru.cbrrate.model.MessageTextProcessorResult; 5 | 6 | public interface MessageTextProcessor { 7 | Mono process(String msgText); 8 | } 9 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/services/processors/MessageTextProcessorGeneral.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services.processors; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.beans.factory.annotation.Qualifier; 5 | import org.springframework.context.ApplicationContext; 6 | import org.springframework.stereotype.Service; 7 | import reactor.core.publisher.Mono; 8 | import ru.cbrrate.model.MessageTextProcessorResult; 9 | 10 | 11 | @Slf4j 12 | @Service("messageTextProcessorGeneral") 13 | public class MessageTextProcessorGeneral implements MessageTextProcessor { 14 | 15 | private final ApplicationContext applicationContext; 16 | private final MessageTextProcessor messageTextProcessorRate; 17 | 18 | public MessageTextProcessorGeneral(ApplicationContext applicationContext, 19 | @Qualifier("messageTextProcessorRate") MessageTextProcessor messageTextProcessor) { 20 | this.applicationContext = applicationContext; 21 | this.messageTextProcessorRate = messageTextProcessor; 22 | } 23 | 24 | @Override 25 | public Mono process(String msgText) { 26 | for(var cmd : CmdRegistry.values()) { 27 | if (cmd.getCmd().equals(msgText)) { 28 | var handler = applicationContext.getBean(cmd.getHandlerName(), MessageTextProcessor.class); 29 | return handler.process(msgText); 30 | } 31 | } 32 | return messageTextProcessorRate.process(msgText); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/services/processors/MessageTextProcessorRate.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services.processors; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.springframework.stereotype.Service; 6 | import reactor.core.publisher.Mono; 7 | import ru.cbrrate.clients.CurrencyRateClient; 8 | import ru.cbrrate.model.MessageTextProcessorResult; 9 | import ru.cbrrate.services.DateTimeProvider; 10 | 11 | import java.time.LocalDate; 12 | import java.time.format.DateTimeFormatter; 13 | 14 | 15 | @Slf4j 16 | @AllArgsConstructor 17 | @Service("messageTextProcessorRate") 18 | public class MessageTextProcessorRate implements MessageTextProcessor { 19 | private static final String CBR_RATE_CONST = "CBR"; 20 | private static final String DATE_FORMAT_ZERO = "dd-MM-yyyy"; 21 | private static final String DATE_FORMAT = "d-MM-yyyy"; 22 | private static final DateTimeFormatter DATE_FORMATTER_ZERO = DateTimeFormatter.ofPattern(DATE_FORMAT_ZERO); 23 | private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern(DATE_FORMAT); 24 | 25 | private final CurrencyRateClient currencyRateClient; 26 | private final DateTimeProvider dateTimeProvider; 27 | 28 | @Override 29 | public Mono process(String msgText) { 30 | log.info("msgText:{}", msgText); 31 | 32 | var textParts = msgText.split(" "); 33 | 34 | if (textParts.length < 1 || textParts.length > 3) { 35 | return Mono.just(new MessageTextProcessorResult(null, Messages.EXPECTED_FORMAT_MESSAGE.getText())); 36 | } 37 | 38 | String rateType = null; 39 | String currency = null; 40 | String dateAsString = null; 41 | LocalDate date = null; 42 | 43 | if (textParts.length == 3) { 44 | rateType = textParts[0]; 45 | currency = textParts[1]; 46 | dateAsString = textParts[2]; 47 | } 48 | if (textParts.length == 2) { 49 | rateType = CBR_RATE_CONST; 50 | currency = textParts[0]; 51 | dateAsString = textParts[1]; 52 | } 53 | 54 | if (textParts.length == 1) { 55 | rateType = CBR_RATE_CONST; 56 | currency = textParts[0]; 57 | date = dateTimeProvider.get().toLocalDate(); 58 | } 59 | 60 | if (textParts.length == 3 || textParts.length == 2) { 61 | try { 62 | date = parseDate(dateAsString); 63 | } catch (Exception ex) { 64 | log.error("parsing error, string:{}", dateAsString, ex); 65 | 66 | return Mono.just(new MessageTextProcessorResult(null, Messages.DATA_FORMAT_MESSAGE.getText())); 67 | } 68 | } 69 | 70 | if (rateType == null || currency == null) { 71 | log.error("rateType:{} or currency:{} is null", rateType, currency); 72 | throw new IllegalArgumentException("rateType:" + rateType + " or currency:" + currency + " is null"); 73 | } 74 | 75 | return currencyRateClient.getCurrencyRate(rateType.toUpperCase(), currency.toUpperCase(), date) 76 | .map(rate -> new MessageTextProcessorResult(rate.getValue(), null)); 77 | } 78 | 79 | private LocalDate parseDate(String dateAsString) { 80 | try { 81 | return LocalDate.parse(dateAsString, DATE_FORMATTER_ZERO); 82 | } catch (Exception ex) { 83 | return LocalDate.parse(dateAsString, DATE_FORMATTER); 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/services/processors/MessageTextProcessorStart.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services.processors; 2 | 3 | 4 | import org.springframework.stereotype.Service; 5 | import reactor.core.publisher.Mono; 6 | import ru.cbrrate.model.MessageTextProcessorResult; 7 | 8 | import static ru.cbrrate.services.processors.Messages.EXPECTED_FORMAT_MESSAGE; 9 | 10 | @Service("messageTextProcessorStart") 11 | public class MessageTextProcessorStart implements MessageTextProcessor { 12 | @Override 13 | public Mono process(String msgText) { 14 | return Mono.just(new MessageTextProcessorResult(EXPECTED_FORMAT_MESSAGE.getText(), null)); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/java/ru/cbrrate/services/processors/Messages.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services.processors; 2 | 3 | public enum Messages { 4 | DATA_FORMAT_MESSAGE("Ожидаемый формат даты:\n" + "dd-MM-yyyy, Пример: 22-01-2021"), 5 | EXPECTED_FORMAT_MESSAGE(""" 6 | Возможные команды ("/" не нужен): 7 | Курс на дату: CBR USD dd-MM-yyyy 8 | Курс ЦБ на дату: EUR dd-MM-yyyy 9 | Курс ЦБ на сегодня: USD 10 | """); 11 | 12 | private final String text; 13 | 14 | Messages(String text) { 15 | this.text = text; 16 | } 17 | 18 | public String getText() { 19 | return text; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/resources/application-local.yml: -------------------------------------------------------------------------------- 1 | currency-rate-client: 2 | url: "http://localhost:8080/api/v1/currencyRate" 3 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/resources/application-prod.yml: -------------------------------------------------------------------------------- 1 | currency-rate-client: 2 | url: "http://currency-rate-client.default.svc.cluster.local/api/v1/currencyRate" 3 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8083 3 | 4 | 5 | spring: 6 | kafka: 7 | bootstrap-servers: "localhost:9092" 8 | consumer: 9 | auto-offset-reset: earliest 10 | 11 | management: 12 | server: 13 | port: 8093 14 | endpoints: 15 | enabled-by-default: false 16 | endpoint: 17 | health: 18 | enabled: true 19 | probes: 20 | enabled: true 21 | 22 | app: 23 | rest: 24 | api: 25 | prefix: /api 26 | telegram: 27 | url: https://api.telegram.org 28 | refresh-rate-ms: 3000 29 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/test/java/ru/cbrrate/services/KafkaBase.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | import org.apache.kafka.clients.admin.AdminClient; 4 | import org.apache.kafka.clients.admin.NewTopic; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.boot.test.util.TestPropertyValues; 8 | import org.springframework.context.ApplicationContextInitializer; 9 | import org.springframework.context.ConfigurableApplicationContext; 10 | import org.testcontainers.containers.KafkaContainer; 11 | import org.testcontainers.utility.DockerImageName; 12 | 13 | import java.util.Collection; 14 | import java.util.Map; 15 | import java.util.concurrent.ExecutionException; 16 | import java.util.concurrent.TimeUnit; 17 | import java.util.concurrent.TimeoutException; 18 | 19 | import static org.apache.kafka.clients.CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG; 20 | 21 | class KafkaBase { 22 | private static final Logger log = LoggerFactory.getLogger(KafkaBase.class); 23 | 24 | private final static KafkaContainer kafka = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:7.0.0")); 25 | private static boolean started = false; 26 | 27 | public static void start(Collection topics) throws ExecutionException, InterruptedException, TimeoutException { 28 | if (!started) { 29 | kafka.start(); 30 | 31 | log.info("topics creation..."); 32 | try (var admin = AdminClient.create(Map.of(BOOTSTRAP_SERVERS_CONFIG, kafka.getBootstrapServers()))) { 33 | var result = admin.createTopics(topics); 34 | 35 | for(var topicResult: result.values().values()) { 36 | topicResult.get(10, TimeUnit.SECONDS); 37 | } 38 | } 39 | log.info("topics created"); 40 | started = true; 41 | } 42 | } 43 | 44 | public static class Initializer implements ApplicationContextInitializer { 45 | @Override 46 | public void initialize(ConfigurableApplicationContext applicationContext) { 47 | if (started) { 48 | TestPropertyValues.of( 49 | "spring.kafka.bootstrap-servers:" + kafka.getBootstrapServers() 50 | ).applyTo(applicationContext.getEnvironment()); 51 | } 52 | } 53 | } 54 | } -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/test/java/ru/cbrrate/services/MessageTextProcessorRateTest.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import reactor.core.publisher.Mono; 5 | import reactor.test.StepVerifier; 6 | import ru.cbrrate.clients.CurrencyRateClient; 7 | import ru.cbrrate.model.CurrencyRate; 8 | import ru.cbrrate.model.MessageTextProcessorResult; 9 | import ru.cbrrate.services.processors.MessageTextProcessorRate; 10 | import ru.cbrrate.services.processors.Messages; 11 | 12 | import java.time.LocalDate; 13 | import java.time.LocalDateTime; 14 | 15 | import static org.mockito.Mockito.mock; 16 | import static org.mockito.Mockito.when; 17 | 18 | class MessageTextProcessorRateTest { 19 | 20 | @Test 21 | void processTestAgrs3() { 22 | //given 23 | var currencyRateClient = mock(CurrencyRateClient.class); 24 | var currencyRate = new CurrencyRate("USD", "1", "49.4"); 25 | var resultExpected = new MessageTextProcessorResult(currencyRate.getValue(), null); 26 | when(currencyRateClient.getCurrencyRate("CBR", "USD", LocalDate.of(2021, 2, 3))) 27 | .thenReturn(Mono.just(currencyRate)); 28 | 29 | var messageTextProcessor = new MessageTextProcessorRate(currencyRateClient, 30 | () -> LocalDateTime.of(2021, 2, 3,1,1,1)); 31 | var msg = "CBR USD 3-02-2021"; 32 | 33 | //when 34 | var result = messageTextProcessor.process(msg); 35 | 36 | //then 37 | StepVerifier 38 | .create(result) 39 | .expectNext(resultExpected) 40 | .expectComplete() 41 | .verify(); 42 | } 43 | 44 | @Test 45 | void processTestAgrs2() { 46 | //given 47 | var currencyRateClient = mock(CurrencyRateClient.class); 48 | var currencyRate = new CurrencyRate("USD", "1", "49.4"); 49 | var resultExpected = new MessageTextProcessorResult(currencyRate.getValue(), null); 50 | when(currencyRateClient.getCurrencyRate("CBR", "USD", LocalDate.of(2021, 2, 3))) 51 | .thenReturn(Mono.just(currencyRate)); 52 | 53 | var messageTextProcessor = new MessageTextProcessorRate(currencyRateClient, 54 | () -> LocalDateTime.of(2021, 2, 3,1,1,1)); 55 | var msg = "USD 03-02-2021"; 56 | 57 | //when 58 | var result = messageTextProcessor.process(msg); 59 | 60 | //then 61 | StepVerifier 62 | .create(result) 63 | .expectNext(resultExpected) 64 | .expectComplete() 65 | .verify(); 66 | } 67 | 68 | @Test 69 | void processTestAgrs1() { 70 | //given 71 | var currencyRateClient = mock(CurrencyRateClient.class); 72 | var currencyRate = new CurrencyRate("USD", "1", "49.4"); 73 | var resultExpected = new MessageTextProcessorResult(currencyRate.getValue(), null); 74 | when(currencyRateClient.getCurrencyRate("CBR", "USD", LocalDate.of(2021, 2, 3))) 75 | .thenReturn(Mono.just(currencyRate)); 76 | 77 | var messageTextProcessor = new MessageTextProcessorRate(currencyRateClient, 78 | () -> LocalDateTime.of(2021, 2, 3,1,1,1)); 79 | var msg = "USD"; 80 | 81 | //when 82 | var result = messageTextProcessor.process(msg); 83 | 84 | //then 85 | StepVerifier 86 | .create(result) 87 | .expectNext(resultExpected) 88 | .expectComplete() 89 | .verify(); 90 | } 91 | 92 | @Test 93 | void processTestAgrsWrongData() { 94 | //given 95 | var currencyRateClient = mock(CurrencyRateClient.class); 96 | var currencyRate = new CurrencyRate("USD", "1", "49.4"); 97 | var resultExpected = new MessageTextProcessorResult(null, Messages.DATA_FORMAT_MESSAGE.getText()); 98 | when(currencyRateClient.getCurrencyRate("CBR", "USD", LocalDate.of(2021, 2, 3))) 99 | .thenReturn(Mono.just(currencyRate)); 100 | 101 | var messageTextProcessor = new MessageTextProcessorRate(currencyRateClient, 102 | () -> LocalDateTime.of(2021, 2, 3,1,1,1)); 103 | var msg = "USD 2021.03.01"; 104 | 105 | //when 106 | var result = messageTextProcessor.process(msg); 107 | 108 | //then 109 | StepVerifier 110 | .create(result) 111 | .expectNext(resultExpected) 112 | .expectComplete() 113 | .verify(); 114 | } 115 | 116 | @Test 117 | void processTestAgrsWrongFormat() { 118 | //given 119 | var currencyRateClient = mock(CurrencyRateClient.class); 120 | var currencyRate = new CurrencyRate("USD", "1", "49.4"); 121 | var resultExpected = new MessageTextProcessorResult(null, Messages.EXPECTED_FORMAT_MESSAGE.getText()); 122 | when(currencyRateClient.getCurrencyRate("CBR", "USD", LocalDate.of(2021, 2, 3))) 123 | .thenReturn(Mono.just(currencyRate)); 124 | 125 | var messageTextProcessor = new MessageTextProcessorRate(currencyRateClient, 126 | () -> LocalDateTime.of(2021, 2, 3,1,1,1)); 127 | var msg = "RRR RRR USD 03-02-2021"; 128 | 129 | //when 130 | var result = messageTextProcessor.process(msg); 131 | 132 | //then 133 | StepVerifier 134 | .create(result) 135 | .expectNext(resultExpected) 136 | .expectComplete() 137 | .verify(); 138 | } 139 | } -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/test/java/ru/cbrrate/services/TelegramClientTest.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import ru.cbrrate.clients.HttpClientJdk; 5 | import ru.cbrrate.clients.TelegramClientImpl; 6 | import ru.cbrrate.config.JsonConfig; 7 | import ru.cbrrate.config.TelegramClientConfig; 8 | import ru.cbrrate.model.SendMessageRequest; 9 | 10 | import static org.assertj.core.api.Assertions.assertThat; 11 | import static org.mockito.Mockito.*; 12 | 13 | class TelegramClientTest { 14 | 15 | @Test 16 | void sendMessageTest() { 17 | //given 18 | var clientConfig = new TelegramClientConfig("https://api.telegram.org", "G23FD", 100); 19 | var request = new SendMessageRequest(11, "testOk", 173); 20 | 21 | var httpClientJdk = mock(HttpClientJdk.class); 22 | 23 | var objectMapper = new JsonConfig().objectMapper(); 24 | var client = new TelegramClientImpl(httpClientJdk, objectMapper, clientConfig); 25 | 26 | //when 27 | client.sendMessage(request); 28 | 29 | //then 30 | var expectedUrl = String.format("%s/bot%s/sendMessage", clientConfig.getUrl(), clientConfig.getToken()); 31 | var expectedParams = String.format("{\"chat_id\":%d,\"text\":\"%s\",\"reply_to_message_id\":%d}", 32 | request.getChatId(), request.getText(), request.getReplyToMessageId()); 33 | 34 | verify(httpClientJdk).performRequest(expectedUrl, expectedParams); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /currencyRateBotResponseProvider/src/test/java/ru/cbrrate/services/TelegramMessageProcessorImplTest.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import org.apache.kafka.clients.admin.NewTopic; 5 | 6 | import org.junit.jupiter.api.BeforeAll; 7 | import org.junit.jupiter.api.Test; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | import org.springframework.boot.test.mock.mockito.MockBean; 11 | 12 | import org.springframework.kafka.core.KafkaTemplate; 13 | import org.springframework.test.context.ContextConfiguration; 14 | import reactor.core.publisher.Mono; 15 | import ru.cbrrate.clients.TelegramClient; 16 | import ru.cbrrate.model.GetUpdatesResponse; 17 | import ru.cbrrate.model.SendMessageRequest; 18 | 19 | import ru.cbrrate.model.MessageTextProcessorResult; 20 | import ru.cbrrate.services.processors.MessageTextProcessorRate; 21 | 22 | import java.util.List; 23 | import java.util.Random; 24 | import java.util.concurrent.ExecutionException; 25 | import java.util.concurrent.TimeoutException; 26 | 27 | 28 | import static org.mockito.Mockito.timeout; 29 | import static org.mockito.Mockito.verify; 30 | import static org.mockito.Mockito.when; 31 | import static ru.cbrrate.config.ApplicationConfig.TELEGRAM_TOKEN_ENV_NAME; 32 | import static ru.cbrrate.config.KafkaConfig.TOPIC_RATE_REQUESTS; 33 | 34 | @SpringBootTest 35 | @ContextConfiguration(initializers = {KafkaBase.Initializer.class}) 36 | class TelegramMessageProcessorImplTest { 37 | 38 | static { 39 | System.setProperty(TELEGRAM_TOKEN_ENV_NAME, "test"); 40 | } 41 | 42 | @Autowired 43 | private ObjectMapper objectMapper; 44 | 45 | @Autowired 46 | private KafkaTemplate kafkaTemplate; 47 | 48 | @MockBean 49 | private MessageTextProcessorRate messageTextProcessorRate; 50 | 51 | @MockBean 52 | private TelegramClient telegramClient; 53 | 54 | @BeforeAll 55 | public static void init() throws ExecutionException, InterruptedException, TimeoutException { 56 | KafkaBase.start(List.of(new NewTopic(TOPIC_RATE_REQUESTS, 1, (short) 1))); 57 | } 58 | 59 | @Test 60 | void processMessageTest() { 61 | int timeoutMs = 1_000; 62 | var text = "text"; 63 | var reply = "Ok"; 64 | when(messageTextProcessorRate.process(text)).thenReturn(Mono.just(new MessageTextProcessorResult(reply, null))); 65 | 66 | var response1 = makeGetUpdatesResponse(1, text); 67 | putResponseToKafka(response1); 68 | var response2 = makeGetUpdatesResponse(2, text); 69 | putResponseToKafka(response2); 70 | 71 | //first run 72 | var sendMessageRequest1 = new SendMessageRequest(response1.getResult().get(0).getMessage().getChat().getId(), 73 | reply, response1.getResult().get(0).getMessage().getMessageId()); 74 | 75 | var sendMessageRequest2 = new SendMessageRequest(response1.getResult().get(1).getMessage().getChat().getId(), 76 | reply, response1.getResult().get(1).getMessage().getMessageId()); 77 | 78 | verify(telegramClient, timeout(timeoutMs)).sendMessage(sendMessageRequest1); 79 | verify(telegramClient, timeout(timeoutMs)).sendMessage(sendMessageRequest2); 80 | 81 | //second run 82 | var sendMessageRequest3 = new SendMessageRequest(response2.getResult().get(0).getMessage().getChat().getId(), 83 | reply, response2.getResult().get(0).getMessage().getMessageId()); 84 | 85 | var sendMessageRequest4 = new SendMessageRequest(response2.getResult().get(1).getMessage().getChat().getId(), 86 | reply, response2.getResult().get(1).getMessage().getMessageId()); 87 | 88 | verify(telegramClient, timeout(timeoutMs)).sendMessage(sendMessageRequest3); 89 | verify(telegramClient, timeout(timeoutMs)).sendMessage(sendMessageRequest4); 90 | } 91 | 92 | private void putResponseToKafka(GetUpdatesResponse response) { 93 | response.getResult().stream() 94 | .map(GetUpdatesResponse.Response::getMessage) 95 | .map(this::writeValueAsString) 96 | .forEach(this::sendSync); 97 | } 98 | 99 | private void sendSync(String val) { 100 | try { 101 | kafkaTemplate.send(TOPIC_RATE_REQUESTS, val); 102 | } catch (Exception ex) { 103 | throw new RuntimeException(ex); 104 | } 105 | } 106 | 107 | private String writeValueAsString(GetUpdatesResponse.Message msg) { 108 | try { 109 | return objectMapper.writeValueAsString(msg); 110 | } catch (Exception ex) { 111 | throw new RuntimeException(ex); 112 | } 113 | } 114 | 115 | private GetUpdatesResponse makeGetUpdatesResponse(long updateId, String text) { 116 | var from = new GetUpdatesResponse.From(506L, false, "Ivan", "Petrov", "en"); 117 | var chat = new GetUpdatesResponse.Chat(506L, "Ivan", "Petrov", "private"); 118 | var random = new Random(); 119 | var message1 = new GetUpdatesResponse.Message(random.nextLong(), from, chat, 1631970287, text); 120 | var message2 = new GetUpdatesResponse.Message(random.nextLong(), from, chat, 1631970287, text); 121 | 122 | return new GetUpdatesResponse(true, List.of(new GetUpdatesResponse.Response(updateId, message1), 123 | new GetUpdatesResponse.Response(updateId + 1, message2))); 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /currencyRateBotStatistics/HttpRequests.http: -------------------------------------------------------------------------------- 1 | ### 2 | POST https://api.telegram.org/bot[token]/getUpdates 3 | Accept: */* 4 | Content-Type: application/json 5 | Cache-Control: no-cache 6 | 7 | { 8 | "offset": 953141214 9 | } 10 | 11 | ### 12 | POST https://api.telegram.org/bot[token]/sendMessage 13 | Accept: */* 14 | Content-Type: application/json 15 | Cache-Control: no-cache 16 | 17 | { 18 | "chat_id": "506783844", 19 | "text": "testOk2", 20 | "reply_to_message_id": "4" 21 | } 22 | ############################################### 23 | ### 24 | GET http://localhost:8092/actuator/health 25 | Accept: */* 26 | Content-Type: application/json 27 | Cache-Control: no-cache 28 | 29 | ### 30 | GET http://localhost:8092/actuator/health/liveness 31 | Accept: */* 32 | Content-Type: application/json 33 | Cache-Control: no-cache 34 | 35 | ### 36 | GET http://localhost:8092/actuator/health/readiness 37 | Accept: */* 38 | Content-Type: application/json 39 | Cache-Control: no-cache 40 | -------------------------------------------------------------------------------- /currencyRateBotStatistics/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.springframework.boot' 4 | id 'com.google.cloud.tools.jib' 5 | } 6 | 7 | apply from: 'jib.gradle' 8 | 9 | sourceCompatibility = JavaVersion.VERSION_17 10 | targetCompatibility = JavaVersion.VERSION_17 11 | 12 | dependencies { 13 | implementation 'org.springframework.boot:spring-boot-starter-webflux' 14 | implementation 'org.springframework.boot:spring-boot-starter-actuator' 15 | implementation 'org.springframework.kafka:spring-kafka' 16 | implementation 'ch.qos.logback:logback-classic' 17 | 18 | compileOnly 'org.projectlombok:lombok' 19 | testCompileOnly 'org.projectlombok:lombok' 20 | annotationProcessor 'org.projectlombok:lombok' 21 | 22 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 23 | testImplementation 'io.projectreactor:reactor-test' 24 | testImplementation 'org.testcontainers:junit-jupiter' 25 | testImplementation 'org.testcontainers:kafka' 26 | } 27 | 28 | test { 29 | useJUnitPlatform() 30 | testLogging { 31 | events "passed", "skipped", "failed" 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /currencyRateBotStatistics/jib.gradle: -------------------------------------------------------------------------------- 1 | jib { 2 | container.creationTime = 'USE_CURRENT_TIMESTAMP' 3 | from { 4 | image = 'bellsoft/liberica-openjdk-alpine-musl:17.0.1-12' 5 | } 6 | to { 7 | tags = ['v1', 'latest'] 8 | image = 'registry.gitlab.com/petrelevich/dockerregistry/currency-rate-bot-statistics' 9 | auth { 10 | username = gitlabUser 11 | password = gitlabPassword 12 | } 13 | } 14 | } 15 | // ./gradlew jibDockerBuild 16 | 17 | //docker login registry.gitlab.com 18 | //docker run -p 8080:8080 registry.gitlab.com/petrelevich/dockerregistry/currency-rate-bot-statistics 19 | 20 | //docker push registry.gitlab.com/petrelevich/dockerregistry/currency-rate-bot-statistics:latest 21 | -------------------------------------------------------------------------------- /currencyRateBotStatistics/src/main/java/ru/cbrrate/CurrencyRateBotStatistics.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate; 2 | 3 | 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.boot.builder.SpringApplicationBuilder; 6 | 7 | 8 | @SpringBootApplication 9 | public class CurrencyRateBotStatistics { 10 | public static void main(String[] args) { 11 | new SpringApplicationBuilder().sources(CurrencyRateBotStatistics.class).run(args); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /currencyRateBotStatistics/src/main/java/ru/cbrrate/config/JsonConfig.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.config; 2 | 3 | import com.fasterxml.jackson.annotation.JsonInclude; 4 | import com.fasterxml.jackson.databind.DeserializationFeature; 5 | import com.fasterxml.jackson.databind.ObjectMapper; 6 | import com.fasterxml.jackson.databind.SerializationFeature; 7 | import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | 11 | @Configuration 12 | public class JsonConfig { 13 | 14 | @Bean 15 | public ObjectMapper objectMapper() { 16 | var objectMapper = new ObjectMapper(); 17 | objectMapper.registerModule(new JavaTimeModule()); 18 | objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); 19 | objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); 20 | objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 21 | objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); 22 | objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); 23 | return objectMapper; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /currencyRateBotStatistics/src/main/java/ru/cbrrate/config/KafkaConfig.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.config; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import lombok.RequiredArgsConstructor; 5 | import lombok.extern.slf4j.Slf4j; 6 | import org.apache.kafka.clients.admin.NewTopic; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.kafka.annotation.EnableKafka; 10 | import org.springframework.kafka.annotation.KafkaListener; 11 | import org.springframework.kafka.config.TopicBuilder; 12 | import ru.cbrrate.model.GetUpdatesResponse; 13 | import ru.cbrrate.services.BotException; 14 | import ru.cbrrate.services.TelegramRequestStatisticsProcessor; 15 | 16 | @Configuration 17 | @RequiredArgsConstructor 18 | @Slf4j 19 | @EnableKafka 20 | public class KafkaConfig { 21 | 22 | public static final String TOPIC_RATE_REQUESTS = "RATE_REQUESTS"; 23 | public static final String GROUP_ID = "RateRequestsProcessor"; 24 | private final TelegramRequestStatisticsProcessor telegramRequestStatisticsProcessor; 25 | private final ObjectMapper objectMapper; 26 | 27 | @Bean 28 | public NewTopic topic() { 29 | return TopicBuilder 30 | .name(TOPIC_RATE_REQUESTS) 31 | .partitions(1) 32 | .replicas(1) 33 | .build(); 34 | } 35 | 36 | @KafkaListener(groupId = GROUP_ID, topics = TOPIC_RATE_REQUESTS) 37 | public void rateRequestListen(String msgAsString) { 38 | GetUpdatesResponse.Message message; 39 | try { 40 | message = objectMapper.readValue(msgAsString, GetUpdatesResponse.Message.class); 41 | } catch (Exception ex) { 42 | log.error("can't parse message:{}", msgAsString, ex); 43 | throw new BotException("can't parse message:" + msgAsString, ex); 44 | } 45 | telegramRequestStatisticsProcessor.processMessage(message); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /currencyRateBotStatistics/src/main/java/ru/cbrrate/model/CurrencyRate.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonCreator; 4 | import com.fasterxml.jackson.annotation.JsonProperty; 5 | import lombok.Builder; 6 | import lombok.Value; 7 | 8 | @Value 9 | @Builder 10 | public class CurrencyRate { 11 | String charCode; 12 | String nominal; 13 | String value; 14 | 15 | @JsonCreator 16 | public CurrencyRate(@JsonProperty("charCode") String charCode, 17 | @JsonProperty("nominal") String nominal, 18 | @JsonProperty("value") String value) { 19 | this.charCode = charCode; 20 | this.nominal = nominal; 21 | this.value = value; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /currencyRateBotStatistics/src/main/java/ru/cbrrate/model/GetUpdatesResponse.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonCreator; 4 | import com.fasterxml.jackson.annotation.JsonProperty; 5 | import lombok.Builder; 6 | import lombok.Value; 7 | 8 | import java.util.List; 9 | 10 | @Value 11 | @Builder 12 | public class GetUpdatesResponse { 13 | boolean ok; 14 | List result; 15 | 16 | @JsonCreator 17 | public GetUpdatesResponse(@JsonProperty("ok")boolean ok, @JsonProperty("result") List result) { 18 | this.ok = ok; 19 | this.result = result; 20 | } 21 | 22 | @Value 23 | public static class Response { 24 | long updateId; 25 | Message message; 26 | 27 | public Response(long updateId, Message message) { 28 | this.updateId = updateId; 29 | this.message = message; 30 | } 31 | @JsonCreator 32 | public Response(@JsonProperty("update_id") long updateId, @JsonProperty("message") Message message, @JsonProperty("edited_message") Message editedMessage) { 33 | this.updateId = updateId; 34 | this.message = message != null ? message : editedMessage; 35 | } 36 | } 37 | 38 | @Value 39 | public static class Message { 40 | long messageId; 41 | From from; 42 | Chat chat; 43 | long date; 44 | String text; 45 | 46 | @JsonCreator 47 | public Message(@JsonProperty("message_id") long messageId, 48 | @JsonProperty("from") From from, 49 | @JsonProperty("chat") Chat chat, 50 | @JsonProperty("date") long date, 51 | @JsonProperty("text") String text) { 52 | this.messageId = messageId; 53 | this.from = from; 54 | this.chat = chat; 55 | this.date = date; 56 | this.text = text; 57 | } 58 | } 59 | 60 | @Value 61 | public static class From { 62 | long id; 63 | boolean isBot; 64 | String firstName; 65 | String lastName; 66 | String languageCode; 67 | 68 | @JsonCreator 69 | public From(@JsonProperty("id") long id, 70 | @JsonProperty("is_bot") boolean isBot, 71 | @JsonProperty("first_name") String firstName, 72 | @JsonProperty("last_name") String lastName, 73 | @JsonProperty("language_code") String languageCode) { 74 | this.id = id; 75 | this.isBot = isBot; 76 | this.firstName = firstName; 77 | this.lastName = lastName; 78 | this.languageCode = languageCode; 79 | } 80 | } 81 | 82 | @Value 83 | public static class Chat { 84 | long id; 85 | String firstName; 86 | String lastName; 87 | String type; 88 | 89 | @JsonCreator 90 | public Chat(@JsonProperty("id") long id, 91 | @JsonProperty("first_name") String firstName, 92 | @JsonProperty("last_name") String lastName, 93 | @JsonProperty("type") String type) { 94 | this.id = id; 95 | this.firstName = firstName; 96 | this.lastName = lastName; 97 | this.type = type; 98 | } 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /currencyRateBotStatistics/src/main/java/ru/cbrrate/model/MessageTextProcessorResult.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.model; 2 | 3 | import lombok.Value; 4 | 5 | @Value 6 | public class MessageTextProcessorResult { 7 | String okReply; 8 | String failReply; 9 | } 10 | -------------------------------------------------------------------------------- /currencyRateBotStatistics/src/main/java/ru/cbrrate/model/SendMessageRequest.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | import lombok.Value; 5 | 6 | @Value 7 | public class SendMessageRequest { 8 | 9 | @JsonProperty("chat_id") 10 | long chatId; 11 | 12 | @JsonProperty("text") 13 | String text; 14 | 15 | @JsonProperty("reply_to_message_id") 16 | long replyToMessageId; 17 | } 18 | -------------------------------------------------------------------------------- /currencyRateBotStatistics/src/main/java/ru/cbrrate/services/BotException.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | public class BotException extends RuntimeException { 4 | public BotException(String message, Throwable cause) { 5 | super(message, cause); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /currencyRateBotStatistics/src/main/java/ru/cbrrate/services/DateTimeProvider.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | import java.time.LocalDateTime; 4 | 5 | public interface DateTimeProvider { 6 | LocalDateTime get(); 7 | } 8 | -------------------------------------------------------------------------------- /currencyRateBotStatistics/src/main/java/ru/cbrrate/services/DateTimeProviderCurrent.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | import org.springframework.stereotype.Service; 4 | 5 | import java.time.LocalDateTime; 6 | 7 | @Service 8 | public class DateTimeProviderCurrent implements DateTimeProvider { 9 | @Override 10 | public LocalDateTime get() { 11 | return LocalDateTime.now(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /currencyRateBotStatistics/src/main/java/ru/cbrrate/services/TelegramRequestStatisticsProcessor.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | import ru.cbrrate.model.GetUpdatesResponse; 4 | 5 | public interface TelegramRequestStatisticsProcessor { 6 | void processMessage(GetUpdatesResponse.Message message); 7 | 8 | long getRequestCounter(); 9 | } 10 | -------------------------------------------------------------------------------- /currencyRateBotStatistics/src/main/java/ru/cbrrate/services/TelegramRequestStatisticsProcessorImpl.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.stereotype.Service; 5 | import ru.cbrrate.model.GetUpdatesResponse; 6 | 7 | import java.util.concurrent.atomic.AtomicInteger; 8 | import java.util.concurrent.atomic.AtomicLong; 9 | 10 | 11 | @Slf4j 12 | @Service 13 | public class TelegramRequestStatisticsProcessorImpl implements TelegramRequestStatisticsProcessor { 14 | 15 | private final AtomicLong requestCounter = new AtomicLong(0); 16 | 17 | @Override 18 | public void processMessage(GetUpdatesResponse.Message message) { 19 | log.info("message:{}", message); 20 | var lastValue = requestCounter.incrementAndGet(); 21 | log.info("current requestCounter:{}", lastValue); 22 | } 23 | 24 | @Override 25 | public long getRequestCounter() { 26 | return requestCounter.get(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /currencyRateBotStatistics/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8084 3 | 4 | 5 | spring: 6 | kafka: 7 | bootstrap-servers: "localhost:9092" 8 | consumer: 9 | auto-offset-reset: earliest 10 | 11 | management: 12 | server: 13 | port: 8094 14 | endpoints: 15 | enabled-by-default: false 16 | endpoint: 17 | health: 18 | enabled: true 19 | probes: 20 | enabled: true 21 | 22 | app: 23 | rest: 24 | api: 25 | prefix: /api 26 | 27 | -------------------------------------------------------------------------------- /currencyRateBotStatistics/src/test/java/ru/cbrrate/services/KafkaBase.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | import org.apache.kafka.clients.admin.AdminClient; 4 | import org.apache.kafka.clients.admin.NewTopic; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.boot.test.util.TestPropertyValues; 8 | import org.springframework.context.ApplicationContextInitializer; 9 | import org.springframework.context.ConfigurableApplicationContext; 10 | import org.testcontainers.containers.KafkaContainer; 11 | import org.testcontainers.utility.DockerImageName; 12 | 13 | import java.util.Collection; 14 | import java.util.Map; 15 | import java.util.concurrent.ExecutionException; 16 | import java.util.concurrent.TimeUnit; 17 | import java.util.concurrent.TimeoutException; 18 | 19 | import static org.apache.kafka.clients.CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG; 20 | 21 | class KafkaBase { 22 | private static final Logger log = LoggerFactory.getLogger(KafkaBase.class); 23 | 24 | private final static KafkaContainer kafka = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:7.0.0")); 25 | private static boolean started = false; 26 | 27 | public static void start(Collection topics) throws ExecutionException, InterruptedException, TimeoutException { 28 | if (!started) { 29 | kafka.start(); 30 | 31 | log.info("topics creation..."); 32 | try (var admin = AdminClient.create(Map.of(BOOTSTRAP_SERVERS_CONFIG, kafka.getBootstrapServers()))) { 33 | var result = admin.createTopics(topics); 34 | 35 | for(var topicResult: result.values().values()) { 36 | topicResult.get(10, TimeUnit.SECONDS); 37 | } 38 | } 39 | log.info("topics created"); 40 | started = true; 41 | } 42 | } 43 | 44 | public static class Initializer implements ApplicationContextInitializer { 45 | @Override 46 | public void initialize(ConfigurableApplicationContext applicationContext) { 47 | if (started) { 48 | TestPropertyValues.of( 49 | "spring.kafka.bootstrap-servers:" + kafka.getBootstrapServers() 50 | ).applyTo(applicationContext.getEnvironment()); 51 | } 52 | } 53 | } 54 | } -------------------------------------------------------------------------------- /currencyRateBotStatistics/src/test/java/ru/cbrrate/services/TelegramRequestStatisticsProcessorImplTest.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import org.apache.kafka.clients.admin.NewTopic; 5 | 6 | import org.junit.jupiter.api.BeforeAll; 7 | import org.junit.jupiter.api.Test; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | 11 | import org.springframework.kafka.core.KafkaTemplate; 12 | import org.springframework.test.context.ContextConfiguration; 13 | import ru.cbrrate.model.GetUpdatesResponse; 14 | 15 | import java.util.List; 16 | import java.util.Random; 17 | import java.util.concurrent.ExecutionException; 18 | import java.util.concurrent.TimeUnit; 19 | import java.util.concurrent.TimeoutException; 20 | 21 | 22 | import static org.testcontainers.shaded.org.awaitility.Awaitility.await; 23 | import static ru.cbrrate.config.KafkaConfig.TOPIC_RATE_REQUESTS; 24 | 25 | @SpringBootTest 26 | @ContextConfiguration(initializers = {KafkaBase.Initializer.class}) 27 | class TelegramRequestStatisticsProcessorImplTest { 28 | 29 | @Autowired 30 | private ObjectMapper objectMapper; 31 | 32 | @Autowired 33 | private KafkaTemplate kafkaTemplate; 34 | 35 | @Autowired 36 | private TelegramRequestStatisticsProcessor telegramRequestStatisticsProcessor; 37 | 38 | @BeforeAll 39 | public static void init() throws ExecutionException, InterruptedException, TimeoutException { 40 | KafkaBase.start(List.of(new NewTopic(TOPIC_RATE_REQUESTS, 1, (short) 1))); 41 | } 42 | 43 | @Test 44 | void processMessageTest() { 45 | var text = "text"; 46 | var responseList1 = makeGetUpdatesResponse(1, text).getResult().stream() 47 | .map(GetUpdatesResponse.Response::getMessage) 48 | .map(this::writeValueAsString).toList(); 49 | 50 | var responseList2 = makeGetUpdatesResponse(2, text).getResult().stream() 51 | .map(GetUpdatesResponse.Response::getMessage) 52 | .map(this::writeValueAsString).toList(); 53 | 54 | responseList1.forEach(this::sendSync); 55 | responseList2.forEach(this::sendSync); 56 | 57 | int responseCounter = responseList1.size() + responseList2.size(); 58 | //first run 59 | 60 | //second run 61 | await().atMost(30, TimeUnit.SECONDS).until(() -> responseCounter == telegramRequestStatisticsProcessor.getRequestCounter()); 62 | } 63 | 64 | private void sendSync(String val) { 65 | try { 66 | kafkaTemplate.send(TOPIC_RATE_REQUESTS, val); 67 | } catch (Exception ex) { 68 | throw new RuntimeException(ex); 69 | } 70 | } 71 | 72 | private String writeValueAsString(GetUpdatesResponse.Message msg) { 73 | try { 74 | return objectMapper.writeValueAsString(msg); 75 | } catch (Exception ex) { 76 | throw new RuntimeException(ex); 77 | } 78 | } 79 | 80 | private GetUpdatesResponse makeGetUpdatesResponse(long updateId, String text) { 81 | var from = new GetUpdatesResponse.From(506L, false, "Ivan", "Petrov", "en"); 82 | var chat = new GetUpdatesResponse.Chat(506L, "Ivan", "Petrov", "private"); 83 | var random = new Random(); 84 | var message1 = new GetUpdatesResponse.Message(random.nextLong(), from, chat, 1631970287, text); 85 | var message2 = new GetUpdatesResponse.Message(random.nextLong(), from, chat, 1631970287, text); 86 | 87 | return new GetUpdatesResponse(true, List.of(new GetUpdatesResponse.Response(updateId, message1), 88 | new GetUpdatesResponse.Response(updateId + 1, message2))); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /currencyRateClient/HttpRequests.http: -------------------------------------------------------------------------------- 1 | ### 2 | GET http://localhost:8080/api/v1/currencyRate/CBR/EUR/02-03-2021 3 | Accept: */* 4 | Content-Type: application/json 5 | Cache-Control: no-cache 6 | 7 | ### 8 | GET http://localhost:8090/actuator/health 9 | Accept: */* 10 | Content-Type: application/json 11 | Cache-Control: no-cache 12 | 13 | ### 14 | GET http://localhost:8090/actuator/health/liveness 15 | Accept: */* 16 | Content-Type: application/json 17 | Cache-Control: no-cache 18 | 19 | ### 20 | GET http://localhost:8090/actuator/health/readiness 21 | Accept: */* 22 | Content-Type: application/json 23 | Cache-Control: no-cache 24 | -------------------------------------------------------------------------------- /currencyRateClient/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.springframework.boot' 4 | id 'com.google.cloud.tools.jib' 5 | } 6 | 7 | apply from: 'jib.gradle' 8 | 9 | sourceCompatibility = JavaVersion.VERSION_17 10 | targetCompatibility = JavaVersion.VERSION_17 11 | 12 | dependencies { 13 | implementation 'org.springframework.boot:spring-boot-starter-webflux' 14 | implementation 'org.springframework.boot:spring-boot-starter-actuator' 15 | implementation 'ch.qos.logback:logback-classic' 16 | implementation 'org.ehcache:ehcache' 17 | 18 | 19 | compileOnly 'org.projectlombok:lombok' 20 | testCompileOnly 'org.projectlombok:lombok' 21 | annotationProcessor 'org.projectlombok:lombok' 22 | 23 | testImplementation('org.springframework.boot:spring-boot-starter-test') 24 | } 25 | 26 | test { 27 | useJUnitPlatform() 28 | testLogging { 29 | events "passed", "skipped", "failed" 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /currencyRateClient/jib.gradle: -------------------------------------------------------------------------------- 1 | jib { 2 | container.creationTime = 'USE_CURRENT_TIMESTAMP' 3 | from { 4 | image = 'bellsoft/bellsoft/liberica-openjdk-alpine-musl:17.0.1-12' 5 | } 6 | to { 7 | tags = ['v3', 'latest'] 8 | image = 'registry.gitlab.com/petrelevich/dockerregistry/currency-rate-client' 9 | auth { 10 | username = gitlabUser 11 | password = gitlabPassword 12 | } 13 | } 14 | } 15 | // ./gradlew jibDockerBuild 16 | 17 | //docker login registry.gitlab.com 18 | //docker run -p 8080:8080 registry.gitlab.com/petrelevich/dockerregistry/currencyRateClient 19 | 20 | //docker push registry.gitlab.com/petrelevich/dockerregistry/currencyRateClient:latest 21 | -------------------------------------------------------------------------------- /currencyRateClient/src/main/java/ru/cbrrate/CurrencyRateClient.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate; 2 | 3 | 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.boot.builder.SpringApplicationBuilder; 6 | 7 | 8 | 9 | @SpringBootApplication 10 | public class CurrencyRateClient { 11 | public static void main(String[] args) { 12 | new SpringApplicationBuilder().sources(CurrencyRateClient.class).run(args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /currencyRateClient/src/main/java/ru/cbrrate/clients/CbrRateClient.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.clients; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import lombok.RequiredArgsConstructor; 5 | import lombok.extern.slf4j.Slf4j; 6 | import org.springframework.stereotype.Service; 7 | import reactor.core.publisher.Mono; 8 | import ru.cbrrate.config.CbrRateClientConfig; 9 | import ru.cbrrate.model.CurrencyRate; 10 | import java.time.LocalDate; 11 | import java.time.format.DateTimeFormatter; 12 | 13 | @Service("cbr") 14 | @RequiredArgsConstructor 15 | @Slf4j 16 | public class CbrRateClient implements RateClient { 17 | public static final String DATE_FORMAT = "dd-MM-yyyy"; 18 | private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern(DATE_FORMAT); 19 | 20 | private final CbrRateClientConfig config; 21 | private final ru.cbrrate.clients.HttpClient httpClient; 22 | private final ObjectMapper objectMapper; 23 | 24 | @Override 25 | public Mono getCurrencyRate(String currency, LocalDate date) { 26 | log.info("getCurrencyRate currency:{}, date:{}", currency, date); 27 | var urlWithParams = String.format("%s/%s/%s", config.getUrl(), currency, DATE_FORMATTER.format(date)); 28 | 29 | try { 30 | return httpClient.performRequest(urlWithParams) 31 | .map(this::parse); 32 | } catch (HttpClientException ex) { 33 | throw new RateClientException("Error from Cbr Client host:" + ex.getMessage()); 34 | } catch (Exception ex) { 35 | log.error("Getting currencyRate error, currency:{}, date:{}", currency, date, ex); 36 | throw new RateClientException("Can't get currencyRate. currency:" + currency + ", date:" + date); 37 | } 38 | } 39 | 40 | private CurrencyRate parse(String rateAsString) { 41 | try { 42 | return objectMapper.readValue(rateAsString, CurrencyRate.class); 43 | } catch (Exception ex) { 44 | throw new RateClientException("Can't parse string:" + rateAsString); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /currencyRateClient/src/main/java/ru/cbrrate/clients/HttpClient.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.clients; 2 | 3 | import reactor.core.publisher.Mono; 4 | 5 | public interface HttpClient { 6 | 7 | Mono performRequest(String url); 8 | } 9 | -------------------------------------------------------------------------------- /currencyRateClient/src/main/java/ru/cbrrate/clients/HttpClientException.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.clients; 2 | 3 | public class HttpClientException extends RuntimeException { 4 | public HttpClientException(String msg) { 5 | super(msg); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /currencyRateClient/src/main/java/ru/cbrrate/clients/HttpClientJdk.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.clients; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.http.MediaType; 5 | import org.springframework.stereotype.Service; 6 | import org.springframework.web.reactive.function.client.WebClient; 7 | import reactor.core.publisher.Mono; 8 | 9 | import java.net.URI; 10 | import java.net.http.HttpRequest; 11 | import java.net.http.HttpResponse; 12 | 13 | @Service 14 | @Slf4j 15 | public class HttpClientJdk implements HttpClient { 16 | 17 | private final WebClient.Builder webBuilder; 18 | 19 | public HttpClientJdk(WebClient.Builder webBuilder) { 20 | this.webBuilder = webBuilder; 21 | } 22 | 23 | @Override 24 | public Mono performRequest(String url) { 25 | log.info("http request, url:{}", url); 26 | var client = webBuilder.baseUrl(url).build(); 27 | try { 28 | return client.get() 29 | .accept(MediaType.APPLICATION_JSON) 30 | .retrieve() 31 | .bodyToMono(String.class) 32 | .doOnError(error -> log.error("Http request error, url:{}", url, error)) 33 | .doOnNext(val -> log.info("val:{}", val)); 34 | } catch (Exception ex) { 35 | throw new HttpClientException(ex.getMessage()); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /currencyRateClient/src/main/java/ru/cbrrate/clients/RateClient.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.clients; 2 | 3 | import reactor.core.publisher.Mono; 4 | import ru.cbrrate.model.CurrencyRate; 5 | 6 | import java.time.LocalDate; 7 | 8 | public interface RateClient { 9 | 10 | Mono getCurrencyRate(String currency, LocalDate date); 11 | } 12 | -------------------------------------------------------------------------------- /currencyRateClient/src/main/java/ru/cbrrate/clients/RateClientException.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.clients; 2 | 3 | public class RateClientException extends RuntimeException { 4 | public RateClientException(String msg) { 5 | super(msg); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /currencyRateClient/src/main/java/ru/cbrrate/config/ApplicationConfig.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.config; 2 | 3 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 4 | import org.springframework.context.annotation.Configuration; 5 | 6 | @Configuration 7 | @EnableConfigurationProperties(CbrRateClientConfig.class) 8 | public class ApplicationConfig { 9 | 10 | } 11 | -------------------------------------------------------------------------------- /currencyRateClient/src/main/java/ru/cbrrate/config/CbrRateClientConfig.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.config; 2 | 3 | import lombok.Data; 4 | import org.springframework.boot.context.properties.ConfigurationProperties; 5 | 6 | @Data 7 | @ConfigurationProperties(prefix = "cbr-rate-client") 8 | public class CbrRateClientConfig { 9 | String url; 10 | } 11 | -------------------------------------------------------------------------------- /currencyRateClient/src/main/java/ru/cbrrate/config/JsonConfig.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.config; 2 | 3 | import com.fasterxml.jackson.annotation.JsonInclude; 4 | import com.fasterxml.jackson.databind.DeserializationFeature; 5 | import com.fasterxml.jackson.databind.ObjectMapper; 6 | import com.fasterxml.jackson.databind.SerializationFeature; 7 | import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | 11 | @Configuration 12 | public class JsonConfig { 13 | 14 | @Bean 15 | public ObjectMapper objectMapper() { 16 | var objectMapper = new ObjectMapper(); 17 | objectMapper.registerModule(new JavaTimeModule()); 18 | objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); 19 | objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); 20 | objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 21 | objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); 22 | objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); 23 | return objectMapper; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /currencyRateClient/src/main/java/ru/cbrrate/controller/CurrencyRateEndpointController.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.controller; 2 | 3 | import lombok.RequiredArgsConstructor; 4 | import lombok.extern.slf4j.Slf4j; 5 | import org.springframework.format.annotation.DateTimeFormat; 6 | import org.springframework.web.bind.annotation.GetMapping; 7 | import org.springframework.web.bind.annotation.PathVariable; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | import reactor.core.publisher.Mono; 11 | import ru.cbrrate.model.CurrencyRate; 12 | import ru.cbrrate.model.RateType; 13 | import ru.cbrrate.services.CurrencyRateEndpointService; 14 | 15 | import java.time.LocalDate; 16 | 17 | 18 | @RestController 19 | @Slf4j 20 | @RequiredArgsConstructor 21 | @RequestMapping(path = "${app.rest.api.prefix}/v1") 22 | public class CurrencyRateEndpointController { 23 | 24 | public final CurrencyRateEndpointService currencyRateEndpointService; 25 | 26 | @GetMapping("/currencyRate/{type}/{currency}/{date}") 27 | public Mono getCurrencyRate(@PathVariable("type") RateType type, 28 | @PathVariable("currency") String currency, 29 | @DateTimeFormat(pattern = "dd-MM-yyyy") @PathVariable("date") LocalDate date) { 30 | log.info("getCurrencyRate, currency:{}, date:{}", currency, date); 31 | return currencyRateEndpointService.getCurrencyRate(type, currency, date); 32 | } 33 | } -------------------------------------------------------------------------------- /currencyRateClient/src/main/java/ru/cbrrate/controller/ExceptionHandlingController.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.controller; 2 | 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.web.bind.annotation.ExceptionHandler; 5 | import org.springframework.web.bind.annotation.ResponseStatus; 6 | import org.springframework.web.bind.annotation.RestControllerAdvice; 7 | 8 | 9 | @RestControllerAdvice 10 | public class ExceptionHandlingController { 11 | 12 | @ExceptionHandler(Exception.class) 13 | @ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE) 14 | public String serverExceptionHandler(Exception ex) { 15 | return ex.getMessage(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /currencyRateClient/src/main/java/ru/cbrrate/model/CurrencyRate.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.model; 2 | 3 | import com.fasterxml.jackson.annotation.JsonCreator; 4 | import com.fasterxml.jackson.annotation.JsonProperty; 5 | import lombok.Builder; 6 | import lombok.Value; 7 | 8 | @Value 9 | @Builder 10 | public class CurrencyRate { 11 | String charCode; 12 | String nominal; 13 | String value; 14 | 15 | @JsonCreator 16 | public CurrencyRate(@JsonProperty("charCode") String charCode, 17 | @JsonProperty("nominal") String nominal, 18 | @JsonProperty("value") String value) { 19 | this.charCode = charCode; 20 | this.nominal = nominal; 21 | this.value = value; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /currencyRateClient/src/main/java/ru/cbrrate/model/RateType.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.model; 2 | 3 | public enum RateType { 4 | CBR("cbr"); 5 | 6 | String serviceName; 7 | 8 | RateType(String serviceName) { 9 | this.serviceName = serviceName; 10 | } 11 | 12 | public String getServiceName() { 13 | return serviceName; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /currencyRateClient/src/main/java/ru/cbrrate/services/CurrencyRateEndpointService.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | 5 | import org.springframework.stereotype.Service; 6 | import reactor.core.publisher.Mono; 7 | import ru.cbrrate.clients.RateClient; 8 | 9 | import ru.cbrrate.model.CurrencyRate; 10 | import ru.cbrrate.model.RateType; 11 | 12 | 13 | import java.time.LocalDate; 14 | import java.util.Map; 15 | 16 | @Service 17 | @Slf4j 18 | public class CurrencyRateEndpointService { 19 | 20 | private final Map clients; 21 | 22 | public CurrencyRateEndpointService(Map clients) { 23 | this.clients = clients; 24 | } 25 | 26 | public Mono getCurrencyRate(RateType rateType, String currency, LocalDate date) { 27 | log.info("getCurrencyRate. rateType:{}, currency:{}, date:{}", rateType, currency, date); 28 | var client = clients.get(rateType.getServiceName()); 29 | return client.getCurrencyRate(currency, date); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /currencyRateClient/src/main/java/ru/cbrrate/services/CurrencyRateNotFoundException.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.services; 2 | 3 | public class CurrencyRateNotFoundException extends RuntimeException { 4 | public CurrencyRateNotFoundException(String message) { 5 | super(message); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /currencyRateClient/src/main/resources/application-local.yml: -------------------------------------------------------------------------------- 1 | cbr-rate-client: 2 | url: "http://localhost:8081/api/v1/currencyRate" 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /currencyRateClient/src/main/resources/application-prod.yml: -------------------------------------------------------------------------------- 1 | cbr-rate-client: 2 | url: "http://cbr-rate.default.svc.cluster.local/api/v1/currencyRate" 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /currencyRateClient/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8080 3 | 4 | management: 5 | server: 6 | port: 8090 7 | endpoints: 8 | enabled-by-default: false 9 | endpoint: 10 | health: 11 | enabled: true 12 | probes: 13 | enabled: true 14 | 15 | app: 16 | rest: 17 | api: 18 | prefix: /api 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /currencyRateClient/src/test/java/ru/cbrrate/controller/CurrencyRateEndpointControllerTest.java: -------------------------------------------------------------------------------- 1 | package ru.cbrrate.controller; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.boot.test.mock.mockito.MockBean; 7 | import org.springframework.http.MediaType; 8 | import org.springframework.test.web.reactive.server.WebTestClient; 9 | import reactor.core.publisher.Mono; 10 | import ru.cbrrate.clients.HttpClient; 11 | import ru.cbrrate.config.CbrRateClientConfig; 12 | 13 | import static org.assertj.core.api.Assertions.assertThat; 14 | import static org.mockito.Mockito.*; 15 | 16 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 17 | class CurrencyRateEndpointControllerTest { 18 | 19 | @Autowired 20 | private WebTestClient webTestClient; 21 | 22 | @Autowired 23 | CbrRateClientConfig config; 24 | 25 | @MockBean 26 | HttpClient httpClient; 27 | 28 | @Test 29 | void getCurrencyRateTest() { 30 | //given 31 | var type = "CBR"; 32 | var currency = "EUR"; 33 | var date = "02-03-2021"; 34 | 35 | var url = String.format("%s/%s/%s", config.getUrl(), currency, date); 36 | when(httpClient.performRequest(url)) 37 | .thenReturn(Mono.just("{\"numCode\":\"978\",\"charCode\":\"EUR\",\"nominal\":\"1\",\"name\":\"Евро\",\"value\":\"89,4461\"}")); 38 | //when 39 | 40 | var result = webTestClient 41 | .get().uri(String.format("/api/v1/currencyRate/%s/%s/%s", type, currency, date)) 42 | .accept(MediaType.APPLICATION_JSON) 43 | .exchange() 44 | .expectStatus().isOk() 45 | .returnResult(String.class) 46 | .getResponseBody() 47 | .blockLast(); 48 | 49 | //then 50 | assertThat(result).isEqualTo("{\"charCode\":\"EUR\",\"nominal\":\"1\",\"value\":\"89,4461\"}"); 51 | } 52 | } -------------------------------------------------------------------------------- /docker/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.9" 2 | services: 3 | zookeeper: 4 | image: confluentinc/cp-zookeeper:6.2.0 5 | container_name: zookeeper 6 | environment: 7 | ZOOKEEPER_CLIENT_PORT: 2181 8 | ZOOKEEPER_TICK_TIME: 2000 9 | 10 | broker: 11 | image: confluentinc/cp-kafka:7.0.0 12 | container_name: broker 13 | ports: 14 | - "9092:9092" 15 | depends_on: 16 | - zookeeper 17 | environment: 18 | KAFKA_BROKER_ID: 1 19 | KAFKA_ZOOKEEPER_CONNECT: 'zookeeper:2181' 20 | KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_INTERNAL:PLAINTEXT 21 | KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092,PLAINTEXT_INTERNAL://broker:29092 22 | KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 23 | KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1 24 | KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1 -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/petrelevich/currency-rate/021573f97874016576e30e4c0d4fafb315b4efa9/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.3-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /kube/cbrRate/deployment_cbr-rate.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: apps/v1 3 | kind: Deployment 4 | metadata: 5 | name: cbr-rate 6 | spec: 7 | replicas: 1 8 | selector: 9 | matchLabels: 10 | app: cbr-rate 11 | strategy: 12 | rollingUpdate: 13 | maxSurge: 1 14 | maxUnavailable: 1 15 | type: RollingUpdate 16 | template: 17 | metadata: 18 | labels: 19 | app: cbr-rate 20 | spec: 21 | containers: 22 | - image: registry.gitlab.com/petrelevich/dockerregistry/cbr-rate:v1 23 | name: cbr-rate 24 | ports: 25 | - containerPort: 8081 26 | envFrom: 27 | - configMapRef: 28 | name: currency-rate-config 29 | readinessProbe: 30 | failureThreshold: 3 31 | httpGet: 32 | path: /actuator/health/readiness 33 | port: 8091 34 | periodSeconds: 10 35 | successThreshold: 1 36 | timeoutSeconds: 1 37 | livenessProbe: 38 | failureThreshold: 3 39 | httpGet: 40 | path: /actuator/health/liveness 41 | port: 8091 42 | periodSeconds: 10 43 | successThreshold: 1 44 | timeoutSeconds: 1 45 | initialDelaySeconds: 10 46 | imagePullSecrets: 47 | - name: regcred 48 | -------------------------------------------------------------------------------- /kube/cbrRate/service_cbr-rate.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: v1 3 | kind: Service 4 | metadata: 5 | name: cbr-rate 6 | spec: 7 | ports: 8 | - port: 80 9 | targetPort: 8081 10 | selector: 11 | app: cbr-rate 12 | type: ClusterIP 13 | -------------------------------------------------------------------------------- /kube/config/currency-rate-config.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: v1 3 | kind: ConfigMap 4 | metadata: 5 | name: currency-rate-config 6 | data: 7 | SPRING_PROFILES_ACTIVE: prod 8 | JAVA_TOOL_OPTIONS: -XX:+UseContainerSupport -XX:MaxRAMPercentage=80 9 | -------------------------------------------------------------------------------- /kube/currencyRateBot/deployment_currency-rate-bot.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: apps/v1 3 | kind: Deployment 4 | metadata: 5 | name: currency-rate-bot 6 | spec: 7 | replicas: 1 8 | selector: 9 | matchLabels: 10 | app: currency-rate-bot 11 | strategy: 12 | rollingUpdate: 13 | maxSurge: 1 14 | maxUnavailable: 1 15 | type: RollingUpdate 16 | template: 17 | metadata: 18 | labels: 19 | app: currency-rate-bot 20 | spec: 21 | containers: 22 | - image: registry.gitlab.com/petrelevich/dockerregistry/currency-rate-bot:v7 23 | name: currency-rate-bot 24 | ports: 25 | - containerPort: 8082 26 | envFrom: 27 | - configMapRef: 28 | name: currency-rate-config 29 | - secretRef: 30 | name: secret-currency-rate-config 31 | readinessProbe: 32 | failureThreshold: 3 33 | httpGet: 34 | path: /actuator/health/readiness 35 | port: 8092 36 | periodSeconds: 10 37 | successThreshold: 1 38 | timeoutSeconds: 1 39 | livenessProbe: 40 | failureThreshold: 3 41 | httpGet: 42 | path: /actuator/health/liveness 43 | port: 8092 44 | periodSeconds: 10 45 | successThreshold: 1 46 | timeoutSeconds: 1 47 | initialDelaySeconds: 10 48 | imagePullSecrets: 49 | - name: regcred 50 | -------------------------------------------------------------------------------- /kube/currencyRateBot/service_currency-rate-bot.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: v1 3 | kind: Service 4 | metadata: 5 | name: currency-rate-bot 6 | spec: 7 | ports: 8 | - port: 80 9 | targetPort: 8082 10 | selector: 11 | app: currency-rate-bot 12 | type: ClusterIP 13 | -------------------------------------------------------------------------------- /kube/currencyRateClient/deployment_currency-rate-client.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: apps/v1 3 | kind: Deployment 4 | metadata: 5 | name: currency-rate-client 6 | spec: 7 | replicas: 1 8 | selector: 9 | matchLabels: 10 | app: currency-rate-client 11 | strategy: 12 | rollingUpdate: 13 | maxSurge: 1 14 | maxUnavailable: 1 15 | type: RollingUpdate 16 | template: 17 | metadata: 18 | labels: 19 | app: currency-rate-client 20 | spec: 21 | containers: 22 | - image: registry.gitlab.com/petrelevich/dockerregistry/currency-rate-client:v3 23 | name: currency-rate-client 24 | ports: 25 | - containerPort: 8080 26 | envFrom: 27 | - configMapRef: 28 | name: currency-rate-config 29 | readinessProbe: 30 | failureThreshold: 3 31 | httpGet: 32 | path: /actuator/health/readiness 33 | port: 8090 34 | periodSeconds: 10 35 | successThreshold: 1 36 | timeoutSeconds: 1 37 | livenessProbe: 38 | failureThreshold: 3 39 | httpGet: 40 | path: /actuator/health/liveness 41 | port: 8090 42 | periodSeconds: 10 43 | successThreshold: 1 44 | timeoutSeconds: 1 45 | initialDelaySeconds: 10 46 | imagePullSecrets: 47 | - name: regcred 48 | -------------------------------------------------------------------------------- /kube/currencyRateClient/ingress_currency-rate-client.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: networking.k8s.io/v1 3 | kind: Ingress 4 | metadata: 5 | name: currency-rate-client 6 | spec: 7 | rules: 8 | - http: 9 | paths: 10 | - path: / 11 | pathType: Prefix 12 | backend: 13 | service: 14 | name: currency-rate-client 15 | port: 16 | number: 80 17 | -------------------------------------------------------------------------------- /kube/currencyRateClient/service_currency-rate-client.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | apiVersion: v1 3 | kind: Service 4 | metadata: 5 | name: currency-rate-client 6 | spec: 7 | ports: 8 | - port: 80 9 | targetPort: 8080 10 | selector: 11 | app: currency-rate-client 12 | type: ClusterIP 13 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'currency-rate' 2 | include 'cbrRate' 3 | include 'currencyRateClient' 4 | include 'currencyRateBotRequestConsumer' 5 | include 'currencyRateBotResponseProvider' 6 | include 'currencyRateBotStatistics' 7 | --------------------------------------------------------------------------------