├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── screenshots ├── screenshot_1.PNG ├── screenshot_2.PNG ├── screenshot_3.PNG ├── screenshot_4.PNG ├── screenshot_5.PNG └── spring_boot_currency_diagram.png ├── src ├── main │ ├── java │ │ └── com │ │ │ └── exchangeapi │ │ │ └── currencyexchange │ │ │ ├── dto │ │ │ ├── RateInfoDto.java │ │ │ ├── RateDto.java │ │ │ └── ExchangeDto.java │ │ │ ├── exception │ │ │ ├── RestTemplateError.java │ │ │ ├── RateNotFoundException.java │ │ │ ├── ExchangeNotFoundException.java │ │ │ ├── RestServiceException.java │ │ │ ├── Error.java │ │ │ ├── RestTemplateErrorHandler.java │ │ │ └── GeneralExceptionAdvice.java │ │ │ ├── CurrencyexchangeApplication.java │ │ │ ├── repository │ │ │ ├── RateRepository.java │ │ │ └── ExchangeRepository.java │ │ │ ├── payload │ │ │ └── response │ │ │ │ └── RateResponse.java │ │ │ ├── config │ │ │ ├── SpringCachingConfig.java │ │ │ ├── SpringCacheCustomizer.java │ │ │ ├── OpenApiConfiguration.java │ │ │ └── RestTemplateConfig.java │ │ │ ├── entity │ │ │ ├── BaseEntity.java │ │ │ ├── RateEntity.java │ │ │ ├── ExchangeEntity.java │ │ │ └── enums │ │ │ │ └── EnumCurrency.java │ │ │ ├── constants │ │ │ └── Constants.java │ │ │ ├── controller │ │ │ ├── ExchangeController.java │ │ │ ├── ConversionController.java │ │ │ └── RateController.java │ │ │ └── service │ │ │ ├── ExchangeService.java │ │ │ └── RateService.java │ └── resources │ │ └── application.yaml └── test │ ├── java │ └── com │ │ └── exchangeapi │ │ └── currencyexchange │ │ ├── CurrencyexchangeApplicationTests.java │ │ ├── base │ │ ├── BaseServiceTest.java │ │ └── BaseControllerTest.java │ │ ├── controller │ │ ├── ExchangeControllerTest.java │ │ ├── RateControllerTest.java │ │ └── ConversionControllerTest.java │ │ └── service │ │ ├── ExchangeServiceTest.java │ │ └── RateServiceTest.java │ └── resources │ └── application-test.yaml ├── docker-compose.yml ├── Dockerfile ├── .gitignore ├── postman_collection └── Currency Exchange API.postman_collection.json ├── pom.xml ├── README.md ├── mvnw.cmd └── mvnw /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rapter1990/currencyexchange/HEAD/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /screenshots/screenshot_1.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rapter1990/currencyexchange/HEAD/screenshots/screenshot_1.PNG -------------------------------------------------------------------------------- /screenshots/screenshot_2.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rapter1990/currencyexchange/HEAD/screenshots/screenshot_2.PNG -------------------------------------------------------------------------------- /screenshots/screenshot_3.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rapter1990/currencyexchange/HEAD/screenshots/screenshot_3.PNG -------------------------------------------------------------------------------- /screenshots/screenshot_4.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rapter1990/currencyexchange/HEAD/screenshots/screenshot_4.PNG -------------------------------------------------------------------------------- /screenshots/screenshot_5.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rapter1990/currencyexchange/HEAD/screenshots/screenshot_5.PNG -------------------------------------------------------------------------------- /screenshots/spring_boot_currency_diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Rapter1990/currencyexchange/HEAD/screenshots/spring_boot_currency_diagram.png -------------------------------------------------------------------------------- /src/main/java/com/exchangeapi/currencyexchange/dto/RateInfoDto.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.dto; 2 | 3 | import com.exchangeapi.currencyexchange.entity.enums.EnumCurrency; 4 | 5 | public record RateInfoDto(EnumCurrency currency, Double rate) {} 6 | -------------------------------------------------------------------------------- /src/main/java/com/exchangeapi/currencyexchange/exception/RestTemplateError.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.exception; 2 | 3 | public record RestTemplateError ( 4 | String timestamp, 5 | String status, 6 | String error, 7 | String path 8 | ){ } 9 | -------------------------------------------------------------------------------- /src/main/java/com/exchangeapi/currencyexchange/exception/RateNotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.exception; 2 | 3 | public class RateNotFoundException extends RuntimeException { 4 | public RateNotFoundException(String message) { 5 | super(message); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/exchangeapi/currencyexchange/exception/ExchangeNotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.exception; 2 | 3 | public class ExchangeNotFoundException extends RuntimeException { 4 | public ExchangeNotFoundException(String message) { 5 | super(message); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.8' 2 | services: 3 | currencyexchange: 4 | image: 'currencyexchange:latest' 5 | build: 6 | context: . 7 | dockerfile: Dockerfile 8 | ports: 9 | - 8080:8080 10 | environment: 11 | - "EXCHANGE_API_API_KEY=${EXCHANGE_API_API_KEY}" 12 | volumes: 13 | - ./logs:/app/logs -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM openjdk:17-jdk-slim AS build 2 | 3 | COPY pom.xml mvnw ./ 4 | COPY .mvn .mvn 5 | RUN ./mvnw dependency:resolve 6 | 7 | COPY src src 8 | RUN ./mvnw package 9 | 10 | FROM openjdk:17-jdk-slim 11 | WORKDIR currencyexchange 12 | COPY --from=build target/*.jar currencyexchange.jar 13 | ENTRYPOINT ["java", "-jar", "currencyexchange.jar"] -------------------------------------------------------------------------------- /src/test/java/com/exchangeapi/currencyexchange/CurrencyexchangeApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class CurrencyexchangeApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/test/java/com/exchangeapi/currencyexchange/base/BaseServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.base; 2 | 3 | import org.junit.jupiter.api.extension.ExtendWith; 4 | import org.mockito.junit.jupiter.MockitoExtension; 5 | import org.springframework.test.context.ActiveProfiles; 6 | 7 | @ExtendWith(MockitoExtension.class) 8 | @ActiveProfiles(value = "test") 9 | public abstract class BaseServiceTest { 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/exchangeapi/currencyexchange/exception/RestServiceException.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.exception; 2 | 3 | import lombok.AllArgsConstructor; 4 | import org.springframework.http.HttpStatus; 5 | 6 | 7 | @AllArgsConstructor 8 | public class RestServiceException extends RuntimeException{ 9 | private String serviceName; 10 | private HttpStatus statusCode; 11 | private String error; 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/exchangeapi/currencyexchange/CurrencyexchangeApplication.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class CurrencyexchangeApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(CurrencyexchangeApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/exchangeapi/currencyexchange/exception/Error.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.exception; 2 | 3 | import lombok.Builder; 4 | import org.springframework.http.HttpStatus; 5 | 6 | import java.time.LocalDateTime; 7 | import java.util.List; 8 | 9 | @Builder 10 | public record Error ( 11 | LocalDateTime timestamp, 12 | int status, 13 | String path, 14 | HttpStatus httpStatus, 15 | List errorDetails 16 | ) { } 17 | -------------------------------------------------------------------------------- /src/main/java/com/exchangeapi/currencyexchange/repository/RateRepository.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.repository; 2 | 3 | import com.exchangeapi.currencyexchange.entity.RateEntity; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | import java.time.LocalDate; 7 | import java.util.Optional; 8 | 9 | public interface RateRepository extends JpaRepository { 10 | 11 | Optional findOneByDate(LocalDate date); 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/exchangeapi/currencyexchange/dto/RateDto.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.dto; 2 | 3 | import com.exchangeapi.currencyexchange.entity.enums.EnumCurrency; 4 | import lombok.Builder; 5 | import lombok.Getter; 6 | 7 | import java.time.LocalDate; 8 | import java.util.List; 9 | 10 | @Builder 11 | @Getter 12 | public class RateDto { 13 | private String id; 14 | private EnumCurrency base; 15 | private LocalDate date; 16 | List rates; 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/exchangeapi/currencyexchange/repository/ExchangeRepository.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.repository; 2 | 3 | import com.exchangeapi.currencyexchange.entity.ExchangeEntity; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | import java.time.LocalDate; 7 | import java.util.List; 8 | 9 | public interface ExchangeRepository extends JpaRepository { 10 | 11 | List findByDateBetween(LocalDate startDate, LocalDate endDate); 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/exchangeapi/currencyexchange/dto/ExchangeDto.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.dto; 2 | 3 | import com.exchangeapi.currencyexchange.entity.enums.EnumCurrency; 4 | import lombok.Builder; 5 | import lombok.Getter; 6 | 7 | import java.time.LocalDate; 8 | import java.util.Map; 9 | 10 | @Builder 11 | @Getter 12 | public class ExchangeDto { 13 | private String id; 14 | private EnumCurrency base; 15 | private Double amount; 16 | private LocalDate date; 17 | private Map rates; 18 | } 19 | -------------------------------------------------------------------------------- /src/test/java/com/exchangeapi/currencyexchange/base/BaseControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.base; 2 | 3 | import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; 4 | import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.ActiveProfiles; 7 | 8 | @SpringBootTest 9 | @AutoConfigureMockMvc 10 | @ActiveProfiles(value = "test") 11 | public abstract class BaseControllerTest { 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/exchangeapi/currencyexchange/payload/response/RateResponse.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.payload.response; 2 | 3 | import com.exchangeapi.currencyexchange.entity.enums.EnumCurrency; 4 | import lombok.Builder; 5 | 6 | import java.time.LocalDate; 7 | import java.util.Map; 8 | 9 | @Builder 10 | public record RateResponse(EnumCurrency base, 11 | LocalDate date, 12 | Map rates, 13 | boolean success, 14 | long timestamp) { 15 | } 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/**/target/ 5 | !**/src/test/**/target/ 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | !**/src/main/**/build/ 30 | !**/src/test/**/build/ 31 | 32 | ### VS Code ### 33 | .vscode/ 34 | 35 | ### Environment file 36 | .env 37 | -------------------------------------------------------------------------------- /src/main/java/com/exchangeapi/currencyexchange/config/SpringCachingConfig.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.config; 2 | 3 | import org.springframework.cache.CacheManager; 4 | import org.springframework.cache.annotation.EnableCaching; 5 | import org.springframework.cache.concurrent.ConcurrentMapCacheManager; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | 9 | import static com.exchangeapi.currencyexchange.constants.Constants.EXCHANGE_CACHE_NAME; 10 | 11 | @Configuration 12 | @EnableCaching 13 | public class SpringCachingConfig { 14 | 15 | @Bean 16 | public CacheManager cacheManager() { 17 | return new ConcurrentMapCacheManager(EXCHANGE_CACHE_NAME); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/exchangeapi/currencyexchange/entity/BaseEntity.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.entity; 2 | 3 | import jakarta.persistence.GeneratedValue; 4 | import jakarta.persistence.Id; 5 | import jakarta.persistence.MappedSuperclass; 6 | import lombok.*; 7 | import lombok.experimental.SuperBuilder; 8 | import org.hibernate.annotations.GenericGenerator; 9 | 10 | import java.time.LocalDate; 11 | 12 | @MappedSuperclass 13 | @Getter 14 | @Setter 15 | @SuperBuilder 16 | @AllArgsConstructor 17 | @NoArgsConstructor 18 | public class BaseEntity { 19 | 20 | @Id 21 | @GeneratedValue(generator = "UUID") 22 | @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator") 23 | private String id; 24 | 25 | private LocalDate date; 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/exchangeapi/currencyexchange/config/SpringCacheCustomizer.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.config; 2 | 3 | import org.springframework.boot.autoconfigure.cache.CacheManagerCustomizer; 4 | import org.springframework.cache.concurrent.ConcurrentMapCacheManager; 5 | import org.springframework.stereotype.Component; 6 | 7 | import java.util.List; 8 | 9 | import static com.exchangeapi.currencyexchange.constants.Constants.EXCHANGE_CACHE_NAME; 10 | 11 | @Component 12 | public class SpringCacheCustomizer implements CacheManagerCustomizer { 13 | 14 | @Override 15 | public void customize(ConcurrentMapCacheManager cacheManager) { 16 | cacheManager.setCacheNames(List.of(EXCHANGE_CACHE_NAME)); 17 | cacheManager.setAllowNullValues(false); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/test/resources/application-test.yaml: -------------------------------------------------------------------------------- 1 | spring: 2 | config: 3 | import: optional:file:.env[.properties] 4 | datasource: 5 | driverClassName: org.h2.Driver 6 | url: jdbc:h2:mem:exchange 7 | username: sa 8 | jackson: 9 | serialization: 10 | fail-on-empty-beans: false 11 | jpa: 12 | database-platform: org.hibernate.dialect.H2Dialect 13 | hibernate: 14 | ddl-auto: update 15 | h2: 16 | console: 17 | enabled: true 18 | 19 | resilience4j: 20 | ratelimiter: 21 | instances: 22 | basic: 23 | limit-for-period: 10 24 | limit-refresh-period: 1m 25 | timeout-duration: 10s 26 | 27 | exchange-api: 28 | api-url: https://api.apilayer.com/exchangerates_data/ 29 | api-key: ${EXCHANGE_API_API_KEY:default-key} 30 | api-call-limit: 60 31 | cache-name: exchanges 32 | cache-ttl: 10000 33 | -------------------------------------------------------------------------------- /src/main/java/com/exchangeapi/currencyexchange/config/OpenApiConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.config; 2 | 3 | import io.swagger.v3.oas.models.OpenAPI; 4 | import io.swagger.v3.oas.models.info.Info; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | 8 | @Configuration 9 | public class OpenApiConfiguration { 10 | 11 | @Bean 12 | public OpenAPI customOpenAPI() { 13 | return new OpenAPI() 14 | .info(new Info() 15 | .title("Exchange API") 16 | .version("1.0") 17 | .description(""" 18 | This is an api which provides currency exchange 19 | for one hour according to currency names 20 | """ 21 | )); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/resources/application.yaml: -------------------------------------------------------------------------------- 1 | spring: 2 | config: 3 | import: optional:file:.env[.properties] 4 | datasource: 5 | driverClassName: org.h2.Driver 6 | url: jdbc:h2:mem:exchange 7 | username: sa 8 | jackson: 9 | serialization: 10 | fail-on-empty-beans: false 11 | jpa: 12 | database-platform: org.hibernate.dialect.H2Dialect 13 | hibernate: 14 | ddl-auto: update 15 | h2: 16 | console: 17 | enabled: true 18 | 19 | resilience4j: 20 | ratelimiter: 21 | instances: 22 | basic: 23 | limit-for-period: 10 24 | limit-refresh-period: 1m 25 | timeout-duration: 10s 26 | 27 | exchange-api: 28 | api-url: https://api.apilayer.com/exchangerates_data/ 29 | api-key: ${EXCHANGE_API_API_KEY:default-key} 30 | api-call-limit: 60 31 | cache-name: exchanges 32 | cache-ttl: 10000 33 | 34 | management: 35 | endpoints: 36 | web: 37 | exposure: 38 | include: "*" 39 | endpoint: 40 | metrics: 41 | enabled: true 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /src/main/java/com/exchangeapi/currencyexchange/entity/RateEntity.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.entity; 2 | 3 | import com.exchangeapi.currencyexchange.entity.enums.EnumCurrency; 4 | import jakarta.persistence.*; 5 | import lombok.AllArgsConstructor; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | import lombok.experimental.SuperBuilder; 9 | 10 | import java.util.Map; 11 | import java.util.Set; 12 | 13 | 14 | @Entity 15 | @Data 16 | @NoArgsConstructor 17 | @AllArgsConstructor 18 | @Table(name = "RateEntity") 19 | @SuperBuilder 20 | public class RateEntity extends BaseEntity{ 21 | 22 | @Enumerated(EnumType.STRING) 23 | private EnumCurrency base; 24 | 25 | @ElementCollection 26 | @CollectionTable(name = "rate_mapping", 27 | joinColumns = {@JoinColumn(name = "rate_id", referencedColumnName = "id")}) 28 | @MapKeyColumn(name = "currency") 29 | @MapKeyEnumerated(EnumType.STRING) 30 | @Column(name = "rates") 31 | private Map rates; 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/exchangeapi/currencyexchange/entity/ExchangeEntity.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.entity; 2 | 3 | import com.exchangeapi.currencyexchange.entity.enums.EnumCurrency; 4 | import jakarta.persistence.*; 5 | import lombok.AllArgsConstructor; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | import lombok.experimental.SuperBuilder; 9 | 10 | import java.util.Map; 11 | import java.util.Set; 12 | 13 | @Entity 14 | @Data 15 | @NoArgsConstructor 16 | @AllArgsConstructor 17 | @Table(name = "ExchangeEntity") 18 | @SuperBuilder 19 | public class ExchangeEntity extends BaseEntity { 20 | 21 | @Enumerated(EnumType.STRING) 22 | private EnumCurrency base; 23 | 24 | private Double amount; 25 | 26 | @ElementCollection 27 | @CollectionTable(name = "exchange_mapping", 28 | joinColumns = {@JoinColumn(name = "exchange_id", referencedColumnName = "id")}) 29 | @MapKeyColumn(name = "currency") 30 | @MapKeyEnumerated(EnumType.STRING) 31 | @Column(name = "rates") 32 | private Map rates; 33 | } 34 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # https://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.7/apache-maven-3.8.7-bin.zip 18 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar 19 | -------------------------------------------------------------------------------- /src/main/java/com/exchangeapi/currencyexchange/constants/Constants.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.constants; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.stereotype.Component; 5 | 6 | @Component 7 | public class Constants { 8 | 9 | public static String EXCHANGE_API_BASE_URL; 10 | public static String EXCHANGE_API_API_KEY; 11 | 12 | public static String EXCHANGE_CACHE_NAME; 13 | public static Integer EXCHANGE_API_CALL_LIMIT; 14 | 15 | @Value("${exchange-api.api-url}") 16 | public void setExchangeApiBaseUrl(String apiUrl) { 17 | EXCHANGE_API_BASE_URL = apiUrl; 18 | } 19 | 20 | @Value("${exchange-api.api-key}") 21 | public void setExchangeApiKey(String apiKey) { 22 | EXCHANGE_API_API_KEY = apiKey; 23 | } 24 | 25 | @Value("${exchange-api.cache-name}") 26 | public void setExchangeCacheName(String cacheName) { 27 | EXCHANGE_CACHE_NAME = cacheName; 28 | } 29 | 30 | @Value("${exchange-api.api-call-limit}") 31 | public void setExchangeApiCallLimit(Integer apiCallLimit) { 32 | EXCHANGE_API_CALL_LIMIT = apiCallLimit; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/exchangeapi/currencyexchange/config/RestTemplateConfig.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.config; 2 | 3 | import com.exchangeapi.currencyexchange.exception.RestTemplateErrorHandler; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; 7 | import org.springframework.web.client.RestTemplate; 8 | 9 | @Configuration 10 | public class RestTemplateConfig { 11 | 12 | private HttpComponentsClientHttpRequestFactory getClientHttpRequestFactory() { 13 | 14 | // Create an instance of Apache HttpClient 15 | HttpComponentsClientHttpRequestFactory clientHttpRequestFactory 16 | = new HttpComponentsClientHttpRequestFactory(); 17 | 18 | int connectTimeout = 5000; 19 | 20 | clientHttpRequestFactory.setConnectTimeout(connectTimeout); 21 | 22 | return clientHttpRequestFactory; 23 | } 24 | 25 | @Bean 26 | public RestTemplate getRestTemplate() { 27 | RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory()); 28 | restTemplate.setErrorHandler(new RestTemplateErrorHandler()); 29 | return restTemplate; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/exchangeapi/currencyexchange/controller/ExchangeController.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.controller; 2 | 3 | import com.exchangeapi.currencyexchange.dto.ExchangeDto; 4 | import com.exchangeapi.currencyexchange.entity.enums.EnumCurrency; 5 | import com.exchangeapi.currencyexchange.service.ExchangeService; 6 | import io.github.resilience4j.ratelimiter.annotation.RateLimiter; 7 | import lombok.AllArgsConstructor; 8 | import org.springframework.http.ResponseEntity; 9 | import org.springframework.web.bind.annotation.*; 10 | 11 | import java.util.List; 12 | 13 | @RestController 14 | @RequestMapping("/v1/exchange") 15 | @AllArgsConstructor 16 | public class ExchangeController { 17 | 18 | private final ExchangeService exchangeService; 19 | 20 | @RateLimiter(name = "basic") 21 | @GetMapping 22 | public ResponseEntity getRates(@RequestParam(name = "base",required = false) EnumCurrency base, 23 | @RequestParam(name = "target",required = false) List target, 24 | @RequestParam(name = "amount") Double amount) { 25 | 26 | return ResponseEntity.ok(exchangeService.calculateExchangeRate(amount 27 | ,base, target)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/exchangeapi/currencyexchange/controller/ConversionController.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.controller; 2 | 3 | import com.exchangeapi.currencyexchange.dto.ExchangeDto; 4 | import com.exchangeapi.currencyexchange.service.ExchangeService; 5 | import io.github.resilience4j.ratelimiter.annotation.RateLimiter; 6 | import lombok.AllArgsConstructor; 7 | import org.springframework.http.ResponseEntity; 8 | import org.springframework.web.bind.annotation.*; 9 | 10 | import java.time.LocalDate; 11 | import java.util.List; 12 | 13 | @RestController 14 | @RequestMapping("/v1/conversion") 15 | @AllArgsConstructor 16 | public class ConversionController { 17 | 18 | private final ExchangeService exchangeService; 19 | 20 | @RateLimiter(name = "basic") 21 | @GetMapping("/{id}") 22 | public ResponseEntity getConversion(@PathVariable(name = "id") String id) { 23 | return ResponseEntity.ok(exchangeService.getConversion(id)); 24 | } 25 | 26 | @RateLimiter(name = "basic") 27 | @GetMapping 28 | public ResponseEntity> getConversionList(@RequestParam(name = "startDate") LocalDate startDate, 29 | @RequestParam(name = "endDate") LocalDate endDate) { 30 | 31 | return ResponseEntity.ok(exchangeService.getConversionList(startDate, 32 | endDate)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/exchangeapi/currencyexchange/controller/RateController.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.controller; 2 | 3 | import com.exchangeapi.currencyexchange.dto.RateDto; 4 | import com.exchangeapi.currencyexchange.entity.enums.EnumCurrency; 5 | import com.exchangeapi.currencyexchange.service.RateService; 6 | import io.github.resilience4j.ratelimiter.annotation.RateLimiter; 7 | import lombok.AllArgsConstructor; 8 | import lombok.extern.slf4j.Slf4j; 9 | import org.springframework.format.annotation.DateTimeFormat; 10 | import org.springframework.http.ResponseEntity; 11 | import org.springframework.web.bind.annotation.*; 12 | 13 | import java.time.LocalDate; 14 | import java.util.List; 15 | 16 | 17 | @RestController 18 | @RequestMapping("/v1/rate") 19 | @AllArgsConstructor 20 | @Slf4j 21 | public class RateController { 22 | 23 | private final RateService rateService; 24 | 25 | @RateLimiter(name = "basic") 26 | @GetMapping 27 | public ResponseEntity getRates(@RequestParam(name = "base",required = false) EnumCurrency base, 28 | @RequestParam(name = "target",required = false) List target, 29 | @RequestParam(name = "date",required = false) @DateTimeFormat(pattern = "yyyy-mm-dd") LocalDate date) { 30 | log.info("RateController | getRates is called"); 31 | return ResponseEntity.ok(rateService.calculateRate(base, target,date)); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/exchangeapi/currencyexchange/exception/RestTemplateErrorHandler.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.exception; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import org.springframework.http.HttpStatus; 5 | import org.springframework.http.client.ClientHttpResponse; 6 | import org.springframework.web.client.ResponseErrorHandler; 7 | 8 | import java.io.BufferedReader; 9 | import java.io.IOException; 10 | import java.io.InputStreamReader; 11 | import java.util.stream.Collectors; 12 | 13 | public class RestTemplateErrorHandler implements ResponseErrorHandler { 14 | 15 | @Override 16 | public boolean hasError(ClientHttpResponse response) throws IOException { 17 | return response.getStatusCode().is4xxClientError() || response.getStatusCode().is5xxServerError(); 18 | } 19 | 20 | @Override 21 | public void handleError(ClientHttpResponse response) throws IOException { 22 | 23 | if (response.getStatusCode().is4xxClientError() 24 | || response.getStatusCode().is5xxServerError()) { 25 | 26 | 27 | try (BufferedReader reader = new BufferedReader( 28 | new InputStreamReader(response.getBody()))) { 29 | String httpBodyResponse = reader.lines() 30 | .collect(Collectors.joining("")); 31 | 32 | ObjectMapper mapper = new ObjectMapper(); 33 | 34 | RestTemplateError restTemplateError = mapper 35 | .readValue(httpBodyResponse, 36 | RestTemplateError.class); 37 | 38 | 39 | throw new RestServiceException( 40 | restTemplateError.path(), 41 | HttpStatus.resolve(response.getStatusCode().value()), 42 | restTemplateError.error()); 43 | } 44 | 45 | } 46 | 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/test/java/com/exchangeapi/currencyexchange/controller/ExchangeControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.controller; 2 | 3 | import com.exchangeapi.currencyexchange.base.BaseControllerTest; 4 | import com.exchangeapi.currencyexchange.dto.ExchangeDto; 5 | import com.exchangeapi.currencyexchange.entity.enums.EnumCurrency; 6 | import com.exchangeapi.currencyexchange.service.ExchangeService; 7 | import org.junit.jupiter.api.Test; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.test.mock.mockito.MockBean; 10 | import org.springframework.test.web.servlet.MockMvc; 11 | 12 | import java.time.LocalDate; 13 | import java.util.Arrays; 14 | import java.util.Collections; 15 | 16 | import static org.mockito.Mockito.when; 17 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 18 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 19 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; 20 | import static org.hamcrest.Matchers.is; 21 | 22 | class ExchangeControllerTest extends BaseControllerTest { 23 | 24 | @Autowired 25 | private MockMvc mockMvc; 26 | 27 | @MockBean 28 | private ExchangeService exchangeService; 29 | 30 | @Test 31 | public void testGetRates() throws Exception { 32 | // Mock the response from the ExchangeService 33 | ExchangeDto exchangeDto = ExchangeDto.builder() 34 | .id("1") 35 | .base(EnumCurrency.USD) 36 | .amount(100.0) 37 | .date(LocalDate.now()) 38 | .rates(Collections.singletonMap(EnumCurrency.EUR, 0.85)) 39 | .build(); 40 | when(exchangeService.calculateExchangeRate(100.0, EnumCurrency.USD, Arrays.asList(EnumCurrency.EUR))) 41 | .thenReturn(exchangeDto); 42 | 43 | // Perform the GET request 44 | mockMvc.perform(get("/v1/exchange") 45 | .param("base", "USD") 46 | .param("target", "EUR") 47 | .param("amount", "100.0")) 48 | .andExpect(status().isOk()) 49 | .andExpect(jsonPath("$.id", is("1"))) 50 | .andExpect(jsonPath("$.base", is("USD"))) 51 | .andExpect(jsonPath("$.amount", is(100.0))) 52 | .andExpect(jsonPath("$.date", is(LocalDate.now().toString()))) 53 | .andExpect(jsonPath("$.rates.EUR", is(0.85))); 54 | } 55 | } -------------------------------------------------------------------------------- /postman_collection/Currency Exchange API.postman_collection.json: -------------------------------------------------------------------------------- 1 | { 2 | "info": { 3 | "_postman_id": "9cc1301a-14f7-408c-8171-8171af378b27", 4 | "name": "Currency Exchange API", 5 | "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", 6 | "_exporter_id": "5570426" 7 | }, 8 | "item": [ 9 | { 10 | "name": "Get Rates", 11 | "request": { 12 | "method": "GET", 13 | "header": [], 14 | "url": { 15 | "raw": "http://localhost:8080/v1/rate?base=USD&target=EUR,TRY&date=2023-05-21", 16 | "protocol": "http", 17 | "host": [ 18 | "localhost" 19 | ], 20 | "port": "8080", 21 | "path": [ 22 | "v1", 23 | "rate" 24 | ], 25 | "query": [ 26 | { 27 | "key": "base", 28 | "value": "USD" 29 | }, 30 | { 31 | "key": "target", 32 | "value": "EUR,TRY" 33 | }, 34 | { 35 | "key": "date", 36 | "value": "2023-05-21" 37 | } 38 | ] 39 | } 40 | }, 41 | "response": [] 42 | }, 43 | { 44 | "name": "Get Exchange Rates By Exchange Request Info", 45 | "protocolProfileBehavior": { 46 | "disableBodyPruning": true 47 | }, 48 | "request": { 49 | "method": "GET", 50 | "header": [], 51 | "body": { 52 | "mode": "raw", 53 | "raw": "", 54 | "options": { 55 | "raw": { 56 | "language": "json" 57 | } 58 | } 59 | }, 60 | "url": { 61 | "raw": "http://localhost:8080/v1/exchange?base=USD&target=EUR,TRY&amount=100", 62 | "protocol": "http", 63 | "host": [ 64 | "localhost" 65 | ], 66 | "port": "8080", 67 | "path": [ 68 | "v1", 69 | "exchange" 70 | ], 71 | "query": [ 72 | { 73 | "key": "base", 74 | "value": "USD" 75 | }, 76 | { 77 | "key": "target", 78 | "value": "EUR,TRY" 79 | }, 80 | { 81 | "key": "amount", 82 | "value": "100" 83 | } 84 | ] 85 | } 86 | }, 87 | "response": [] 88 | }, 89 | { 90 | "name": "Get Conversion", 91 | "request": { 92 | "method": "GET", 93 | "header": [], 94 | "url": { 95 | "raw": "http://localhost:8080/v1/conversion/2f5813e0-d3ce-4475-9d4b-2245d6efde91", 96 | "protocol": "http", 97 | "host": [ 98 | "localhost" 99 | ], 100 | "port": "8080", 101 | "path": [ 102 | "v1", 103 | "conversion", 104 | "2f5813e0-d3ce-4475-9d4b-2245d6efde91" 105 | ] 106 | } 107 | }, 108 | "response": [] 109 | }, 110 | { 111 | "name": "Get Conversion List", 112 | "request": { 113 | "method": "GET", 114 | "header": [], 115 | "url": { 116 | "raw": "http://localhost:8080/v1/conversion?startDate=2023-05-20&endDate=2023-05-21", 117 | "protocol": "http", 118 | "host": [ 119 | "localhost" 120 | ], 121 | "port": "8080", 122 | "path": [ 123 | "v1", 124 | "conversion" 125 | ], 126 | "query": [ 127 | { 128 | "key": "startDate", 129 | "value": "2023-05-20" 130 | }, 131 | { 132 | "key": "endDate", 133 | "value": "2023-05-21" 134 | } 135 | ] 136 | } 137 | }, 138 | "response": [] 139 | } 140 | ] 141 | } -------------------------------------------------------------------------------- /src/test/java/com/exchangeapi/currencyexchange/controller/RateControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.controller; 2 | 3 | import com.exchangeapi.currencyexchange.base.BaseControllerTest; 4 | import com.exchangeapi.currencyexchange.dto.RateDto; 5 | import com.exchangeapi.currencyexchange.dto.RateInfoDto; 6 | import com.exchangeapi.currencyexchange.entity.enums.EnumCurrency; 7 | import com.exchangeapi.currencyexchange.service.RateService; 8 | import org.junit.jupiter.api.Disabled; 9 | import org.junit.jupiter.api.Test; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.boot.test.mock.mockito.MockBean; 12 | import org.springframework.http.MediaType; 13 | import org.springframework.test.web.servlet.MockMvc; 14 | 15 | import java.time.LocalDate; 16 | import java.util.Arrays; 17 | import java.util.List; 18 | 19 | import static org.hamcrest.Matchers.is; 20 | import static org.mockito.Mockito.*; 21 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 22 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 23 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; 24 | 25 | 26 | class RateControllerTest extends BaseControllerTest { 27 | 28 | @Autowired 29 | private MockMvc mockMvc; 30 | 31 | @MockBean 32 | private RateService rateService; 33 | 34 | @Test 35 | void getRates_shouldReturnRateDto() throws Exception { 36 | // Mocked data 37 | EnumCurrency base = EnumCurrency.EUR; 38 | List targets = Arrays.asList(EnumCurrency.USD, EnumCurrency.GBP); 39 | LocalDate date = LocalDate.of(2023, 5, 22); 40 | 41 | List rates = Arrays.asList( 42 | new RateInfoDto(EnumCurrency.USD, 1.2), 43 | new RateInfoDto(EnumCurrency.GBP, 0.9) 44 | ); 45 | 46 | // Mocked RateDto 47 | RateDto mockedRateDto = RateDto.builder() 48 | .base(base) 49 | .rates(rates) 50 | .date(date) 51 | .build(); 52 | 53 | // Mock the rateService.calculateRate() method 54 | when(rateService.calculateRate(base, targets, date)).thenReturn(mockedRateDto); 55 | 56 | // Perform the GET request 57 | mockMvc.perform(get("/v1/rate") 58 | .param("base", base.toString()) 59 | .param("target", EnumCurrency.USD.toString()) 60 | .param("target", EnumCurrency.GBP.toString()) 61 | .param("date", date.toString()) 62 | .contentType(MediaType.APPLICATION_JSON)) 63 | .andExpect(status().isOk()) 64 | .andExpect(jsonPath("$.base", is(base.toString()))) 65 | .andExpect(jsonPath("$.rates[0].currency", is(EnumCurrency.USD.toString()))) 66 | .andExpect(jsonPath("$.rates[0].rate", is(1.2))) 67 | .andExpect(jsonPath("$.rates[1].currency", is(EnumCurrency.GBP.toString()))) 68 | .andExpect(jsonPath("$.rates[1].rate", is(0.9))) 69 | .andExpect(jsonPath("$.date", is(date.toString()))); 70 | 71 | // Verify that the rateService.calculateRate() method was called 72 | verify(rateService, times(1)).calculateRate(base, targets, date); 73 | } 74 | } -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 3.0.6 9 | 10 | 11 | com.exchangeapi 12 | currencyexchange 13 | 0.0.1-SNAPSHOT 14 | currencyexchange 15 | Exchange API for Spring Boot 16 | 17 | 17 18 | 2.14.2 19 | 2.0.2 20 | 2.0.2 21 | 22 | 23 | 24 | 25 | 26 | org.springframework.boot 27 | spring-boot-starter-web 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-test 32 | test 33 | 34 | 35 | org.springframework.boot 36 | spring-boot-starter-data-jpa 37 | 38 | 39 | org.springframework.boot 40 | spring-boot-starter-actuator 41 | 42 | 43 | 44 | 45 | com.h2database 46 | h2 47 | runtime 48 | 49 | 50 | 51 | 52 | org.projectlombok 53 | lombok 54 | true 55 | 56 | 57 | 58 | 59 | org.springdoc 60 | springdoc-openapi-starter-webmvc-ui 61 | ${openapi.version} 62 | 63 | 64 | 65 | 66 | com.fasterxml.jackson.core 67 | jackson-databind 68 | 69 | 70 | com.fasterxml.jackson.datatype 71 | jackson-datatype-jsr310 72 | ${jackson.version} 73 | 74 | 75 | 76 | 77 | io.github.resilience4j 78 | resilience4j-spring-boot3 79 | ${resilience4j.version} 80 | 81 | 82 | 83 | 84 | org.hibernate.validator 85 | hibernate-validator 86 | 87 | 88 | 89 | 90 | org.apache.httpcomponents.client5 91 | httpclient5 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | org.springframework.boot 100 | spring-boot-maven-plugin 101 | 102 | 103 | 104 | org.projectlombok 105 | lombok 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | -------------------------------------------------------------------------------- /src/test/java/com/exchangeapi/currencyexchange/controller/ConversionControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.controller; 2 | 3 | import com.exchangeapi.currencyexchange.base.BaseControllerTest; 4 | import com.exchangeapi.currencyexchange.dto.ExchangeDto; 5 | import com.exchangeapi.currencyexchange.entity.enums.EnumCurrency; 6 | import com.exchangeapi.currencyexchange.service.ExchangeService; 7 | import org.junit.jupiter.api.Test; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.test.mock.mockito.MockBean; 10 | import org.springframework.http.MediaType; 11 | import org.springframework.test.web.servlet.MockMvc; 12 | 13 | import java.time.LocalDate; 14 | import java.util.Arrays; 15 | import java.util.Collections; 16 | import java.util.List; 17 | 18 | import static org.hamcrest.Matchers.is; 19 | import static org.junit.jupiter.api.Assertions.*; 20 | import static org.mockito.Mockito.when; 21 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 22 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 23 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; 24 | 25 | class ConversionControllerTest extends BaseControllerTest { 26 | 27 | @Autowired 28 | private MockMvc mockMvc; 29 | 30 | @MockBean 31 | private ExchangeService exchangeService; 32 | 33 | @Test 34 | public void testGetConversion() throws Exception { 35 | // Mock the response from the ExchangeService 36 | ExchangeDto exchangeDto = ExchangeDto.builder() 37 | .id("1") 38 | .base(EnumCurrency.USD) 39 | .amount(100.0) 40 | .date(LocalDate.now()) 41 | .rates(Collections.singletonMap(EnumCurrency.EUR, 0.85)) 42 | .build(); 43 | 44 | when(exchangeService.getConversion("1")).thenReturn(exchangeDto); 45 | 46 | mockMvc.perform(get("/v1/conversion/{id}", "1") 47 | .contentType(MediaType.APPLICATION_JSON)) 48 | .andExpect(status().isOk()) 49 | .andExpect(jsonPath("$.id", is("1"))) 50 | .andExpect(jsonPath("$.base", is("USD"))) 51 | .andExpect(jsonPath("$.amount", is(100.0))) 52 | .andExpect(jsonPath("$.date", is(LocalDate.now().toString()))) 53 | .andExpect(jsonPath("$.rates.EUR", is(0.85))); 54 | } 55 | 56 | @Test 57 | public void testGetConversionList() throws Exception { 58 | LocalDate startDate = LocalDate.of(2023, 1, 1); 59 | LocalDate endDate = LocalDate.of(2023, 1, 31); 60 | 61 | ExchangeDto exchangeDto1 = ExchangeDto.builder() 62 | .id("123") 63 | .base(EnumCurrency.USD) 64 | .amount(100.0) 65 | .date(LocalDate.now()) 66 | .rates(Collections.singletonMap(EnumCurrency.EUR, 0.85)) 67 | .build(); 68 | 69 | ExchangeDto exchangeDto2 = ExchangeDto.builder() 70 | .id("456") 71 | .base(EnumCurrency.EUR) 72 | .amount(200.0) 73 | .date(LocalDate.now()) 74 | .rates(Collections.singletonMap(EnumCurrency.USD, 1.2)) 75 | .build(); 76 | 77 | List exchangeDtoList = Arrays.asList(exchangeDto1, exchangeDto2); 78 | 79 | when(exchangeService.getConversionList(startDate, endDate)).thenReturn(exchangeDtoList); 80 | 81 | mockMvc.perform(get("/v1/conversion") 82 | .param("startDate", startDate.toString()) 83 | .param("endDate", endDate.toString()) 84 | .contentType(MediaType.APPLICATION_JSON)) 85 | .andExpect(status().isOk()) 86 | .andExpect(jsonPath("$[0].id", is("123"))) 87 | .andExpect(jsonPath("$[0].base", is("USD"))) 88 | .andExpect(jsonPath("$[0].amount", is(100.0))) 89 | .andExpect(jsonPath("$[0].date", is(LocalDate.now().toString()))) 90 | .andExpect(jsonPath("$[0].rates.EUR", is(0.85))) 91 | .andExpect(jsonPath("$[1].id", is("456"))) 92 | .andExpect(jsonPath("$[1].base", is("EUR"))) 93 | .andExpect(jsonPath("$[1].amount", is(200.0))) 94 | .andExpect(jsonPath("$[1].date", is(LocalDate.now().toString()))) 95 | .andExpect(jsonPath("$[1].rates.USD", is(1.2))); 96 | 97 | } 98 | } -------------------------------------------------------------------------------- /src/main/java/com/exchangeapi/currencyexchange/service/ExchangeService.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.service; 2 | 3 | import com.exchangeapi.currencyexchange.dto.ExchangeDto; 4 | import com.exchangeapi.currencyexchange.dto.RateDto; 5 | import com.exchangeapi.currencyexchange.dto.RateInfoDto; 6 | import com.exchangeapi.currencyexchange.entity.ExchangeEntity; 7 | import com.exchangeapi.currencyexchange.entity.enums.EnumCurrency; 8 | import com.exchangeapi.currencyexchange.exception.ExchangeNotFoundException; 9 | import com.exchangeapi.currencyexchange.repository.ExchangeRepository; 10 | import com.fasterxml.jackson.databind.ObjectMapper; 11 | import jakarta.annotation.PostConstruct; 12 | import lombok.AllArgsConstructor; 13 | import lombok.extern.slf4j.Slf4j; 14 | import org.springframework.cache.annotation.CacheConfig; 15 | import org.springframework.cache.annotation.CacheEvict; 16 | import org.springframework.cache.annotation.CachePut; 17 | import org.springframework.cache.annotation.Cacheable; 18 | import org.springframework.scheduling.annotation.Scheduled; 19 | import org.springframework.stereotype.Service; 20 | 21 | import java.math.BigDecimal; 22 | import java.math.MathContext; 23 | import java.math.RoundingMode; 24 | import java.time.LocalDate; 25 | import java.util.List; 26 | import java.util.Map; 27 | import java.util.stream.Collectors; 28 | 29 | 30 | @Service 31 | @CacheConfig(cacheNames = {"exchanges"}) 32 | @AllArgsConstructor 33 | @Slf4j 34 | public class ExchangeService { 35 | 36 | private final ExchangeRepository exchangeRepository; 37 | private final RateService rateService; 38 | 39 | 40 | @CachePut(key = "#result.id") 41 | public ExchangeDto calculateExchangeRate(Double amount, EnumCurrency base, List targets) { 42 | log.info("ExchangeService | calculateExchangeRate is called"); 43 | 44 | RateDto rateDto = rateService.calculateRate(base,targets); 45 | 46 | Map exchanges = rateDto.getRates() 47 | .stream() 48 | .map(rateInfoDto -> mapToRateInfoDto(rateInfoDto,amount)) 49 | .collect(Collectors.toMap(RateInfoDto::currency,RateInfoDto::rate)); 50 | 51 | ExchangeEntity exchangeEntity = ExchangeEntity.builder() 52 | .base(rateDto.getBase()) 53 | .rates(exchanges) 54 | .amount(amount) 55 | .date(LocalDate.now()) 56 | .build(); 57 | 58 | ExchangeEntity savedExchange = exchangeRepository.saveAndFlush(exchangeEntity); 59 | 60 | return mapToExchangeDTO(savedExchange); 61 | } 62 | 63 | 64 | @Cacheable(key = "#id") 65 | public ExchangeDto getConversion(String id) { 66 | log.info("ExchangeService | calculateExchangeRate is called"); 67 | return exchangeRepository.findById(id).map(this::mapToExchangeDTO).orElseThrow(() -> new ExchangeNotFoundException("Not Found")); 68 | } 69 | 70 | public List getConversionList(LocalDate startDate, LocalDate endDate) { 71 | log.info("ExchangeService | getConversionList is called"); 72 | return exchangeRepository.findByDateBetween(startDate, endDate).stream() 73 | .map(this::mapToExchangeDTO) 74 | .collect(Collectors.toList()); 75 | } 76 | 77 | private ExchangeDto mapToExchangeDTO(ExchangeEntity exchangeEntity) { 78 | log.info("ExchangeService | mapToExchangeDTO is called"); 79 | return ExchangeDto.builder() 80 | .id(exchangeEntity.getId()) 81 | .amount(exchangeEntity.getAmount()) 82 | .base(exchangeEntity.getBase()) 83 | .date(exchangeEntity.getDate()) 84 | .rates(exchangeEntity.getRates()) 85 | .build(); 86 | 87 | } 88 | 89 | private RateInfoDto mapToRateInfoDto(RateInfoDto rateInfoDto, Double amount) { 90 | log.info("ExchangeService | mapToRateInfoDto is called"); 91 | EnumCurrency enumCurrency = rateInfoDto.currency(); 92 | Double rate = BigDecimal.valueOf(rateInfoDto.rate()).multiply(BigDecimal.valueOf(amount), 93 | new MathContext(5, RoundingMode.CEILING)).doubleValue(); 94 | return new RateInfoDto(enumCurrency,rate); 95 | } 96 | 97 | @CacheEvict(allEntries = true) 98 | @PostConstruct 99 | @Scheduled(fixedRateString = "${exchange-api.cache-ttl}") 100 | public void clearCache(){ 101 | log.info("Caches are cleared"); 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /src/main/java/com/exchangeapi/currencyexchange/service/RateService.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.service; 2 | 3 | import com.exchangeapi.currencyexchange.dto.RateDto; 4 | import com.exchangeapi.currencyexchange.dto.RateInfoDto; 5 | import com.exchangeapi.currencyexchange.entity.RateEntity; 6 | import com.exchangeapi.currencyexchange.entity.enums.EnumCurrency; 7 | import com.exchangeapi.currencyexchange.payload.response.RateResponse; 8 | import com.exchangeapi.currencyexchange.repository.RateRepository; 9 | import lombok.AllArgsConstructor; 10 | import lombok.extern.slf4j.Slf4j; 11 | import org.springframework.http.*; 12 | import org.springframework.stereotype.Service; 13 | import org.springframework.web.client.RestTemplate; 14 | 15 | import java.time.LocalDate; 16 | import java.util.*; 17 | import java.util.stream.Collectors; 18 | 19 | import static com.exchangeapi.currencyexchange.constants.Constants.EXCHANGE_API_API_KEY; 20 | import static com.exchangeapi.currencyexchange.constants.Constants.EXCHANGE_API_BASE_URL; 21 | 22 | @Service 23 | @AllArgsConstructor 24 | @Slf4j 25 | public class RateService { 26 | 27 | private final RateRepository rateRepository; 28 | private final RestTemplate restTemplate; 29 | 30 | public RateDto calculateRate() { 31 | log.info("ExchangeService | calculateRates() is called | base null"); 32 | return calculateRate(null); 33 | } 34 | 35 | public RateDto calculateRate(EnumCurrency base) { 36 | log.info("ExchangeService | calculateRates(EnumCurrency base) is called | target null"); 37 | return calculateRate(base, null); 38 | } 39 | 40 | public RateDto calculateRate(EnumCurrency base, List targets) { 41 | log.info("ExchangeService | calculateRates(EnumCurrency base, List targets) is called | date null"); 42 | return calculateRate(base, targets, null); 43 | } 44 | 45 | public RateDto calculateRate(EnumCurrency base, List targets, LocalDate date) { 46 | log.info("ExchangeService | calculateRates is called"); 47 | 48 | base = Optional.ofNullable(base).orElse(EnumCurrency.EUR); 49 | targets = Optional.ofNullable(targets) 50 | .orElseGet(() -> Arrays.asList(EnumCurrency.values())); 51 | date = Optional.ofNullable(date).orElse(LocalDate.now()); 52 | 53 | LocalDate finalDate = date; 54 | EnumCurrency finalBase = base; 55 | List finalTargets = targets; 56 | 57 | RateEntity rateEntity = rateRepository.findOneByDate(date) 58 | .orElseGet(() -> saveRatesFromApi(finalDate, finalBase, finalTargets)); 59 | 60 | Map rates = rateEntity.getRates(); 61 | 62 | List rateInfoList = targets.stream() 63 | .map(currency -> new RateInfoDto(currency, rates.get(currency))) 64 | .collect(Collectors.toList()); 65 | 66 | return RateDto.builder() 67 | .id(rateEntity.getId()) 68 | .base(rateEntity.getBase()) 69 | .date(rateEntity.getDate()) 70 | .rates(rateInfoList) 71 | .build(); 72 | } 73 | 74 | private RateEntity saveRatesFromApi(LocalDate rateDate, EnumCurrency base, List targets) { 75 | 76 | log.info("ExchangeService | saveRatesFromApi is called"); 77 | 78 | HttpHeaders headers = new HttpHeaders(); 79 | headers.add("apikey", EXCHANGE_API_API_KEY); 80 | headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); 81 | final HttpEntity headersEntity = new HttpEntity<>(headers); 82 | String url = getExchangeUrl(rateDate, base, targets); 83 | 84 | ResponseEntity responseEntity = restTemplate.exchange(url, HttpMethod.GET, headersEntity, RateResponse.class); 85 | 86 | RateResponse rates = responseEntity.getBody(); 87 | RateEntity entity = convert(rates); 88 | return rateRepository.save(entity); 89 | } 90 | 91 | private String getExchangeUrl(LocalDate rateDate, EnumCurrency base, List targets) { 92 | log.info("ExchangeService | getExchangeUrl is called"); 93 | 94 | String symbols = String.join("%2C", targets.stream().map(EnumCurrency::name).toArray(String[]::new)); 95 | return EXCHANGE_API_BASE_URL + rateDate + "?symbols=" + symbols + "&base=" + base; 96 | } 97 | 98 | private RateEntity convert(RateResponse source) { 99 | log.info("ExchangeService | convert is called"); 100 | 101 | Map rates = source.rates(); 102 | 103 | return RateEntity.builder() 104 | .base(source.base()) 105 | .date(source.date()) 106 | .rates(rates) 107 | .build(); 108 | 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Spring Boot Currency Change API Example 2 | 3 | Main Information 4 | 5 | ### 📖 Information 6 | 7 |
    8 |
  • The purpose of the example is to handle with http get requests regarding currency exchange
  • 9 |
  • Here is the explanation of the currency exchange example 10 |
      11 |
    • Get rates from the database if the rate info is already inserted into database
    • 12 |
    • Get rates from apilayer.com and insert its value into database and return the rate info
    • 13 |
    • Get exchange rates by exchange request info covering base currency, target currency and lastly amount
    • 14 |
    • Get conversion by rate id
    • 15 |
    • Get all conversions between two dates named start date and end date
    • 16 |
    17 |
  • 18 |
19 | 20 | ### Explore Rest APIs 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 |
MethodUrlDescriptionValid Request ParamsValid Path Variable
GET/v1/rateGet RatesInfo
GET/v1/exchangeGet Exchange Rates By Exchange Request InfoInfo
GETgetconversionGet Conversion By IdInfo
GETgetconversionlistGet Conversion ListInfo
59 | 60 | ### Valid Request Params 61 | 62 | ##### Get Rates 63 | ``` 64 | http://localhost:8080/v1/rate?base=USD&target=EUR,TRY&date=2023-05-21 65 | 66 | base: USD 67 | target: EUR,TRY 68 | date: 2023-05-21 69 | ``` 70 | 71 | ##### Get Exchange Rates By Exchange Request Info 72 | ``` 73 | http://localhost:8080/v1/exchange?base=USD&target=EUR,TRY&amount=100 74 | 75 | base: USD 76 | target: EUR 77 | amount: 100 78 | ``` 79 | 80 | ##### Get Exchange Rates By Exchange Request Info 81 | ``` 82 | http://localhost:8080/v1/exchange?base=USD&target=EUR,TRY&amount=100 83 | 84 | base: USD 85 | target: EUR 86 | amount: 100 87 | ``` 88 | 89 | ##### Get Conversion List 90 | ``` 91 | http://localhost:8080/v1/conversion?startDate=2023-05-20&endDate=2023-05-22 92 | 93 | startDate: 2023-05-20 94 | endDate: 2023-05-22 95 | ``` 96 | 97 | ### Valid Path Variable 98 | 99 | ##### Get Conversion 100 | ``` 101 | http://localhost:8080/v1/conversion/17d98364-e435-40d7-a941-af535fc95065 102 | ``` 103 | 104 | ### Technologies 105 | 106 | --- 107 | - Java 17 108 | - Spring Boot 3.0 109 | - Open API Documentation 110 | - Restful API 111 | - Spring Cache 112 | - Actuator 113 | - Resilience4j 114 | - Lombok 115 | - Maven 116 | - Junit5 117 | - Mockito 118 | - Integration Tests 119 | - Docker 120 | - Docker Compose 121 | 122 | ### Prerequisites 123 | 124 | --- 125 | - Get API KEY from apilayer.com 126 | - Maven or Docker 127 | --- 128 | 129 | ### Get API KEY from apilayer.com 130 | 1 ) Open and register apilayer.com 131 | 132 | 2 ) Register Exchange Rates Data API and Get API key 133 | 134 | 135 | ### Create .env and Define API key 136 | --- 137 | EXCHANGE_API_API_KEY={YOUR_API_KEY} 138 | --- 139 | 140 | ### Docker Run 141 | The application can be built and run by the `Docker` engine. The `Dockerfile` has multistage build, so you do not need to build and run separately. 142 | 143 | Please follow directions shown below in order to build and run the application with Docker Compose file; 144 | 145 | ```sh 146 | $ cd currencyexchange 147 | $ docker-compose up -d 148 | ``` 149 | 150 | --- 151 | ### Maven Run 152 | To build and run the application with `Maven`, please follow the directions shown below; 153 | 154 | ```sh 155 | $ cd currencyexchange 156 | $ mvn clean install 157 | $ mvn spring-boot:run 158 | ``` 159 | 160 | ### Swagger 161 | You can reach the swagger-ui through the link shown below 162 | ``` 163 | http://localhost:8080/swagger-ui/index.html 164 | ``` 165 | 166 | ### Actuator 167 | You can reach the actuator through the link shown below 168 | ``` 169 | http://localhost:8080/actuator 170 | ``` 171 | 172 | ### Screenshots 173 | 174 |
175 | Click here to show the screenshots of project 176 |

Figure 1

177 | 178 |

Figure 2

179 | 180 |

Figure 3

181 | 182 |

Figure 4

183 | 184 |

Figure 5

185 | 186 |
-------------------------------------------------------------------------------- /src/main/java/com/exchangeapi/currencyexchange/exception/GeneralExceptionAdvice.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.exception; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.http.HttpHeaders; 5 | import org.springframework.http.HttpStatus; 6 | import org.springframework.http.HttpStatusCode; 7 | import org.springframework.http.ResponseEntity; 8 | import org.springframework.http.converter.HttpMessageNotReadableException; 9 | import org.springframework.web.HttpRequestMethodNotSupportedException; 10 | import org.springframework.web.bind.MethodArgumentNotValidException; 11 | import org.springframework.web.bind.MissingServletRequestParameterException; 12 | import org.springframework.web.bind.annotation.ControllerAdvice; 13 | import org.springframework.web.context.request.WebRequest; 14 | import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; 15 | 16 | import java.time.LocalDateTime; 17 | import java.util.ArrayList; 18 | import java.util.List; 19 | 20 | @ControllerAdvice 21 | @Slf4j 22 | public class GeneralExceptionAdvice extends ResponseEntityExceptionHandler { 23 | 24 | // handleMissingServletRequestParameter : triggers when there are missing parameters 25 | @Override 26 | protected ResponseEntity handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { 27 | 28 | List details = new ArrayList(); 29 | StringBuilder builder = new StringBuilder(); 30 | builder.append(ex.getMessage() + " is not supported"); 31 | details.add(builder.toString()); 32 | 33 | HttpStatus httpStatus = HttpStatus.valueOf(status.value()); 34 | 35 | Error error = new Error.ErrorBuilder() 36 | .timestamp(LocalDateTime.now()) 37 | .status(status.value()) 38 | .errorDetails(details) 39 | .path(request.getContextPath()) 40 | .httpStatus(httpStatus) 41 | .build(); 42 | 43 | logger.error("GlobalExceptionHandler | handleHttpRequestMethodNotSupported | ex : " + ex ); 44 | 45 | return ResponseEntity.status(status).body(error); 46 | 47 | } 48 | 49 | // handleMethodArgumentNotValid : triggers when @Valid fails 50 | @Override 51 | protected ResponseEntity handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { 52 | 53 | List details = new ArrayList(); 54 | ex.getBindingResult().getFieldErrors().forEach(err -> { 55 | String errorMessage = err.getDefaultMessage(); 56 | details.add(errorMessage); 57 | } 58 | ); 59 | 60 | HttpStatus httpStatus = HttpStatus.valueOf(status.value()); 61 | 62 | Error error = new Error.ErrorBuilder() 63 | .timestamp(LocalDateTime.now()) 64 | .status(status.value()) 65 | .errorDetails(details) 66 | .path(request.getContextPath()) 67 | .httpStatus(httpStatus) 68 | .build(); 69 | 70 | logger.error("GlobalExceptionHandler | handleMethodArgumentNotValid | ex : " + ex ); 71 | 72 | return new ResponseEntity<>(error, headers, status); 73 | } 74 | 75 | // handleMissingServletRequestParameter : triggers when there are missing parameters 76 | @Override 77 | protected ResponseEntity handleMissingServletRequestParameter(MissingServletRequestParameterException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { 78 | 79 | 80 | List details = new ArrayList(); 81 | StringBuilder builder = new StringBuilder(); 82 | builder.append(ex.getParameterName()); 83 | details.add(builder.toString()); 84 | 85 | HttpStatus httpStatus = HttpStatus.valueOf(status.value()); 86 | 87 | Error error = new Error.ErrorBuilder() 88 | .timestamp(LocalDateTime.now()) 89 | .status(status.value()) 90 | .errorDetails(details) 91 | .path(request.getContextPath()) 92 | .httpStatus(httpStatus) 93 | .build(); 94 | 95 | logger.error("GlobalExceptionHandler | handleMissingServletRequestParameter | ex : " + ex ); 96 | 97 | return ResponseEntity.status(status).body(error); 98 | 99 | } 100 | 101 | // handleHttpMessageNotReadable : triggers when the JSON is malformed 102 | @Override 103 | protected ResponseEntity handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { 104 | 105 | List details = new ArrayList(); 106 | StringBuilder builder = new StringBuilder(); 107 | builder.append(ex.getMessage()); 108 | details.add(builder.toString()); 109 | 110 | HttpStatus httpStatus = HttpStatus.valueOf(status.value()); 111 | 112 | Error error = new Error.ErrorBuilder() 113 | .timestamp(LocalDateTime.now()) 114 | .status(status.value()) 115 | .errorDetails(details) 116 | .path(request.getContextPath()) 117 | .httpStatus(httpStatus) 118 | .build(); 119 | 120 | logger.error("GlobalExceptionHandler | handleHttpMessageNotReadable | ex : " + ex ); 121 | 122 | return ResponseEntity.status(status).body(error); 123 | 124 | } 125 | 126 | } 127 | -------------------------------------------------------------------------------- /src/test/java/com/exchangeapi/currencyexchange/service/ExchangeServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.service; 2 | 3 | import com.exchangeapi.currencyexchange.base.BaseServiceTest; 4 | import com.exchangeapi.currencyexchange.dto.ExchangeDto; 5 | import com.exchangeapi.currencyexchange.dto.RateDto; 6 | import com.exchangeapi.currencyexchange.dto.RateInfoDto; 7 | import com.exchangeapi.currencyexchange.entity.ExchangeEntity; 8 | import com.exchangeapi.currencyexchange.entity.enums.EnumCurrency; 9 | import com.exchangeapi.currencyexchange.repository.ExchangeRepository; 10 | import org.junit.jupiter.api.BeforeEach; 11 | import org.junit.jupiter.api.Test; 12 | import org.mockito.InjectMocks; 13 | import org.mockito.Mock; 14 | 15 | import java.time.LocalDate; 16 | import java.util.Arrays; 17 | import java.util.Collections; 18 | import java.util.List; 19 | import java.util.Optional; 20 | import java.util.stream.Collectors; 21 | 22 | import static org.junit.jupiter.api.Assertions.*; 23 | import static org.mockito.ArgumentMatchers.any; 24 | import static org.mockito.ArgumentMatchers.eq; 25 | import static org.mockito.Mockito.when; 26 | 27 | class ExchangeServiceTest extends BaseServiceTest { 28 | 29 | @Mock 30 | private ExchangeRepository exchangeRepository; 31 | 32 | @Mock 33 | private RateService rateService; 34 | 35 | @InjectMocks 36 | private ExchangeService exchangeService; 37 | 38 | @Test 39 | public void testCalculateExchangeRate() { 40 | // Mocking dependencies 41 | EnumCurrency baseCurrency = EnumCurrency.USD; 42 | List targetCurrencies = Arrays.asList(EnumCurrency.EUR, EnumCurrency.GBP); 43 | 44 | List rateInfoDtos = Arrays.asList( 45 | new RateInfoDto(EnumCurrency.EUR, 0.85), 46 | new RateInfoDto(EnumCurrency.GBP, 0.72) 47 | ); 48 | 49 | RateDto rateDto = RateDto.builder() 50 | .base(baseCurrency) 51 | .rates(rateInfoDtos) 52 | .build(); 53 | 54 | when(rateService.calculateRate(eq(baseCurrency), eq(targetCurrencies))).thenReturn(rateDto); 55 | 56 | Double amount = 100.0; 57 | ExchangeEntity savedExchange = ExchangeEntity.builder() 58 | .base(baseCurrency) 59 | .amount(amount) 60 | .rates(rateInfoDtos.stream().collect(Collectors.toMap(RateInfoDto::currency, RateInfoDto::rate))) 61 | .build(); 62 | when(exchangeRepository.saveAndFlush(any(ExchangeEntity.class))).thenReturn(savedExchange); 63 | 64 | // Call the method 65 | ExchangeDto result = exchangeService.calculateExchangeRate(amount, baseCurrency, targetCurrencies); 66 | 67 | // Assertions 68 | assertNotNull(result); 69 | assertEquals(savedExchange.getId(), result.getId()); 70 | assertEquals(savedExchange.getBase(), result.getBase()); 71 | assertEquals(savedExchange.getAmount(), result.getAmount()); 72 | assertEquals(savedExchange.getDate(), result.getDate()); 73 | assertEquals(savedExchange.getRates(), result.getRates()); 74 | } 75 | 76 | @Test 77 | public void testGetConversion() { 78 | String exchangeId = "exampleId"; 79 | EnumCurrency baseCurrency = EnumCurrency.USD; 80 | Double amount = 100.0; 81 | List rateInfoDtos = Arrays.asList( 82 | new RateInfoDto(EnumCurrency.EUR, 0.85), 83 | new RateInfoDto(EnumCurrency.GBP, 0.72) 84 | ); 85 | ExchangeEntity savedExchange = ExchangeEntity.builder() 86 | .base(baseCurrency) 87 | .amount(amount) 88 | .rates(rateInfoDtos.stream().collect(Collectors.toMap(RateInfoDto::currency, RateInfoDto::rate))) 89 | .build(); 90 | 91 | when(exchangeRepository.findById(eq(exchangeId))).thenReturn(Optional.of(savedExchange)); 92 | 93 | // Call the method 94 | ExchangeDto result = exchangeService.getConversion(exchangeId); 95 | 96 | // Assertions 97 | assertNotNull(result); 98 | assertEquals(savedExchange.getId(), result.getId()); 99 | assertEquals(savedExchange.getBase(), result.getBase()); 100 | assertEquals(savedExchange.getAmount(), result.getAmount()); 101 | assertEquals(savedExchange.getDate(), result.getDate()); 102 | assertEquals(savedExchange.getRates(), result.getRates()); 103 | } 104 | 105 | @Test 106 | public void testGetConversionList() { 107 | LocalDate startDate = LocalDate.of(2023, 1, 1); 108 | LocalDate endDate = LocalDate.of(2023, 12, 31); 109 | 110 | EnumCurrency baseCurrency = EnumCurrency.USD; 111 | Double amount = 100.0; 112 | List rateInfoDtos = Arrays.asList( 113 | new RateInfoDto(EnumCurrency.EUR, 0.85), 114 | new RateInfoDto(EnumCurrency.GBP, 0.72) 115 | ); 116 | ExchangeEntity exchangeEntity = ExchangeEntity.builder() 117 | .base(baseCurrency) 118 | .amount(amount) 119 | .rates(rateInfoDtos.stream().collect(Collectors.toMap(RateInfoDto::currency, RateInfoDto::rate))) 120 | .build(); 121 | 122 | List exchangeEntities = Collections.singletonList(exchangeEntity); 123 | when(exchangeRepository.findByDateBetween(eq(startDate), eq(endDate))).thenReturn(exchangeEntities); 124 | 125 | // Call the method 126 | List result = exchangeService.getConversionList(startDate, endDate); 127 | 128 | // Assertions 129 | assertNotNull(result); 130 | assertEquals(exchangeEntities.size(), result.size()); 131 | } 132 | } -------------------------------------------------------------------------------- /src/main/java/com/exchangeapi/currencyexchange/entity/enums/EnumCurrency.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.entity.enums; 2 | 3 | public enum EnumCurrency { 4 | AED("United Arab Emirates Dirham"), 5 | AFN("Afghan Afghani"), 6 | ALL("Albanian Lek"), 7 | AMD("Armenian Dram"), 8 | ANG("Netherlands Antillean Guilder"), 9 | AOA("Angolan Kwanza"), 10 | ARS("Argentine Peso"), 11 | AUD("Australian Dollar"), 12 | AWG("Aruban Florin"), 13 | AZN("Azerbaijani Manat"), 14 | BAM("Bosnia-Herzegovina Convertible Mark"), 15 | BBD("Barbadian Dollar"), 16 | BDT("Bangladeshi Taka"), 17 | BGN("Bulgarian Lev"), 18 | BHD("Bahraini Dinar"), 19 | BIF("Burundian Franc"), 20 | BMD("Bermudan Dollar"), 21 | BND("Brunei Dollar"), 22 | BOB("Bolivian Boliviano"), 23 | BRL("Brazilian Real"), 24 | BSD("Bahamian Dollar"), 25 | BTC("Bitcoin"), 26 | BTN("Bhutanese Ngultrum"), 27 | BWP("Botswanan Pula"), 28 | BYN("New Belarusian Ruble"), 29 | BYR("Belarusian Ruble"), 30 | BZD("Belize Dollar"), 31 | CAD("Canadian Dollar"), 32 | CDF("Congolese Franc"), 33 | CHF("Swiss Franc"), 34 | CLF("Chilean Unit of Account (UF"), 35 | CLP("Chilean Peso"), 36 | CNY("Chinese Yuan"), 37 | COP("Colombian Peso"), 38 | CRC("Costa Rican Col\\u00f3n"), 39 | CUC("Cuban Convertible Peso"), 40 | CUP("Cuban Peso"), 41 | CVE("Cape Verdean Escudo"), 42 | CZK("Czech Republic Koruna"), 43 | DJF("Djiboutian Franc"), 44 | DKK("Danish Krone"), 45 | DOP("Dominican Peso"), 46 | DZD("Algerian Dinar"), 47 | EGP("Egyptian Pound"), 48 | ERN("Eritrean Nakfa"), 49 | ETB("Ethiopian Birr"), 50 | EUR("Euro"), 51 | FJD("Fijian Dollar"), 52 | FKP("Falkland Islands Pound"), 53 | GBP("British Pound Sterling"), 54 | GEL("Georgian Lari"), 55 | GGP("Guernsey Pound"), 56 | GHS("Ghanaian Cedi"), 57 | GIP("Gibraltar Pound"), 58 | GMD("Gambian Dalasi"), 59 | GNF("Guinean Franc"), 60 | GTQ("Guatemalan Quetzal"), 61 | GYD("Guyanaese Dollar"), 62 | HKD("Hong Kong Dollar"), 63 | HNL("Honduran Lempira"), 64 | HRK("Croatian Kuna"), 65 | HTG("Haitian Gourde"), 66 | HUF("Hungarian Forint"), 67 | IDR("Indonesian Rupiah"), 68 | ILS("Israeli New Sheqel"), 69 | IMP("Manx pound"), 70 | INR("Indian Rupee"), 71 | IQD("Iraqi Dinar"), 72 | IRR("Iranian Rial"), 73 | ISK("Icelandic Kr\\u00f3na"), 74 | JEP("Jersey Pound"), 75 | JMD("Jamaican Dollar"), 76 | JOD("Jordanian Dinar"), 77 | JPY("Japanese Yen"), 78 | KES("Kenyan Shilling"), 79 | KGS("Kyrgystani Som"), 80 | KHR("Cambodian Riel"), 81 | KMF("Comorian Franc"), 82 | KPW("North Korean Won"), 83 | KRW("South Korean Won"), 84 | KWD("Kuwaiti Dinar"), 85 | KYD("Cayman Islands Dollar"), 86 | KZT("Kazakhstani Tenge"), 87 | LAK("Laotian Kip"), 88 | LBP("Lebanese Pound"), 89 | LKR("Sri Lankan Rupee"), 90 | LRD("Liberian Dollar"), 91 | LSL("Lesotho Loti"), 92 | LTL("Lithuanian Litas"), 93 | LVL("Latvian Lats"), 94 | LYD("Libyan Dinar"), 95 | MAD("Moroccan Dirham"), 96 | MDL("Moldovan Leu"), 97 | MGA("Malagasy Ariary"), 98 | MKD("Macedonian Denar"), 99 | MMK("Myanma Kyat"), 100 | MNT("Mongolian Tugrik"), 101 | MOP("Macanese Pataca"), 102 | MRO("Mauritanian Ouguiya"), 103 | MUR("Mauritian Rupee"), 104 | MVR("Maldivian Rufiyaa"), 105 | MWK("Malawian Kwacha"), 106 | MXN("Mexican Peso"), 107 | MYR("Malaysian Ringgit"), 108 | MZN("Mozambican Metical"), 109 | NAD("Namibian Dollar"), 110 | NGN("Nigerian Naira"), 111 | NIO("Nicaraguan C\\u00f3rdoba"), 112 | NOK("Norwegian Krone"), 113 | NPR("Nepalese Rupee"), 114 | NZD("New Zealand Dollar"), 115 | OMR("Omani Rial"), 116 | PAB("Panamanian Balboa"), 117 | PEN("Peruvian Nuevo Sol"), 118 | PGK("Papua New Guinean Kina"), 119 | PHP("Philippine Peso"), 120 | PKR("Pakistani Rupee"), 121 | PLN("Polish Zloty"), 122 | PYG("Paraguayan Guarani"), 123 | QAR("Qatari Rial"), 124 | RON("Romanian Leu"), 125 | RSD("Serbian Dinar"), 126 | RUB("Russian Ruble"), 127 | RWF("Rwandan Franc"), 128 | SAR("Saudi Riyal"), 129 | SBD("Solomon Islands Dollar"), 130 | SCR("Seychellois Rupee"), 131 | SDG("Sudanese Pound"), 132 | SEK("Swedish Krona"), 133 | SGD("Singapore Dollar"), 134 | SHP("Saint Helena Pound"), 135 | SLE("Sierra Leonean Leone"), 136 | SLL("Sierra Leonean Leone"), 137 | SOS("Somali Shilling"), 138 | SRD("Surinamese Dollar"), 139 | STD("S\\u00e3o Tom\\u00e9 and Pr\\u00edncipe Dobra"), 140 | SVC("Salvadoran Col\\u00f3n"), 141 | SYP("Syrian Pound"), 142 | SZL("Swazi Lilangeni"), 143 | THB("Thai Baht"), 144 | TJS("Tajikistani Somoni"), 145 | TMT("Turkmenistani Manat"), 146 | TND("Tunisian Dinar"), 147 | TOP("Tongan Pa\\u02bbanga"), 148 | TRY("Turkish Lira"), 149 | TTD("Trinidad and Tobago Dollar"), 150 | TWD("New Taiwan Dollar"), 151 | TZS("Tanzanian Shilling"), 152 | UAH("Ukrainian Hryvnia"), 153 | UGX("Ugandan Shilling"), 154 | USD("United States Dollar"), 155 | UYU("Uruguayan Peso"), 156 | UZS("Uzbekistan Som"), 157 | VEF("Venezuelan Bol\\u00edvar Fuerte"), 158 | VES("Sovereign Bolivar"), 159 | VND("Vietnamese Dong"), 160 | VUV("Vanuatu Vatu"), 161 | WST("Samoan Tala"), 162 | XAF("CFA Franc BEAC"), 163 | XAG("Silver (troy )ounce"), 164 | XAU("Gold (troy )ounce"), 165 | XCD("East Caribbean Dollar"), 166 | XDR("Special Drawing Rights"), 167 | XOF("CFA Franc BCEAO"), 168 | XPF("CFP Franc"), 169 | YER("Yemeni Rial"), 170 | ZAR("South African Rand"), 171 | ZMK("Zambian Kwacha (pre-2013)"), 172 | ZMW("Zambian Kwacha"), 173 | ZWL("Zimbabwean Dollar"); 174 | 175 | private final String description; 176 | 177 | EnumCurrency(String description) { 178 | this.description = description; 179 | } 180 | 181 | public String getDescription() { 182 | return description; 183 | } 184 | 185 | public EnumCurrency convert(String source) { 186 | return EnumCurrency.valueOf(source.toUpperCase()); 187 | } 188 | } 189 | -------------------------------------------------------------------------------- /src/test/java/com/exchangeapi/currencyexchange/service/RateServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.exchangeapi.currencyexchange.service; 2 | 3 | import com.exchangeapi.currencyexchange.base.BaseServiceTest; 4 | import com.exchangeapi.currencyexchange.dto.RateDto; 5 | import com.exchangeapi.currencyexchange.dto.RateInfoDto; 6 | import com.exchangeapi.currencyexchange.entity.RateEntity; 7 | import com.exchangeapi.currencyexchange.entity.enums.EnumCurrency; 8 | import com.exchangeapi.currencyexchange.payload.response.RateResponse; 9 | import com.exchangeapi.currencyexchange.repository.RateRepository; 10 | import org.junit.jupiter.api.BeforeEach; 11 | import org.junit.jupiter.api.Test; 12 | import org.mockito.InjectMocks; 13 | import org.mockito.Mock; 14 | import org.springframework.beans.factory.annotation.Autowired; 15 | import org.springframework.boot.test.mock.mockito.MockBean; 16 | import org.springframework.http.HttpEntity; 17 | import org.springframework.http.HttpHeaders; 18 | import org.springframework.http.HttpMethod; 19 | import org.springframework.http.ResponseEntity; 20 | import org.springframework.web.client.RestTemplate; 21 | 22 | import java.time.LocalDate; 23 | import java.util.*; 24 | import java.util.stream.Collectors; 25 | 26 | import static org.assertj.core.api.Assertions.assertThat; 27 | import static org.mockito.ArgumentMatchers.anyString; 28 | import static org.mockito.Mockito.*; 29 | 30 | 31 | class RateServiceTest extends BaseServiceTest { 32 | 33 | 34 | @Mock 35 | private RateRepository rateRepository; 36 | 37 | @Mock 38 | private RestTemplate restTemplate; 39 | 40 | @InjectMocks 41 | private RateService rateService; 42 | 43 | 44 | @Test 45 | void whenCalculateRate_butRateRepositoryFoundOne() { 46 | 47 | // Mocked data 48 | EnumCurrency base = EnumCurrency.EUR; 49 | List targets = Arrays.asList(EnumCurrency.USD, EnumCurrency.GBP); 50 | LocalDate date = LocalDate.of(2023, 5, 22); 51 | 52 | // Mocked rate entity 53 | RateEntity mockedRateEntity = new RateEntity(); 54 | mockedRateEntity.setBase(base); 55 | mockedRateEntity.setDate(date); 56 | Map rates = new HashMap<>(); 57 | rates.put(EnumCurrency.USD, 1.2); 58 | rates.put(EnumCurrency.GBP, 0.9); 59 | mockedRateEntity.setRates(rates); 60 | 61 | List rateInfoList = targets.stream() 62 | .map(currency -> new RateInfoDto(currency, rates.get(currency))) 63 | .collect(Collectors.toList()); 64 | 65 | RateDto expected = RateDto.builder() 66 | .id(mockedRateEntity.getId()) 67 | .base(mockedRateEntity.getBase()) 68 | .date(mockedRateEntity.getDate()) 69 | .rates(rateInfoList) 70 | .build(); 71 | 72 | // Mock repository behavior 73 | when(rateRepository.findOneByDate(date)).thenReturn(Optional.of(mockedRateEntity)); 74 | 75 | 76 | // Call the method 77 | RateDto result = rateService.calculateRate(base, targets, date); 78 | 79 | // Verify the result 80 | assertThat(result.getBase()).isEqualTo(expected.getBase()); 81 | assertThat(result.getDate()).isEqualTo(expected.getDate()); 82 | assertThat(result.getRates()).hasSize(2); 83 | assertThat(result.getRates()).containsExactlyInAnyOrder( 84 | new RateInfoDto(EnumCurrency.USD, 1.2), 85 | new RateInfoDto(EnumCurrency.GBP, 0.9) 86 | ); 87 | 88 | // Verify repository method was called 89 | verify(rateRepository, times(1)).findOneByDate(date); 90 | 91 | // The saveRatesFromApi method won't be run because the rateRepository.findOneByDate return the mockedRateEntity 92 | verify(restTemplate, times(0)).exchange( 93 | anyString(), 94 | eq(HttpMethod.GET), 95 | any(HttpEntity.class), 96 | eq(RateResponse.class) 97 | ); 98 | } 99 | 100 | @Test 101 | void whenCalculateRate_andRateRepositoryNotFound() { 102 | // Mocked data 103 | EnumCurrency base = EnumCurrency.EUR; 104 | List targets = Arrays.asList(EnumCurrency.USD, EnumCurrency.GBP); 105 | LocalDate date = LocalDate.of(2023, 5, 22); 106 | 107 | // Mocked rate entity 108 | RateEntity mockedRateEntity = new RateEntity(); 109 | mockedRateEntity.setBase(base); 110 | mockedRateEntity.setDate(date); 111 | Map rates = new HashMap<>(); 112 | rates.put(EnumCurrency.USD, 1.2); 113 | rates.put(EnumCurrency.GBP, 0.9); 114 | mockedRateEntity.setRates(rates); 115 | 116 | List rateInfoList = targets.stream() 117 | .map(currency -> new RateInfoDto(currency, rates.get(currency))) 118 | .collect(Collectors.toList()); 119 | 120 | RateDto expected = RateDto.builder() 121 | .id(mockedRateEntity.getId()) 122 | .base(mockedRateEntity.getBase()) 123 | .date(mockedRateEntity.getDate()) 124 | .rates(rateInfoList) 125 | .build(); 126 | 127 | // Mock API response 128 | RateResponse mockedRateResponse = RateResponse.builder() 129 | .base(base) 130 | .rates(rates) 131 | .date(date) 132 | .build(); 133 | 134 | ResponseEntity mockedResponseEntity = ResponseEntity.ok().body(mockedRateResponse); 135 | 136 | // Mock repository behavior 137 | when(rateRepository.findOneByDate(date)).thenReturn(Optional.empty()); // Return null to simulate repository not finding the entity 138 | 139 | when(restTemplate.exchange( 140 | anyString(), 141 | eq(HttpMethod.GET), 142 | any(HttpEntity.class), 143 | eq(RateResponse.class) 144 | )).thenReturn(mockedResponseEntity); 145 | 146 | // Mock saveRatesFromApi behavior 147 | when(rateRepository.save(any(RateEntity.class))).thenReturn(mockedRateEntity); 148 | 149 | // Call the method 150 | RateDto result = rateService.calculateRate(base, targets, date); 151 | 152 | // Verify the result 153 | assertThat(result.getBase()).isEqualTo(expected.getBase()); 154 | assertThat(result.getDate()).isEqualTo(expected.getDate()); 155 | assertThat(result.getRates()).hasSize(2); 156 | assertThat(result.getRates()).containsExactlyInAnyOrder( 157 | new RateInfoDto(EnumCurrency.USD, 1.2), 158 | new RateInfoDto(EnumCurrency.GBP, 0.9) 159 | ); 160 | 161 | // Verify repository method was called 162 | verify(rateRepository, times(1)).findOneByDate(date); 163 | verify(rateRepository, times(1)).save(any(RateEntity.class)); 164 | 165 | // Verify restTemplate.exchange was called 166 | verify(restTemplate, times(1)).exchange( 167 | anyString(), 168 | eq(HttpMethod.GET), 169 | any(HttpEntity.class), 170 | eq(RateResponse.class) 171 | ); 172 | } 173 | 174 | } -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM https://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* 50 | if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 124 | 125 | FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 127 | ) 128 | 129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 131 | if exist %WRAPPER_JAR% ( 132 | if "%MVNW_VERBOSE%" == "true" ( 133 | echo Found %WRAPPER_JAR% 134 | ) 135 | ) else ( 136 | if not "%MVNW_REPOURL%" == "" ( 137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 138 | ) 139 | if "%MVNW_VERBOSE%" == "true" ( 140 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 141 | echo Downloading from: %DOWNLOAD_URL% 142 | ) 143 | 144 | powershell -Command "&{"^ 145 | "$webclient = new-object System.Net.WebClient;"^ 146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 148 | "}"^ 149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ 150 | "}" 151 | if "%MVNW_VERBOSE%" == "true" ( 152 | echo Finished downloading %WRAPPER_JAR% 153 | ) 154 | ) 155 | @REM End of extension 156 | 157 | @REM Provide a "standardized" way to retrieve the CLI args that will 158 | @REM work with both Windows and non-Windows executions. 159 | set MAVEN_CMD_LINE_ARGS=%* 160 | 161 | %MAVEN_JAVA_EXE% ^ 162 | %JVM_CONFIG_MAVEN_PROPS% ^ 163 | %MAVEN_OPTS% ^ 164 | %MAVEN_DEBUG_OPTS% ^ 165 | -classpath %WRAPPER_JAR% ^ 166 | "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ 167 | %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 168 | if ERRORLEVEL 1 goto error 169 | goto end 170 | 171 | :error 172 | set ERROR_CODE=1 173 | 174 | :end 175 | @endlocal & set ERROR_CODE=%ERROR_CODE% 176 | 177 | if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost 178 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 179 | if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" 180 | if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" 181 | :skipRcPost 182 | 183 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 184 | if "%MAVEN_BATCH_PAUSE%"=="on" pause 185 | 186 | if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% 187 | 188 | cmd /C exit /B %ERROR_CODE% 189 | -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # https://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /usr/local/etc/mavenrc ] ; then 40 | . /usr/local/etc/mavenrc 41 | fi 42 | 43 | if [ -f /etc/mavenrc ] ; then 44 | . /etc/mavenrc 45 | fi 46 | 47 | if [ -f "$HOME/.mavenrc" ] ; then 48 | . "$HOME/.mavenrc" 49 | fi 50 | 51 | fi 52 | 53 | # OS specific support. $var _must_ be set to either true or false. 54 | cygwin=false; 55 | darwin=false; 56 | mingw=false 57 | case "`uname`" in 58 | CYGWIN*) cygwin=true ;; 59 | MINGW*) mingw=true;; 60 | Darwin*) darwin=true 61 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 62 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 63 | if [ -z "$JAVA_HOME" ]; then 64 | if [ -x "/usr/libexec/java_home" ]; then 65 | export JAVA_HOME="`/usr/libexec/java_home`" 66 | else 67 | export JAVA_HOME="/Library/Java/Home" 68 | fi 69 | fi 70 | ;; 71 | esac 72 | 73 | if [ -z "$JAVA_HOME" ] ; then 74 | if [ -r /etc/gentoo-release ] ; then 75 | JAVA_HOME=`java-config --jre-home` 76 | fi 77 | fi 78 | 79 | if [ -z "$M2_HOME" ] ; then 80 | ## resolve links - $0 may be a link to maven's home 81 | PRG="$0" 82 | 83 | # need this for relative symlinks 84 | while [ -h "$PRG" ] ; do 85 | ls=`ls -ld "$PRG"` 86 | link=`expr "$ls" : '.*-> \(.*\)$'` 87 | if expr "$link" : '/.*' > /dev/null; then 88 | PRG="$link" 89 | else 90 | PRG="`dirname "$PRG"`/$link" 91 | fi 92 | done 93 | 94 | saveddir=`pwd` 95 | 96 | M2_HOME=`dirname "$PRG"`/.. 97 | 98 | # make it fully qualified 99 | M2_HOME=`cd "$M2_HOME" && pwd` 100 | 101 | cd "$saveddir" 102 | # echo Using m2 at $M2_HOME 103 | fi 104 | 105 | # For Cygwin, ensure paths are in UNIX format before anything is touched 106 | if $cygwin ; then 107 | [ -n "$M2_HOME" ] && 108 | M2_HOME=`cygpath --unix "$M2_HOME"` 109 | [ -n "$JAVA_HOME" ] && 110 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 111 | [ -n "$CLASSPATH" ] && 112 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 113 | fi 114 | 115 | # For Mingw, ensure paths are in UNIX format before anything is touched 116 | if $mingw ; then 117 | [ -n "$M2_HOME" ] && 118 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 119 | [ -n "$JAVA_HOME" ] && 120 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 121 | fi 122 | 123 | if [ -z "$JAVA_HOME" ]; then 124 | javaExecutable="`which javac`" 125 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 126 | # readlink(1) is not available as standard on Solaris 10. 127 | readLink=`which readlink` 128 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 129 | if $darwin ; then 130 | javaHome="`dirname \"$javaExecutable\"`" 131 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 132 | else 133 | javaExecutable="`readlink -f \"$javaExecutable\"`" 134 | fi 135 | javaHome="`dirname \"$javaExecutable\"`" 136 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 137 | JAVA_HOME="$javaHome" 138 | export JAVA_HOME 139 | fi 140 | fi 141 | fi 142 | 143 | if [ -z "$JAVACMD" ] ; then 144 | if [ -n "$JAVA_HOME" ] ; then 145 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 146 | # IBM's JDK on AIX uses strange locations for the executables 147 | JAVACMD="$JAVA_HOME/jre/sh/java" 148 | else 149 | JAVACMD="$JAVA_HOME/bin/java" 150 | fi 151 | else 152 | JAVACMD="`\\unset -f command; \\command -v java`" 153 | fi 154 | fi 155 | 156 | if [ ! -x "$JAVACMD" ] ; then 157 | echo "Error: JAVA_HOME is not defined correctly." >&2 158 | echo " We cannot execute $JAVACMD" >&2 159 | exit 1 160 | fi 161 | 162 | if [ -z "$JAVA_HOME" ] ; then 163 | echo "Warning: JAVA_HOME environment variable is not set." 164 | fi 165 | 166 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 167 | 168 | # traverses directory structure from process work directory to filesystem root 169 | # first directory with .mvn subdirectory is considered project base directory 170 | find_maven_basedir() { 171 | 172 | if [ -z "$1" ] 173 | then 174 | echo "Path not specified to find_maven_basedir" 175 | return 1 176 | fi 177 | 178 | basedir="$1" 179 | wdir="$1" 180 | while [ "$wdir" != '/' ] ; do 181 | if [ -d "$wdir"/.mvn ] ; then 182 | basedir=$wdir 183 | break 184 | fi 185 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 186 | if [ -d "${wdir}" ]; then 187 | wdir=`cd "$wdir/.."; pwd` 188 | fi 189 | # end of workaround 190 | done 191 | echo "${basedir}" 192 | } 193 | 194 | # concatenates all lines of a file 195 | concat_lines() { 196 | if [ -f "$1" ]; then 197 | echo "$(tr -s '\n' ' ' < "$1")" 198 | fi 199 | } 200 | 201 | BASE_DIR=`find_maven_basedir "$(pwd)"` 202 | if [ -z "$BASE_DIR" ]; then 203 | exit 1; 204 | fi 205 | 206 | ########################################################################################## 207 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 208 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 209 | ########################################################################################## 210 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 211 | if [ "$MVNW_VERBOSE" = true ]; then 212 | echo "Found .mvn/wrapper/maven-wrapper.jar" 213 | fi 214 | else 215 | if [ "$MVNW_VERBOSE" = true ]; then 216 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 217 | fi 218 | if [ -n "$MVNW_REPOURL" ]; then 219 | jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 220 | else 221 | jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 222 | fi 223 | while IFS="=" read key value; do 224 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 225 | esac 226 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 227 | if [ "$MVNW_VERBOSE" = true ]; then 228 | echo "Downloading from: $jarUrl" 229 | fi 230 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 231 | if $cygwin; then 232 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` 233 | fi 234 | 235 | if command -v wget > /dev/null; then 236 | if [ "$MVNW_VERBOSE" = true ]; then 237 | echo "Found wget ... using wget" 238 | fi 239 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 240 | wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" 241 | else 242 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" 243 | fi 244 | elif command -v curl > /dev/null; then 245 | if [ "$MVNW_VERBOSE" = true ]; then 246 | echo "Found curl ... using curl" 247 | fi 248 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 249 | curl -o "$wrapperJarPath" "$jarUrl" -f 250 | else 251 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f 252 | fi 253 | 254 | else 255 | if [ "$MVNW_VERBOSE" = true ]; then 256 | echo "Falling back to using Java to download" 257 | fi 258 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 259 | # For Cygwin, switch paths to Windows format before running javac 260 | if $cygwin; then 261 | javaClass=`cygpath --path --windows "$javaClass"` 262 | fi 263 | if [ -e "$javaClass" ]; then 264 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 265 | if [ "$MVNW_VERBOSE" = true ]; then 266 | echo " - Compiling MavenWrapperDownloader.java ..." 267 | fi 268 | # Compiling the Java class 269 | ("$JAVA_HOME/bin/javac" "$javaClass") 270 | fi 271 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 272 | # Running the downloader 273 | if [ "$MVNW_VERBOSE" = true ]; then 274 | echo " - Running MavenWrapperDownloader.java ..." 275 | fi 276 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 277 | fi 278 | fi 279 | fi 280 | fi 281 | ########################################################################################## 282 | # End of extension 283 | ########################################################################################## 284 | 285 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 286 | if [ "$MVNW_VERBOSE" = true ]; then 287 | echo $MAVEN_PROJECTBASEDIR 288 | fi 289 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 290 | 291 | # For Cygwin, switch paths to Windows format before running java 292 | if $cygwin; then 293 | [ -n "$M2_HOME" ] && 294 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 295 | [ -n "$JAVA_HOME" ] && 296 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 297 | [ -n "$CLASSPATH" ] && 298 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 299 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 300 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 301 | fi 302 | 303 | # Provide a "standardized" way to retrieve the CLI args that will 304 | # work with both Windows and non-Windows executions. 305 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 306 | export MAVEN_CMD_LINE_ARGS 307 | 308 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 309 | 310 | exec "$JAVACMD" \ 311 | $MAVEN_OPTS \ 312 | $MAVEN_DEBUG_OPTS \ 313 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 314 | "-Dmaven.home=${M2_HOME}" \ 315 | "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 316 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 317 | --------------------------------------------------------------------------------