30 Haziran 2022 Perşembe

Jakarta EE Concurrency @ManagedExecutorDefinition

Giriş
Açıklaması şöyle
One of the most commonly used services in the Jakarta Concurrency API is the ManagedExecutorService. It is used to create a thread pool in the Jakarta EE environment to spawn threads in a more manageable way. Although it is pretty much the same as ExecutorService, we employ it in the Java SE environment.

To configure the thread pool, we had a vendor-specific setting. Now it can be defined with just annotation. This is a more standard way of configuring the thread pool.
Örnek
Şöyle yaparız
@Path("concurrency")
@RequestScoped public class GenericResource { @Context private UriInfo context; @Resource private ManagedExecutorService managedExecutor; @GET @Path("simplejob") @Produces(MediaType.TEXT_PLAIN) public String getText() { manageExecutor.submit(() -> { System.out.println("Job running..."); }); return "Job Sumitted"; } }
Örnek
Şöyle yaparız
import static jakarta.enterprise.concurrent.ContextServiceDefinition.APPLICATION;
import static jakarta.enterprise.concurrent.ContextServiceDefinition.SECURITY;

import jakarta.annotation.Resource;
import jakarta.ejb.Asynchronous;

import jakarta.enterprise.concurrent.ContextServiceDefinition;
import jakarta.enterprise.concurrent.ManagedExecutorDefinition;
import jakarta.enterprise.concurrent.ManagedExecutorService;

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Named;
import java.time.Duration;
import java.time.LocalDate;
import java.util.concurrent.CompletableFuture;

@Named
@ApplicationScoped
@ManagedExecutorDefinition(
    name = "java:module/concurrent/MyExecutor",
    context = "java:module/concurrent/MyExecutorContext",
    hungTaskThreshold = 120000,
    maxAsync = 5)
@ContextServiceDefinition(
    name = "java:module/concurrent/MyExecutorContext",
    propagated = {SECURITY, APPLICATION})
public class WorkService {
  
  @Resource(name = "java:app/concurrent/MyExecutorService")
  private ManagedExecutorService executor;

  @Asynchronous
  public CompletableFuture<Long> hoursWorked(LocalDate from, LocalDate to) {

    return CompletableFuture.supplyAsync(() -> heavyAPICall(from, to), executor);
  }

  private static long heavyAPICall(LocalDate from, LocalDate to) {

    return Duration.between(from, to).toMillis();
  }
}

Jakarta EE Concurrency @Asynchronous Anotasyonu

Giriş
Açıklaması şöyle
There is a similar annotation available in EJB. A method annotated with this annotation is supposed to run asynchronously. Unfortunately, however, the EJB one is a bit out of date.

Also, in EJB, we can't specify the thread pool. It used to use the app server's default thread pool. Now the new annotation jakarta.enterprise.concurrent.Asynchronous comes with Jakarta EE Concurrency 3.0, which doesn't require using EJB, and we can specify the thread pool. It can be used with any CDI bean. Each asynchronous method execution corresponds to a managed java.util.concurrent.CompletableFuture instance that is backed by jakarta.enterprise.concurrent.ManagedExecutorService as its default asynchronous execution facility.
executor Alanı
Örnek
Şöyle yaparız
import jakarta.enterprise.concurrent.Asynchronous;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Named;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;

@Named
@ApplicationScoped
public class PaymentService {

  @Asynchronous(executor = "java:app/concurrent/MyExecutorService")
  public CompletableFuture<Confirmation> processPayment(final Order order) {
    try {
      var status = processOrder(order);
      return CompletableFuture.completedFuture(status);
    } catch (PaymentException ex) {
      throw new CompletionException(ex);
    }
  }

  private Confirmation processOrder(Order order) {
    return new Confirmation();
  }
}

Jakarta EE @OpenIdAuthenticationDefinition Anotasyonu

Giriş
Açıklaması şöyle
Well, for many years, we have been using usernames and passwords for authenticating users in a web application. However, in modern applications, it has become widespread to log in using other services, e.g. Facebook, Google, Twitter, etc. The OpenID Connect protocol powers this kind of authentication. With the Jakarta Security 3.0, we now have a standard way to adhere to OpenID Connect by using just an annotation, which is @ OpenIdAuthenticationDefinition. Life is much simpler now; specify the required properties, such as Provider URI, clientId, clientSecret, redirect URI, etc.
Örnek
Şöyle yaparız
@OpenIdAuthenticationDefinition(
       providerURI = "https://sample-openid-server.com",
       clientId = "87068hgfg5675htfv6mrucov57bknst.apps.sample.com",
       clientSecret = "{my-secret}",
       redirectURI = "${baseURL}/callback",
       extraParameters = {
            "testKey=testValue", 
            "testKey2=testValue2"
       }
)

public class SecurityConfig {
}

20 Haziran 2022 Pazartesi

jboss-cli komutu

shutdown
Aynı şey Yönetim Ekranından (Management Console) da yapılabilir.

Örnek
Şöyle yaparız
jboss-cli.sh -- connect
[standalone@localhost:9990 /] shutdown
Örnek
Şöyle yaparız
jboss-cli.sh -- connect
[standalone@localhost:9990 /] shutdown --timeout=10
Örnek - restart
Şöyle yaparız
jboss-cli.sh -- connect
[standalone@localhost:9990 /] shutdown --restart=true 
HAL Management Console'dan şöyle yaparız
When running in Standalone mode, select the Runtime upper Tab and, from your Server name, click on the Combo Menu’s arrow. You should be able to Reload, Restart or Suspend the Server from there:
Şeklen şöyle



9 Haziran 2022 Perşembe

Jakarta NoSQL

Giriş
İki tane standart var
1. Jakarta NoSQL Standardı
2. Jakarta Data Standardı

Jakarta NoSQL Standardı
Açıklaması şöyle. Yani NoSQL veri tabanları ile çalışmak için
We have JPA for a while in the specification world to make your life easier in the relational database world. We're glad to work on a specification to make it easier to work with NoSQL: Jakarta NoSQL.

The core principle of the Jakarta NoSQL is to standardize behavior, to make a low cognitive load while changing among databases, and at the same time be extensible enough to allow specific behavior from a particular vendor. At this time we have the pleasure of announcing a new version, Jakarta NoSQL Version 1.0.0-b4.
Jakarta Data Standardı
Açıklaması şöyle
After several discussions to have more integration between JPA and NoSQL, the community has decided to create a new specification to apply those patterns around data: Jakarta Data. We've published it to the Jakarta EE Committee.
Jakarta NoSQL Kullanımı
Builder veya Fluent şekilde kullanılabilir. Açıklaması şöyle
... Jakarta NoSQL has two approaches to creating a database request: using a fluent API and using a builder pattern.
Maven
Şu satırı dahil ederiz
<dependency>
<groupId>org.eclipse.jnosql.mapping</groupId>
<artifactId>mongodb-extension</artifactId>
<version>${project.version}</version>
</dependency>
DocumentCollectionManager Sınıfı
Örnek
Şöyle yaparız
@ApplicationScoped
public class MongoDBProducer {

  @Inject
  @ConfigProperty(name = "document")
  private DocumentCollectionManager manager;

  @Produces
  public MongoDBDocumentCollectionManager getManager() {
    return (MongoDBDocumentCollectionManager) manager;
  }

  public void destroy(@Disposes DocumentCollectionManager manager) {
    manager.close();
  }
}
properties dosyası şöyledir
document=document
document.database=olympus
document.settings.jakarta.nosql.host=localhost:27017
document.provider=org.eclipse.jnosql.communication.mongodb.document.MongoDBDocumentConfiguration
DocumentTemplate Sınfı
delete metodu
Örnek
Şöyle yaparız
try (SeContainer container = SeContainerInitializer.newInstance().initialize()) {

  Worker poliana = Worker.builder()
    .age(30).name("Poliana")
    .city("Salvador")
    .gender(Gender.FEMALE)
    .dailyHours(30).build();

  Worker otavio = Worker.builder()
    .age(35).name("Otavio")
    .city("Salvador")
    .gender(Gender.MALE)
    .dailyHours(30).build();

  DocumentTemplate template = container.select(DocumentTemplate.class).get();

  template.insert(Arrays.asList(otavio, poliana));
  ...
  template.delete(Worker.class, otavio.getId());
  template.delete(Worker.class, poliana.getId());
}
insert metodu
Örnek
Şöyle yaparız
try (SeContainer container = SeContainerInitializer.newInstance().initialize()) {

  Worker poliana = Worker.builder()
    .age(30).name("Poliana")
    .city("Salvador")
    .gender(Gender.FEMALE)
    .dailyHours(30).build();

  Worker otavio = Worker.builder()
    .age(35).name("Otavio")
    .city("Salvador")
    .gender(Gender.MALE)
    .dailyHours(30).build();

  DocumentTemplate template = container.select(DocumentTemplate.class).get();

  template.insert(Arrays.asList(otavio, poliana));
  
}
select metodu
Örnek
Şöyle yaparız
try (SeContainer container = SeContainerInitializer.newInstance().initialize()) {

  DocumentTemplate template = container.select(DocumentTemplate.class).get();

  DocumentCondition maleAfterThirty = and(eq("gender", Gender.MALE), gte("age", 30));

  DocumentCondition femaleAfterThirty = and(eq("gender", Gender.FEMALE),gte("age", 30));

  DocumentQuery query =  DocumentQuery.builder()
    .from("Worker")
    .sort(asc("name"))
    .where(or(maleAfterThirty, femaleAfterThirty))
    .build();

  Stream<Worker> stream = template.select(query);
  List<Worker> workers = stream.collect(Collectors.toList());
  workers.forEach(System.out::println);

}





Bean Validation @GroupSequence Anotasyonu

Örnek Elimizde şöyle bir kod olsun public class SampleRequest {   @NotNull   LocalDate startDate;   @NotNull   LocalDate endDate;   @AssertT...