23 Ağustos 2021 Pazartesi

WatchEvent Arayüzü - NIO

Giriş
Şu satırı dahil ederiz.
import java.nio.file.WatchEvent;
context metodu
Şöyle yaparız
WatchKey key = ...;
for (final WatchEvent<?> event : key.pollEvents()) {
  final Path changed = monitoringDirectory.resolve((Path) event.context());

  if (event.kind() == ENTRY_MODIFY && changed.equals(file)) {
    ...
  }

20 Ağustos 2021 Cuma

Kotlin run function

Giriş
Açıklaması şöyle
Kotlin has made our life very easy by providing features like extension functions, nullability check and much more. One such kind of really helpful feature is Scope functions. Once you understand what scope functions are, you will not able to resist yourself from using them.

Scope functions are nothing but the functions which define to the scope of the calling object. We can apply operations on that object within that scope and return the object itself from that scope function or we can even return the result of operation or operations from the scope function.
There are a few scope functions
- let
- with
- run
- apply
- also
run metodu
run() metodunun iki tane hali var. Açıklaması şöyle
run has two variants, one is an extension function to Template class and another one is not an extension function to Template class.
Extension Function
Örnek
Şöyle yaparız
class Employee {
    var firstName: String? = null
    var age: Int = 0
}

val employee: Employee? = Employee()
employee?.firstName = "Suneet"
employee?.age = 27

employee?.run {
    println(age)
}
Not Extension Function
Örnek
Şöyle yaparız
val alphaNumeric = run {
val digits = "0-9" val aplhabets = "A-Za-z" Regex("[$digits$aplhabets]+") } for (match in alphaNumeric.findAll("+1234 -FFFF I-am?-a!string?!")) { println(match.value) } //this will print 1234 FFFF I am a string


19 Ağustos 2021 Perşembe

Micronaut Http Client

Giriş
Açıklaması şöyle
Micronaut provides two ways of creating HTTP clients:

- A declarative HTTP Client
- A programmatic HTTP Client
Örnek
Şöyle yaparız
@Validated
public interface PetOperations {
    @Post
    Single<Pet> save(@NotBlank String name, @Min(1L) int age);
}

@Client("/pets") 
public interface PetClient extends PetOperations { 

    @Override
    Single<Pet> save(String name, int age); 
}

PetClient client = applicationContext.getBean(PetOperations.class);
Single<Pet> pet = client.save("Hoppie", 1));

17 Ağustos 2021 Salı

String.format metodu

Giriş
İmzası şöyle
public static String format(String format, Object... args) 
public static String format(Locale l, String format, Object... args) {
Söz dizimi şöyle. Her zaman % format specifier ile başlar
%<index$><flags><width><.precision><conversion>
Locale Kullanımı
Örnek
Şöyle yaparız
String name = "Tandrew";
int age = 16;

String formattedString = String.format(Locale.US, "My name is %s and I am %d years old",
  name, age);

// notice the format specifiers %s and %d
System.out.println(formattedString); 

// Output: My name is Tandrew and I am 16 years old
1. Index
Açıklaması şöyle
<index$> is an optional positive integer that corresponds to an argument in the argument list. This index starts at 1 (i.e., the first argument in the argument list is indexed as 1). Therefore, the first argument in the argument list can be addressed using 1$, the second argument can be addressed using 2$, and so on. For example, we can format a String — which has a conversion of s— that corresponds to the second argument in our argument list using the following format specifier:
Örnek
Şöyle yaparız
String.format("The hex value of %d is 0x%1$h",8756);//"The hex value of 8756 is 0x2234"
2. Flags
Flags şöyle
-            Left-justifies the results.
#           Uses an alternative form.
+           Always includes a sign.
(space) Add leading space for positive values.
0           Zero-pads the result.
,            Includes locale-specific grouping separators.
(            Encloses negative numbers in parenthesis.

3. Width
Örnek
Şöyle yaparız
Birinci örnekte % formatlamaya başlama karakteridir, 10 width içindir gerekirse sağa doğru doldurulur, s ise parametrenin string olarak formatlanacağını belirtir
İkinci örnekte % formatlamaya başlama karakteridir, -10 width içindir ve gerekirse sola doğru doldurulur, s ise parametrenin string olarak formatlanacağını belirtir
String formattedString1 = String.format("%10s", "name");    // Result: "name      "
String formattedString2 = String.format("%-10s", "name");   // Result: "      name"
Örnek
Şöyle yaparız.
0 baş tarafı doldurma karakteridir, 32 width içindir,  x ise parametrenin hexadecimal olarak formatlanacağını belirtir
BigInteger n = ...;
String md5h = String.format("%032x",n);
4. Precision
Açıklaması şöyle
General: 
Maximum number of characters displayed; if the supplied argument results in more characters than the supplied precision, the resulting string is truncated to the correct number of characters. For example, supplying Justin as an argument to the format specifier %.1s result in J.

Floating point (e, E, and f): 
Number of digits after the decimal place. For example, a format specifier of %.1f with an argument of 1.2345 results in 1.2.

Floating point (g, G, a and A): 
Number of digits in the magnitude after rounding.
5. Conversion Tablosu
Conversion Tablosu şöyle
%b, B : true, false, TRUE, FALSE
%h, H : fff03,6199ec4,6199EC4
%s, S : foo ,bar, BAR
%c, C : c, f ,F
%d :     10,5347
%o :      2,151
%x, X :  ff4,e56d2,E56D2
%e, E :  1.114313e+09,1.682340e-08,1.682340E-08
%f :       4.562340, 1245.643876
%g, G : 128636, 8.12935e+16,3546.50,8.12935E+16
%a, A :  0x1.63c774a3d70a4p19, 0x1.187ff0337c5abp-26, 0X1.8D7025536252DP45

Boolean %b veya %B
Açıklaması şöyle
The boolean result as a string (e.g., true or false) if the supplied argument is a Boolean. false if the supplied argument is null and true for all other arguments. If B is used, the resulting boolean value is capitalized (e.g., TRUE or FALSE).
Hexadecimal String -%h veya %h
Açıklaması şöyle. fff03, 6199ec4, 6199EC4 gibi
The hexadecimal value of the supplied argument, arg, by applying the expression Integer.toHexString(arg.hashCode()). Note that the result does not include a 0x prefix. If H is used, the resulting alphabetic hexadecimal characters are capitalized.
String - %s
Açıklaması şöyle
The provided argument as a string (by invoking Object.toString). If the supplied argument is a Formattable object, the string is obtained by invoking Formattable.formatTo. If S is supplied, the supplied string is capitalized.
Şöyle yaparız.
int a = ...;
int b = ...;
int c = ...;
return String.format("%s-%s-%s", a, b, c);
Character %c veya %C
Açıklaması şöyle
The Unicode character. If a String object is supplied, an IllegalFormatConversionException is thrown. If C is used, the supplied character is capitalized.
Integer -%d
Açıklaması şöyle
The decimal integer.
Şöyle yaparız.
String.format("%011d", 4366)
Çıktı olarak şunu alırız
00000004366
Octal Integer -%o
Açıklaması şöyle. 12, 151 gibi
The octal integer.
hexadecimal Integer - %x veya %X
Açıklaması şöyle. ff4, e56d2, E56D2 gibi
The hexadecimal integer. Note that the result does not include a 0x prefix. This specifier should be preferred over h when supplying an integer. If X is used, the resulting alphabetic hexadecimal characters are capitalized.
Şöyle yaparız.
int a = ...;
System.out.println( String.format("%X", a) );
Floating Point - %e veya %E
Açıklaması şöyle. 1.114313e+09, 1.682340e-08, 1.682340E-08 gibi
The value in scientific notation. If E is used, the exponent symbol (e) is capitalized (i.e., E).
Floating Point - %f
Açıklaması şöyle.
Use %.4f to perform the rounding you want. This format specifier indicates a floating point value with 4 digits after the decimal place. Half-up rounding is used for this, meaning that if the last digit to be considered is greater than or equal to five, it will round up and any other cases will result in rounding down.
Örnek
Şöyle yaparız.
String.format("%.2f", 62.1232131342);
Floating Point In Scientific Notation Or Decimal Format- %g
Açıklaması şöyle. 128636, 8.12935e+16, 3546.50, 8.12935E+16 gibi
The value in scientific notation or decimal format, depending on the result after rounding. If G is used, the exponent symbol (e) is capitalized (i.e., E).
Açıklaması şöyle.
The %g format specifier is used to indicate how many significant digits in scientific notation are displayed. Leading zeroes are not significant, so they are skipped.
Örnek
Şöyle yaparız. Çıktı olarak 0.1235 alırız
String.format("%.4g", 0.1234712)
Örnek
Şöyle yaparızz. Çıktı olarak 0,0009877 alırız
String.format("%.4g", 0.000987654321)
Floating Point In Scientific Notation - %a veya %A
Açıklaması şöyle.  0x1.63c774a3d70a4p19, 0x1.187ff0337c5abp-26, 0X1.8D7025536252DP45 gibi
The value in scientific notation, where the significand is a hexadecimal floating point value, and the power follows a p delimiter. If A is used, the resulting alphabetic hexadecimal characters are capitalized and the p delimiter is capitalized (i.e., P).

15 Ağustos 2021 Pazar

maven Transitive Dependencies

Giriş
Farklı modüllerden bir kütüphanenin farklı sürümleri transitive dependency olarak geliyor olabilir. 
Bu durumda kök (root) düğüme en yakın olan kullanılır.

Örnek
Elimizde şöyle bir ağaç olsun
  A
  ├── B
  │   └── C
  │       └── D 2.0
  └── E
      └── D 1.0

Bu durumda D1.0 tercih edilir. Maven mesaj olarak "omitted for conflict with .." şeklinde bir mesaj verir.

Eğer D2.0 ı kullanmayı mecbur yapmak istersek, D bağımlılığı elle eklenir. Bu durumda pom.xml şöyle olur
 A
  ├── B
  │   └── C
  │       └── D 2.0
  ├── E
  │   └── D 1.0
  │
  └── D 2.0      


Quarkus

Quarkus'u Kim Geliştiriyor
Açıklaması şöyle. 2018 yılında geliştirilmeye başladı.
Quarkus, on the other hand, is developed and backed by RedHat, Inc., which is a well-known company in the programming world.
Quarkus Altta Ne Kullanır
Açıklaması şöyle
Quarkus depends heavily on the Vert.x toolkit and MicroProfile project. The Eclipse Foundation maintains both. 
Quarkus ve LiveRoad
Kodda değişikli olunca JVM'in tekrar başlaması gerekmez.

Quarkus ve Spring
Quarkus ile Spring kodlarını kullanma imkanı var. Compatibility extensions menüsünden "Spring DI" ve "Spring Web API" seçilebilir.

Quarkus Messaging implementation
Kafka, AMQP, JMS destekler.

Proje Oluşturma
https://code.quarkus.io/ adresinden aynı Spring gibi proje oluşturulabilir. Proje yapısı şöyle
README.md
pom.xml
build.gradle

src/main/docker
src/main/java
src/main/resources

src/main/resources/application.properties
src/main/resources/application.yml
src/main/resources/application.yaml

src/main/resources/META-INF/resources
src/test/java
Dev Mode and Live Coding
Şöyle yaparız
./mvnw quarkus:dev
./gradlew quarkusDev
Kubernetes Development
Burada detaylı açıklama var

Native Image
Şöyle yaparız
./mvnw package -Pnative
./gradlew build -Dquarkus.package.type=native
SmallRye
Açıklaması şöyle
... Quarkus uses SmallRye reactive library

Örnek
Şöyle yaparız
@Path("/application-info")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
class ApplicationInfoResource(
@Inject private val applicationInfoService: ApplicationInfoService) {
  @GET
  fun get(@QueryParam("request-to") requestTo: String?): Response =
    Response.ok(applicationInfoService.get(requestTo)).build()
  
  @GET
  @Path("/logo")
  @Produces("image/png")
  fun logo(): Response
    Response.ok(applicationInfoService.getLogo()).build()
}
DataSource
Şöyle yaparız
quarkus:
  datasource:
    customers:
      db-kind: h2
      jdbc: false
      reactive:
        url: h2:file:~/testdb
        max-size: 20

ActiveMQ Kullanımı

Giriş
Not : ActiveMQ API yazısına da bakabilirsiniz

ActiveMQ indirilip ve unzip edilir. Daha sonra bin dizininde şöyle yaparız
activeMQ start 
Login
Login için şu adrese gideriz. Kullanıcı adı ve şifre 'admin'
http://localhost:8161/admin/
Menülerde Queue ve Topic linklerini kullanarak kuyruklara bakılabilir.
Topics
Şeklen şöyle

Subscribers
Şeklen şöyle


Artemis
Artemis aslında eski HornetQ. Açıklaması şöyle
In spite of HornetQ's incredible speed, however, it failed to surpass its biggest competitor. Near the end of 2014, the codebase for HornetQ was donated to the Apache ActiveMQ community. Today, it exists as an Active MQ subproject called Artemis.