11 Nisan 2020 Cumartesi

SpringWebFlux Mono Sınıfı

Giriş
Şu satırı dahil ederiz
import reactor.core.publisher.Mono;
Bu sınıf aslında Spring'e ait değil. Project Reactor'a ait. Soyut bir sınıf. [0-1) arası nesne üretir. Project Reactor Java 8+ ile kullanılır. Açıklaması şöyle.
Reactor on the other hand is Java 8+ only, so it can make full use of the new Java 8 native classes. Since Spring 5.0 is also Java 8+ only, that means Reactor has the edge in this regard.
Bu Sınıf Niçin Lazım ?
Açıklaması şöyle. Reactive Stream tiplerinin yetersiz kaldığı düşünülerek tasarlanmış. Reactive Stream'deki Publisher arayüzünü gerçekleştirir.
The Reactive Streams types are not enough; you’ll need higher order implementations to support operations like filtering and transformation. The Reactor project is a good choice here; it builds on top of the Reactive Streams specification. It provides two specializations of  Publisher<T>.

The first, Flux<T>, is a Publisher that produces zero or more values. It’s unbounded. The second, Mono<T>, is a Publisher<T> that produces zero or one value. They’re both publishers and you can treat them that way, but they go much further than the Reactive Streams specification. They both provide operators, ways to process a stream of values. Reactor types compose nicely - the output of one thing can be the input to another and if a type needs to work with other streams of data, they rely upon Publisher<T> instances.

Both Mono<T> and Flux<T> implement Publisher<T>; our recommendation is that your methods accept Publisher<T> instances but return Flux<T> or Mono<T> to help the client distinguish the kind of data its being given.
block metodu
Açıklaması şöyle
to retrieve object from mono you have to block
Örnek
Şöyle yaparız.
Mono.just(new Employee().setName("Kill"))
    .switchIfEmpty(Mono.defer(() -> Mono.just(new Employee("Bill"))))
    .block()
    .getName();
doOnError metodu - Consumer
Şöyle yaparız.
Mono<AuthorizeResponse> result = ...
response = result.doOnError(e -> {throw new RuntimeException(e);})
                 .block();
error metodu
Şöyle yaparız
@Transactional
public Mono<Store> addStore(Store store) {
  if (store.isValid()) {
    final Mono<Store> result = storePort.addStore(store);
    return result;
  }
  return Mono.error(InvalidAttributesException::new);
}
flatMap metodu
Mono.flatMap metodu yazısına taşıdım

flatMapMany metodu
Mono nesnesini Flux nesnesine çevirir. Yani 1 nesneyi OneToMany haline getirir.

fromCallable metodu
Mono.fromCallable metodu yazısına taşıdım

fromRunnable metodu
Örnek
Şöyle yaparız
Mono.fromRunnable(() -> System.out.println("Hello"))
        .subscribe(
                i -> System.out.println("Received :: " + i),
                err -> System.out.println("Error :: " + err),
                () -> System.out.println("Successfully completed"));

//Output
Hello
Successfully completed
fromSupplier metodu
Şöyle yaparız. Supplier verilen veriyi işler ve bir sonuç döner. Bu döndürülen Mono nesnesinin sonucunu almak için ya block() metodu ya da subscribe() metodu çağrılır.
public Mono<Integer> nonBlockingSum(Integer arr[])
  throws InterruptedException {

  Mono<Integer> m = Mono.fromSupplier(() ->this.computationService.getSum(arr))
                        .subscribeOn(this.scheduler);
  return m;
}
justmetodu
Mono.just metodu yazısına taşıdım

justOrEmpty metodu
Örnek
Şöyle yaparız
Mono<String> publisher = Mono.justOrEmpy("My first publisher");
onErrorResume metodu
Mono.onErrorResume metodu yazısına taşıdım

then metodu
Mono.then metodu yazısına taşıdım

thenReturn metodu
Mono.thenReturn metodu yazısına taşıdım

switchIfEmpty metodu
Mono.switchIfEmpty metodu yazısına taşıdım














7 Nisan 2020 Salı

SpringSecurity @PostAuthorize Anotasyonu - MethodSecurity Kavramı

Giriş
Metoda bittikten sonra çalışır. Açıklaması şöyle.
The @PostAuthorize as name suggest checks for authorization after method execution. The @PostAuthorize authorizes on the basis of logged in roles, return object by method and passed argument to the method. For the returned object spring security provides built-in keyword i.e. returnObject.
Bu anotasyonun kardeşi @PreAuthorize.

SpringSecurity PermissionEvaluator Arayüzü

Giriş
Bu arayüzün sadece hasPermission metodu var.

hasPermission metodu
İmzaları şöyle.
public boolean hasPermission(Authentication authentication , Object targetDomainObject,
  Object permission)

public boolean hasPermission(Authentication authentication, Serializable targetId,
  String targetType, Object permission)

SpringContext @Value Anotasyonu - Tek Bir Değişkeni Okuma

Giriş
Açıklaması şöyle. application.properties, ortam değişkeni, JVM parametresi gibi bir değeri değişkene atayabilmeyi sağlar.
@Value annotation is used to assign a value to a property. It is only used to assign a value for a simple type property,for example, primitive types, in a bean class.in this way, IOC container reads the value of a key from resource bundle and initializes a simple property with that value.
Bu Anotasyon Constructor Parametresi veya Metod Parametresi veya Üye Alan Üzerinde Kullanılabilir
Açıklaması şöyle.
This annotation is used at the field, constructor parameter, and method parameter levels. The @Value  annotation indicates a default value expression for the field or parameter to initialize the property with. As the @Autowired annotation tells Spring to inject an object into another when it loads your application context, you can also use the @Value annotation to inject values from a property file into a bean’s attribute. It supports both #{...} and ${...} placeholders.
@ConfigurationProperties İle Farkı
Açıklaması şöyle. Tek bir değişken yerine bir sınıfı POJO tüm olarak okumak istersek @ConfigurationProperties anotasyonu kullanılır.
Your two main choices for injecting configuration are using either @Value on individual properties or @ConfigurationProperties on a javabean configuration object.

Which one you use comes down to preference. Personally I prefer using a configuration object.

Using @ConfigurationProperties allows you to use JSR-303 bean validation.
You can also write your own custom validation in the setter of your javabean if you desire.
You can annotate config beans from non-spring projects, which allows you to write libraries that are easily configured but don’t depend on spring.
You can generate IDE meta-data from the objects that may make your development process smoother.
Kullanılan String
Eğer sadece application.properties'teki bir değeri çekmek istersek şöyle yaparız. Dolar karakteri ve süslü parantezler içine değişken ismini yazmak gerekir.
@Value("${...}")
Static Üye Alan
@Value static üye alan ile çalışmıyor. Şu kod işe yaramaz. Çözümü ise static üye alan için setter() metod yazmak.
@Value("${tenantdb.driver.classname}")
static String tenantDbDriverClassname;
Varsayılan (Default) Değer
@Value Anotasyonu Varsayılan (Default) Değer Okuma yazısına taşıdım

Dolar Kareteri ve Hash Karakteri
Bu anotasyon "${...}" veya "#{...}" şeklinde kullanılabiliyor. Açıklaması şöyle.
${...} is the property placeholder syntax. It can only be used to dereference properties.

#{...} is SpEL syntax, which is far more capable and complex. It can also handle property placeholders, and a lot more besides.

Both are valid, and neither is deprecated.
SpEL için @Value Anotasyonu - Conditional Değer Okuma yazısına bakabilirsiniz

1. application.properties Dosyası Örnekleri
application.properties dosyasındaki değerin otomatik olarak değişkene atanmasını sağlar.

@Value Anotasyonu - Array Okuma yazısına taşıdım
@Value Anotasyonu - List Okuma yazısına taşıdım
@Value Anotasyonu - Map Okuma yazısına taşıdım

Örnek - Boolean Okuma
Şöyle yaparız.
@Value("${app.settings.value1:false}")
private boolean value1;
Örnek - Integer Okuma
application.properties şöyle olsun
my.prop.for.func=25
Değeri String değil ama Integer olarak okumak için şöyle yaparız.
@Value("${my.prop.for.func}")
private Integer myPropForFunc; // Needs to be an object and not a primitive data type.

Örnek - String Okuma
Dosya şöyle olsun.
profile.name=myname
Şöyle yaparız.
@Component    
public class SampleClass() implements Runnable{
  @Value("${profile.name}")
  private String name;
  ...
}
Varsayılan değer atamak istersek şöyle yaparız.
@Value("${profile.name:'samplename'}")
Örnek - String Okuma
Şöyle yaparız.
@Value("#{mysql.databaseName}")
private String databaseName;

2. yml Dosyası Örnekleri
Örnek
yml dosyası şöyle olsun.
spring:
  url: localhost
email:
  from: something@gmail.com
app:
  uuid: 3848348j34jk2dne9
Şöyle yaparız. Burada nesnenin constructor metoduna parametreler geçiliyor.
@Component
public class FooA {
  private final String url;

  public FooA(@Value("${spring.url}") String url) {
    this.url = url
  }
}

@Component
public class FooB {
  private final String from;

  public FooA(@Value("${email.from}") String from) {
    this.from = from
  }
}

@Component
public class FooC {
  private final String uuid;

  public FooA(@Value("${app.uuid}") String uuid) {
    this.uuid = uuid
  }
}
3. JVM Parametreleri Örnekleri
SpEL kullanılıyor.
 
4. Shell Parametreleri Örnekleri
Linux'ta export=abs şeklindeki kabuk parametrelerini okumak için kullanılır.

Örnek
Şöyle yaparız.
@Value("#{systemEnvironment['COMPONENT_PARAM_CORS']}")
private String COMPONENT_PARAM_CORS;