31 Mart 2021 Çarşamba

SpringWebFlux @WebFluxTest Anotasyonu


@WebFluxTest Anotasyonu
Örnek
Şöyle yaparız
@WebFluxTest(controllers = {RateRestController.class})
@Tag("UnitTest")
public class RateRestControllerTest {

  @MockBean
  private RateService rateService;
  
  @Autowired
  WebTestClient webTestClient;
  
  @Test
  public void getLatestRates() throws Exception {

    // Mock return data of rate service
    when(rateService.fetchLatestRates(anyString()))    
    .thenAnswer(invocation -> {
      String baseCurrency = (String) invocation.getArgument(0);
      LocalDateTime timestamp = LocalDateTime.now();
      return Flux.just(
          new Rate(timestamp, baseCurrency, "USD", Math.random()),
          new Rate(timestamp, baseCurrency, "EUR", Math.random()),
          new Rate(timestamp, baseCurrency, "CAD", Math.random()),
          new Rate(timestamp, baseCurrency, "JPY", Math.random())
          );
    });
    
    // trigger API request to rate controller
    webTestClient.get()
    .uri("/rates/latest/GBP")
    .accept(MediaType.APPLICATION_JSON)
    .exchange()
    .expectStatus().isOk()
    .expectBody()
    .jsonPath("$").isArray()
    .jsonPath("$[0].baseCurrency").isEqualTo("GBP")
    .jsonPath("$[0].counterCurrency").isEqualTo("USD")
    .jsonPath("$[0].rate").isNumber()
    .jsonPath("$[1].baseCurrency").isEqualTo("GBP")
    .jsonPath("$[1].counterCurrency").isEqualTo("EUR")
    .jsonPath("$[1].rate").isNumber()
    .jsonPath("$[2].baseCurrency").isEqualTo("GBP")
    .jsonPath("$[2].counterCurrency").isEqualTo("CAD")
    .jsonPath("$[2].rate").isNumber()
    .jsonPath("$[3].baseCurrency").isEqualTo("GBP")
    .jsonPath("$[3].counterCurrency").isEqualTo("JPY")
    .jsonPath("$[3].rate").isNumber();    
  }
}

29 Mart 2021 Pazartesi

SpringContext Internationalization MessageSource Arayüzü

Giriş
Şu satırı dahil ederiz
import org.springframework.context.MessageSource;
Gösterilecek metinleri yükleyen arayüz. Açıklaması şöyle
MessageSource is an interface that defines several methods for resolving messages. The ApplicationContext interface extends this interface so that all application contexts are able to resolve text messages.
Bu arayüzü gerçekleştiren iki tane sınıf var. Bunlar ResourceBundleMessageSource ve ReloadableResourceBundleMessageSource.

Açıklaması şöyle. 
Spring Boot has i18n built-in thanks to the Spring Framework and its MessageSource implementations. There’s a ResourceBundleMessageSource that builds on ResourceBundle, as well as a ReloadableResourceBundleMessageSource that should be self-explanatory.

Inject MessageSource into a Spring bean and call getMessage(key, args, locale) to your heart’s content!

SpringKafka Consumer ConcurrentKafkaListenerContainerFactory.setErrorHandler() metodu

Giriş
Hataları ele almak için seçeneklerimiz şöyle
When you build your spring boot application and make use of Kafka in order to create some consumer, Spring provides on its own a listener container for asynchronous execution of POJO listeners. The provided listener container has three ways to handle a potential exception:

1. Ignores it and moves to the next record.
2. It can retry to process the same item from the listed topics/partitions of that listener.
3. It can send the item to a dead letter topic.
Açıklaması şöyle. Yani eğer bir şey yapmazsak varsayılan davranış hatalar dikkate almamak
By default, records that fail are simply logged, and we move on to the next one. We can, however, configure an error handler in the listener container to perform some other action. 
Retry
Retry için iki seçenek var
1. Kafka Client Kütüphanesini kullanmak. Bu yöntem stateless retry olarak anılıyor.
2. Spring sınıflarını kullanmak. Bu yöntem stateful retry olarak anılıyor.

setErrorHandler metodu - Stateful Retry İçindir
SeekToCurrentErrorHandler kullanılabilir.


setRetryTemplate metodu - Stateless Retry İçindir
Açıklaması şöyle
The Java Kafka client library offers stateless retry, with the Kafka consumer retrying a retryable exception as part of the consumer poll.
- Retries happen within the consumer poll for the batch.
- Consumer poll must complete before poll timeout, containing all retries, and total processing time (including REST calls & DB calls), retry delay and backoff, for all records in the batch.
- Default poll time is 5 minutes for 500 records in the batch. This only averages to 600ms per event.
- If poll time is exceeded this results in event duplication.
- Calculation of retries/time possible, but total retry duration will have to be short.
Örnek
Şöyle yaparız
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.retry.support.RetryTemplate;

//Stateless retry listener.
@Bean
public ConcurrentKafkaListenerContainerFactory<String, String>
  kafkaStatelessRetryListenerContainerFactory(
    ConsumerFactory<String, String> consumerFactory, final RetryTemplate retryTemplate) {

  ConcurrentKafkaListenerContainerFactory<String, String> factory =
    new ConcurrentKafkaListenerContainerFactory();
  factory.setConsumerFactory(consumerFactory);
  factory.setRetryTemplate(retryTemplate);
  factory.setRecoveryCallback((context -> {
    log.warn("**** Retries exhausted - error class: "+context.getLastThrowable() +
             " - error message: "+context.getLastThrowable().getMessage());
      // Return null to mark processing complete.
      return null;
  }));
  return factory;
}

@Bean
public RetryTemplate retryTemplate() {
  return RetryTemplate.builder()
    .fixedBackoff(4000)
    .maxAttempts(5)
    .build();
}

23 Mart 2021 Salı

SpringBoot spring.jpa Hibernate'e Özel Ayarlar - Hibernate Naming Strategies

Giriş
İki tane naming strategy var. Bunlar ImplicitNamingStrategy ve PhysicalNamingStrategy. Eğer nesnemize bir isim vermediysek, ImplicitNamingStrategy devreye girer ve bir isim üretir. Ancak bu isim veri tabanındaki isim değildir. Hibernate tarafından kullanılan mnatıksa bir isimdir. Bu ismi gerçek veri tabanına dönüştüren şey ise PhysicalNamingStrategy.

Yani şeklen şöyle


Hibernate Açısından Arayüzlerin Açıklaması
Açıklaması şöyle
According to the documentation, there are two interfaces responsible for naming your tables, columns etc. in Hibernate: ImplicitNamingStrategy and PhysicalNamingStrategy.
Aslında bunlar arayüz oldukları için gerçekte kullanılan sınıflar ImplicitNamingStrategyJpaCompliantImpl ve PhysicalNamingStrategyStandardImpl.

Bir de ImplicitNamingStrategyLegacyJpaImpl var. Ancak bu JPA 1.0 için kullanılıyordu.

1. ImplicitNamingStrategy 
Açıklaması şöyle. Eğer bir nesneye isim vermezsek bu arayüz devreye girer ve bir isim üretir.
ImplicitNamingStrategy is in charge of naming all objects that were not explicitly named by a developer: e.g. entity name, table name, column name, index, FK etc. The resulting name is called the logical name, it is used internally by Hibernate to identify an object. It is not the name that gets put into the DB.
Örnek
Şöyle yaparız.
spring.jpa.hibernate.naming.physical-strategy=
  org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
Örnek
Şöyle yaparız
spring:
 jpa:
  hibernate:
   naming:
    physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
    implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
2. PhysicalNamingStrategy
Açıklaması şöyle. 
PhysicalNamingStrategy provides the actual physical name used in the DB based on the logical JPA object name. Effectively, this means that using Hibernate you cannot specify database object names directly, but only logical ones.
Bu aslında şu anlama geliyor
Effectively, this means that using Hibernate you cannot specify database object names directly, but only logical ones.

Spring Açısından Arayüzlerin Açıklaması
Ancak Spring, Hibernate tarafından sağlanan arayüzlere kendi sınıflarını takıyor. Açıklaması şöyle.
Spring Boot overrides Hibernate default implementations for both interfaces and uses SpringImplicitNamingStrategy and SpringPhysicalNamingStrategy instead.
1. SpringImplicitNamingStrategy
Açıklaması şöyle.
Effectively, SpringImplicitNamingStrategy copies the behaviour of ImplicitNamingStrategyJpaCompliantImpl with only a minor difference in join table naming. 
...
By default, Spring Boot configures the physical naming strategy with SpringPhysicalNamingStrategy. This implementation provides the same table structure as Hibernate 4: all dots are replaced by underscores and camel casing is replaced by underscores as well. Additionally, by default, all table names are generated in lower case. For example, a TelephoneNumber entity is mapped to the telephone_number table.
...
Basically, it always transforms camelCase and PascalCase to snake_case. In fact, using it isn't possible to work with non_snake_case at all. 
Açıklaması şöyle.
By default, Spring Boot configures the physical naming strategy with SpringPhysicalNamingStrategy. Which does this: For example, a TelephoneNumber entity is mapped to the telephone_number table (same goes for columns).
Burada Spring JPA standardından sapıyor ve isimleri snake_case olarak üretiyor. Açıklaması şöyle
The JPA default table name is the name of the class (minus the package) with the first letter capitalized. 
2. SpringPhysicalNamingStrategy
@Table(name = "PetType") versek bile veri tabanında pet_type isimli tablo oluşur
@Table(name = "\"PetType\"")  versek bile veri tabanında "pet_type" isimli tablo oluşur
Eğer kendi nesnemizi takmak istersek şöyle yaparız.
public class UpperCaseNamingStrategy extends SpringPhysicalNamingStrategy {
  @Override
  protected Identifier getIdentifier(String name, boolean quoted,
JdbcEnvironment jdbcEnvironment) {
    return new Identifier(name.toUpperCase(), quoted);
  }
}
Kullanmak için şöyle yaparız.
spring.jpa.hibernate.naming.physical-strategy=
com.baeldung.namingstrategy.UpperCaseNamingStrategy

10 Mart 2021 Çarşamba

SpringWebFlux Security

Giriş
Şu satırı dahil ederiz
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
Örnek
Şöyle yaparız
@EnableWebFluxSecurity
public class HelloWebFluxSecurityConfig {
  @Bean
  public MapReactiveUserDetailsService userDetailsService() {
    UserDetails user = User.withDefaultPasswordEncoder()
      .username("user")
      .password("user")
      .roles("USER")
      .build();
    return new MapReactiveUserDetailsService(user);
  }
}
Örnek
Şöyle yaparız
@Component
public class AuthenticationManager implements ReactiveAuthenticationManager {

  @Autowired
  private JWTUtil jwtUtil;

  @Override
  public Mono<Authentication> authenticate(Authentication authentication) {

    String authToken = authentication.getCredentials().toString();
    return Mono.just(authToken)
               .map(token -> jwtUtil.validateToken(token))
               .onErrorResume(e -> Mono.empty())
               .flatMap(isValid -> jwtUtil.getAllClaimsFromToken(authToken))
               .map(claims -> new UsernamePasswordAuthenticationToken(
                 claims.getSubject(), 
                 null, 
                 Collections.singletonList(new SimpleGrantedAuthority(
                   claims.get(KEY_ROLE).toString()))));
    }
}


4 Mart 2021 Perşembe

SpringCache Kullanımı

Giriş
Kısaca 
1. @EnableCaching ile cache etkinleştirilir
2. Bir CacheManager Arayüzü tanımlanır
3. @Cacheable select, find metodları için kullanılır
4. @CachePut update metodları için kullanılır
5. @CacheEvict delete metodları için kullanılır
6. @Caching metod üzerinde birden fazla aynı cache anotasyonunu kullanmak birden fazla defa kullanmak istiyorsak bunları birleştirmek için kullanılır. Çünkü Java aynı anotasyonunu iki defa eklenmesine izin vermez. Örneğin bir metod çağrısında iki farklı cahce'ten bir şey silmek istiyorsak işe yarar
7. @CacheConfig sınıf üzerine yazılır. Sınıfta kullanılan tüm cache anotasyonlarına ortak özellikler verir

Bir başka açıklama şöyle
@Cacheable : Triggers cache population
@CachePut : Updates the cache, without interfering with the method execution
@CacheEvict : Triggers cache eviction[removing items from cache]
@Caching : Regroups multiple cache operations to be applied on a method
@CacheConfig : Shares some common cache-related settings at class-level
@EnableCaching : Configuration level annotation, enables Caching
Desteklenen Cache Sağlayıcıları
Açıklaması şöyle
The following are the cache provider supported by Spring Boot framework :

1. JCache (JSR-107)
2. EhCache
3. Hazelcast
4. Infinispan
5. Couchbase
6. Redis
7. Caffeine
8. Simple


SpringCache Redis Kullanımı

Giriş
Açıklaması şöyle
The RedisCacheManager is automatically configured when we configure Redis. The default configuration is set by using property spring.cache.redis.*.

Maven
Şu satırı dahil ederiz
dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
  <groupId>redis.clients</groupId>
  <artifactId>jedis</artifactId>
</dependency>
Gradle
Şu satırı dahil ederiz
dependencies {
 ...
 implementation 'org.springframework.boot:spring-boot-starter-cache'
 implementation 'org.springframework.boot:spring-boot-starter-data-redis'
 ...
}

application.properties Ayarları