Skip to main content

#REVIEW: What’s new in MicroProfile 3.0

by rieckpil at June 16, 2019 01:36 PM

With the MicroProfile release cycle of three releases every year in February, June, and October we got MicroProfile 3.0 on June 11th, 2019. This version is based on MicroProfile 2.2 and updates the Rest Client, Metrics, and Health Check API which I’ll show you in this blog post today.

The current API landscape for MicroProfile 3.0 looks like the following:

 

As you can see in this image, there were no new APIs added with this release. The Microprofile Rest Client API was updated from 1.2 to 1.3 with no breaking change included. The Metrics API got a new major version update from 1.1 to 2.0 introducing some breaking changes, which you’ll learn about. The same is true for the Health Check API which is now available with version 2.0 and also introduces breaking API changes.

Changes with Metrics 2.0: Counters ftw!

Important links:

  • Official changelog on GitHub
  • Current API specification document as pdf
  • Release information on GitHub

Breaking changes:

  • Refactoring of Counters, as the old @Counted was misleading in practice (you can find migration hints in the API specification document)
  • Removed deprecated org.eclipse.microprofile.metrics.MetricRegistry.register(String name, Metric, Metadata)
  • Metadata is now immutable and built via a MetadataBuilder.
  • Metrics are now uniquely identified by a MetricID (a combination of the metric’s name and tags).
  • JSON output format for GET requests now appends tags along with the metric in metricName;tag=value;tag=value format. JSON format for OPTIONS requests has been modified such that the ‘tags’ attribute is a list of nested lists which holds tags from different metrics that are associated with the metadata. The default value of the reusable attribute for metric objects created programmatically (not via annotations) is now true
    Some base metrics’ names have changed to follow the convention of ending the name of accumulating counters with total

Other important changes:

  • Removed unnecessary @InterceptorBinding annotation from org.eclipse.microprofile.metrics.annotation.Metric
  • Tag key names for labels are restricted to match the regex [a-zA-Z_][a-zA-Z0-9_]*.
  • MetricFilter modified to filter with MetricID instead of the name
  • Tag values defined through  MP_METRICS_TAGS must escape equal signs = and commas, with a backslash \.

Changes with Health Check 2.0: Kubernetes here we come!

Important links:

  • Current API specification document as pdf
  • All changes with this release
  • Release information on GitHub

Breaking changes:

  • The message body of Health check response was modified, outcome and state were replaced by status
  • Introduction of Health checks for @Liveness and @Readiness on /health/ready and /health/live endpoints (nice for Kubernetes)

Other important changes:

  • Deprecation of @Health annotation
  • Correction and enhancement of response JSON format
  • TCK enhancement and cleanup
  • Enhance examples in spec (introduce Health check procedures producers)

Changes with Rest Client 1.3: Improved config and security!

Important links:

Important changes:

  • Spec-defined SSL support via new RestClientBuilder methods and MP Config properties.
  • Allow client proxies to be cast to Closeable/AutoCloseable.
  • Simpler configuration using configKeys.
  • Defined application/json to be the default MediaType if none is specified in @Produces/@Consumes.

For more details, you can visit the official announcement post on the MicroProfile page.

I’m planning to give you code-based examples for MicroProfile 3.0 once the first application server supports it (for Payara this will be version 5.193). Stay tuned!

Have fun with MicroProfile 3.0,

Philip


by rieckpil at June 16, 2019 01:36 PM

Deploying and Configuring Payara Micro on OpenShift with s2i

by admin at June 12, 2019 12:35 PM

Payara Micro Server is configurable with Boot Scripts, which work well together with OpenShift's s2i tool.

Payara Micro s2i image uses the OpenShift's "source to image" functionality to configure the server and deploy Java EE / Jakarta EE / MicroProfile apps in "cloud native" fashion:

The following tools were used in the screencast:
  1. Java EE 8 Quickstarter
  2. s2i-payara-micro openshift "builder" image
  3. (indirectly) payara-micro-s2i super docker image
See: https://github.com/AdamBien/s2i-payara-micro for installation details / examples.

s2i is also available for Payara Full: https://github.com/AdamBien/s2i-payara

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.


by admin at June 12, 2019 12:35 PM

Transactions, J2EE, Java EE, Jakarta EE, MicroProfile and Quarkus--airhacks.fm Podcast

by admin at June 11, 2019 01:19 PM

Subscribe to airhacks.fm podcast via: spotify| iTunes| RSS

The #40 airhacks.fm episode with Mark Little (@nmcl) about Transactions, J2EE, Java EE, Jakarta EE, MicroProfile and Quarkus is available for download.

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.

by admin at June 11, 2019 01:19 PM

Adding External NPM JavaScript Dependencies as ES 6 Modules

by admin at June 10, 2019 01:17 PM

In this free bonus episode from the effectiveweb.training training, I'm adding a lit-html and d3js dependencies as ES 6 modules created by www.pikapkg.com:

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.


by admin at June 10, 2019 01:17 PM

#HOWTO: Send emails with Java EE using Payara

by rieckpil at June 09, 2019 05:34 PM

Sending emails to your application’s clients or customers is a common enterprise use case. The emails usually contain invoices, reports or confirmations for a given business transaction. With Java, we have a mature and robust API for this: The JavaMail API.

The JavaMail API standard has a dedicated website providing official documentation and quickstart examples. The API is part of the Java Standard Edition (Java SE) and Java Enterprise Edition (Java EE) and can, therefore, be used also without Java EE.

In this blog post, I’ll show you how you can send an email with an attachment to an email address of your choice using this API and Java EE 8, MicroProfile 2.0, Payara 5.192, Java 8, Maven and Docker.

Let’s get started.

Setting up the backend

For the backend, I’ve created a straightforward Java EE 8 Maven project:

<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>de.rieckpil.blog</groupId>
  <artifactId>java-ee-sending-mails</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>
  <dependencies>
    <dependency>
      <groupId>javax</groupId>
      <artifactId>javaee-api</artifactId>
      <version>8.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.eclipse.microprofile</groupId>
      <artifactId>microprofile</artifactId>
      <version>2.0.1</version>
      <type>pom</type>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <version>2.23.0</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>
    <finalName>java-ee-sending-mails</finalName>
  </build>
  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <failOnMissingWebXml>false</failOnMissingWebXml>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  </properties>
</project>

The email transport is triggered by a JAX-RS endpoint (definitely no best practice, but good enough for this example):

@Path("mails")
public class MailingResource {

  @Inject
  private MailingService mailingService;

  @GET
  public Response sendSimpleMessage() {
    mailingService.sendSimpleMail();
    return Response.ok("Mail was successfully delivered").build();
  }

}

The actual logic for creating and sending the email is provided by the MailingService EJB which is injected via CDI in the JAX-RS class:

@Stateless
public class MailingService {

    @Inject
    @ConfigProperty(name = "email")
    private String emailAddress;


    @Resource(name = "mail/localsmtp")
    private Session mailSession;

    public void sendSimpleMail() {

        Message simpleMail = new MimeMessage(mailSession);

        try {
            simpleMail.setSubject("Hello World from Java EE!");
            simpleMail.setRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress));

            MimeMultipart mailContent = new MimeMultipart();

            MimeBodyPart mailMessage = new MimeBodyPart();
            mailMessage.setContent(
               "<p>Take a look at the <b>scecretMessage.txt</b> file</p>", "text/html; charset=utf-8");
            mailContent.addBodyPart(mailMessage);

            MimeBodyPart mailAttachment = new MimeBodyPart();
            DataSource source = new ByteArrayDataSource(
               "This is a secret message".getBytes(), "text/plain");
            mailAttachment.setDataHandler(new DataHandler(source));
            mailAttachment.setFileName("secretMessage.txt");

            mailContent.addBodyPart(mailAttachment);
            simpleMail.setContent(mailContent);

            Transport.send(simpleMail);

            System.out.println("Message successfully send to: " + emailAddress);
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }
}

First, the EJB requires an instance of the javax.mail.Session class which is injected with @Resoucre and found via its unique JNDI name. The connection setup for this email session is done with either the Payara admin web page or using asadmin as you’ll see in the next section.

The Session object is then used to create a MimeMessage instance which represents the actual email. Setting the email recipient and the subject of the email is pretty straightforward. In this example, I’m injecting the recipient’s email address via the MicroProfile Config API with a microprofile-config.properties file:

email=duke@java.ee

For both the attachment and for the email body I’m using a dedicated MimeBodyPart instance and add both to the MimeMultipart object. Finally, the email is sent via the static Transport.send(Message msg) method via SMPT.

Providing an SMPT server

For your real-world example, you would connect to your company internal SMPT server to send the emails to e.g. your customers. To provide you a running example without using an external SMPT server I’m using a Docker container to start a local SMPT server. The whole infrastructure (SMPT server and Java EE backend) for this example is combined in a simple docker-compose.yml file:

version: '3'
services:
  app:
    build: ./
    ports:
      - "8080:8080"
      - "4848:4848"
    links:
      - smtp
  smtp:
    image: namshi/smtp
    ports:
      - "25:25"

With this setup, the Docker container with the Payara application server can reach the SMPT server via its name smpt and I don’t need to hardcode any IP address.

The email session is then configured (connection settings and JNDI name) in Payara with a post-boot asadmin script:

# Connecting to the SMTP server within the Docker Compose environment
create-javamail-resource --mailhost smtp --mailuser duke --fromaddress duke@java.ee mail/localsmtp

# For a connecting to e.g. Gmail's SMTP you have to specify further parameters (check e.g. https://medium.com/@swhp/sending-email-with-payara-and-gmail-56b0b5d56882)

deploy /opt/payara/deployments/java-ee-sending-mails.war

For the sake of completeness, this is the Dockerfile for the backend:

FROM payara/server-full:5.192
COPY create-mail-session.asadmin $CONFIG_DIR
COPY target/java-ee-sending-mails.war $DEPLOY_DIR
ENV POSTBOOT_COMMANDS $CONFIG_DIR/create-mail-session.asadmin

You can find the source code alongside a docker-compose.yml file to bootstrap the application and an SMTP server for local development on GitHub.

Have fun sending emails with Java EE,

Phil


by rieckpil at June 09, 2019 05:34 PM

Json Web Token Generator - JWTenizr.sh 0.0.3 released

by admin at June 07, 2019 09:39 AM

Version 0.0.3 of jwtenizr.sh was released. The 0.0.3 version comes with improved user output and configuration formatting.

JWTenizr is a JWT-, public- and private key, and MicroProfile config generator:

  1. Download: https://github.com/AdamBien/jwtenizr/releases/
  2. Use: java -jar jwtenizr.jar

With jwtenizr.sh you can easily generate a JWToken comprising roles and principal, as well as, a MicroProfile configuration file and curl command. The generated output is particularly useful for system testing:

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.

by admin at June 07, 2019 09:39 AM

[EN] Using Logger with @Produces

by Altuğ Bilgin Altıntaş at June 06, 2019 12:23 PM

Logging the events is crucial so how can we use Logging mechanism into our Jakarta EE projects? Here we go :

import java.util.logging.Logger;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;

/**
*
* @author altuga
*/
public class LogManager {

   @Produces
   public Logger configure(InjectionPoint point) {
     String name = point.getMember().getName();
     return Logger.getLogger(name);
   }
}

In order to use Logger in your project, just inject the Logger and start using it like this :

import java.util.List;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import org.eclipse.microprofile.metrics.annotation.Metered;


@Path("/ping")
@Stateless
public class PingResource {

   @Inject
   Pingy pingy;

   @Inject
   Logger logger;

   @GET
   public String ping() {
     return pingy.pingMe();
   }

   @POST
   @Metered
   public void save(Ping ping) {
    logger.info("save method called...");
    pingy.save(ping);
  }

   @GET
   @Path("/all")
   public List<Ping> getAll() {
     return pingy.getAll();
   }
}

After that, you should be able to see the logs in app server’s log management system.

Enjoy


by Altuğ Bilgin Altıntaş at June 06, 2019 12:23 PM

Java's Job Listings, JWT, Kafka, Serverless, Streaming, JARs in WARs, Threads, Code Coverage--63rd airhacks.tv

by admin at June 06, 2019 07:00 AM

63rd airhacks.tv episode with the following topics:
"Java's job listing report for May 2019, JWT, Authorization, Kafka vs. JMS, Java and serverless, streaming, containers, proper scope for JAX-RS resources, purpose of JARs in WARs, dealing with threads in Java EE runtimes, code coverage and system tests quarkus vs. OpenLiberty, CI/CD"

Any questions left? Ask now: https://gist.github.com/AdamBien/a72ef679c0651101c2598a9d79ff62bd and get the answers at the next airhacks.tv.

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.

by admin at June 06, 2019 07:00 AM

Reactive, Asynchronous JAX-RS Client with Thread Pool aka Bulkheads

by admin at June 05, 2019 09:42 AM

A plain Java class with injected and configurable thread pool (ManagedExecutorService):

import java.util.concurrent.CompletionStage;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.enterprise.concurrent.ManagedExecutorService;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;


public class ContentFetcher {

    private Client client;
    private WebTarget workshopsTarget;
    
    @Resource
    ManagedExecutorService mes;
    
    @PostConstruct
    public void initClient() {
        this.client = ClientBuilder.
                newBuilder().
                executorService(this.mes).build();
        this.workshopsTarget = this.client.target("http://workshops.adam-bien.com");
    }

    public CompletionStage<String> fetchContent() {
        return this.workshopsTarget.request().
                rx().
                get(String.class);
    }

}
        

...used by the asynchronous, reactive invoker (the method rx()).

Can be directly exposed via an ordinary JAX-RS resource:


@Path("workshops")
public class WorkshopsResource {

    @Inject
    ContentFetcher fetcher;

    @GET
    public CompletionStage<String> content() {
        return this.fetcher.fetchContent();
    }

}

The amount of parallelism is globally configurable with the default ManagedExecutorService, or by declaring dedicated ManagedExecutorService (effectively Bulkhead pattern, also covered in javaeemicro.services workshop) for each communication / IO channel.

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.

by admin at June 05, 2019 09:42 AM

[EN] How to Call the Next Handler in Vert.x?

by Hüseyin Akdogan at June 05, 2019 05:00 AM

In Vert.x, when a Router takes an HTTP request, it finds a matching route (if any) and then it calls the handler of the route passing in an instance of RoutingContext. More than one handler can be bounded to a route. This means that you can tell the router to route this context to the next matching route without ending the response in your handler.

Let’s assume we want to control and limit the amount of incoming and outgoing network traffic. For example, let’s say we provide a service that is configured to allow 10 requests/second. Similarly, let’s assume we use a circuit breaker for fault detection related to the service that the incoming request wants to access. In this case, If the incoming requests exceed the defined limit, or the service is unavailable, it will be necessary to refuse the request.

Calling the next handler offers us a useful way to manage the kind of need that’s requiring different controls for the same purpose.

Calling the Next Handler

@Override
public void start(Future future) {

    final ConfigStoreOptions rateOptions = new ConfigStoreOptions()
            .setType("file")
            .setOptional(true)
            .setConfig(new JsonObject().put("path", System.getProperty("user.dir") + "/Routing/src/main/resources/config.json"));

    final ConfigRetrieverOptions options = new ConfigRetrieverOptions().addStore(rateOptions);

    final Router router = RouterHelper.createRouter(vertx, "Hello from routing example!");
    router.get("/limiting").handler(new CircuitBreakerHandler(options));
    router.get("/limiting").handler(new RateLimiterHandler(options));
    HttpServerHelper.createAnHttpServer(vertx, router, config(), future);
}

In the above code, we created two routes for the same path and bounded different handlers. When a GET /limiting request arrives the CircuitBreakerHandler will work first.

@Override
public void handle(RoutingContext context) {

    final ConfigRetriever retriever = ConfigRetriever.create(context.vertx(), options);

    retriever.getConfig(ar -> {
        if (ar.failed()) {
            log.error("Failed to retrieve the configuration");
        } else {

            final JsonObject config = ar.result();
            final boolean circuitbreaker = config.getBoolean("circuitbreaker");

            if (!circuitbreaker) {
                context.next();
            } else {
                context.response()
                        .putHeader(CONTENT_TYPE, HTML_PRODUCE)
                        .setStatusCode(HTTP_SERVICE_UNAVAILABLE)
                        .end("Service unavailable!");
            }
        }
    });
}

In the handler, we are checking firstly to CircuitBreaker and if it’s closed we call next method of the RoutingContext. The next method tell the router to route this context to the next matching route (if any). In our example, this will provide calling RateLimiterHandler. I created a repository for this example, you can examine.

Conclusion

Vert.x allows multiple handlers binding to a route. This provides routing the handled context to the next matching route and so encapsulates your handlers for different logic by linking together such as a chain.

References


by Hüseyin Akdogan at June 05, 2019 05:00 AM

Java EE - Jakarta EE Initializr

June 03, 2019 01:37 PM

Getting started with Jakarta EE just became even easier!

Get started

Update!

version 1.2 now has…

Payara 5.192 and JKD 11.0.3


June 03, 2019 01:37 PM

The Payara Monthly Roundup for May 2019

by Jadon Ortlepp (Jadon.Ortlepp@Payara.fish) at June 03, 2019 10:31 AM

This was a big month for the Payara Team. We just released Payara Platform 5.192, we toured all across Japan and there has been plenty going on in the Java world with the announcement by the Eclipse Foundation regarding the continued use of the javax namespace. 


by Jadon Ortlepp (Jadon.Ortlepp@Payara.fish) at June 03, 2019 10:31 AM

JWT, Authorization, Kafka vs. JMS, Streaming, Containers, Serverless, Code Coverage, CI/CD--or 63rd airhacks.tv

by admin at June 03, 2019 04:14 AM

Topics for the 63rd airhacks.tv episode: https://gist.github.com/AdamBien/994d66074ce6a93a967e0720b714de2f:
  1. Answering past JWT questions and jwtenizr.sh introduction
  2. Kafka Streaming and co. Streaming Architectures Workshop
  3. No JARs in WARs and the exceptional cases
  4. Java an alien in serverless world?
  5. Java and cgroups
  6. Java in containers boot time
  7. EJB, RequestScoped, ApplicationScoped for JAX-RS resources
  8. Asynchronous clients, forbidden threads and async JAX-RS client
  9. OpenLiberty with tuned configuration vs. Quarkus
  10. Code Coverage and System Tests
  11. CI/CD setup with Jenkins
  12. JMS vs. Kafka

Ask questions during the show via twitter mentioning me: http://twitter.com/AdamBien (@AdamBien) or using the hashtag: #airhacks. You can join the Q&A session live each first Monday of month, 6 P.M at airhacks.tv or http://www.ustream.tv/channel/adambien

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.

by admin at June 03, 2019 04:14 AM

Use the Most Productive Stack You Can Get--airhacks.fm Podcast

by admin at June 02, 2019 08:38 PM

Subscribe to airhacks.fm podcast via: spotify|iTunes|RSS

The #39 airhacks.fm episode with Gunnar Morling (@gunnarmorling) about BeanValidation, Debezium, Quarkus, architecture verification and innovation is available for download.

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.

by admin at June 02, 2019 08:38 PM

Java EE - Jakarta EE Initializr

May 31, 2019 07:45 PM

<p><img src="/images/2019/javaee---jakarta-ee-initializr/javaee---jakarta-ee-initializr.jpg" style="width:50%;height:50%;display: block;margin: 0 auto;"></p> <p>Getting started with Jakarta EE just became even easier!</p> <h1 id="Updated-to-1-2"><a href="#Updated-to-1-2" class="headerlink" title="Updated to 1.2"></a>Updated to 1.2</h1><p><strong>Payara 5.192 and JKD 11.0.3</strong></p> <ul> <li><a href="http://ivo2u.nl/oq" target="_blank" rel="external">Java EE /Jakarta EE - Initializr</a></li> </ul>

May 31, 2019 07:45 PM

The Power of the Application Server

by Edwin Derks at May 31, 2019 07:48 AM

Presently, there is a battle of frameworks going on that compete for being the best “rightsizing” framework, tailored for building and running microservices as efficiently as possible. However, there is an older, yet proven concept available to run enterprise applications, that doesn’t apply the concept of rightsizing. On the contrary, it provides access to the full feature-rich specifications set of Jakarta EE (previously Java EE), without the need to right-size your enterprise applications.

The concept I’m referring to is that of the Application Server, commonly used in the Jakarta EE ecosystem. Because most developers are focusing on the rightsizing frameworks today, the concept of an application server is sometimes perceived to be outdated and not suitable for building (micro)services. This is not necessarily true, and the application server still has a part to play. Therefore I would like to address these perceptions by revisiting the concept of the application server and highlight its perks in building and running Java-based enterprise applications.

Application Server Characteristics

Currently, there are several application servers available that are built and made available by vendors for developers, often as open-source projects. Each of these application servers implements a certain version of the Jakarta EE specifications set. Application servers are used to run your Jakarta EE enterprise applications. This means that present-day application servers implement the specifications of Jakarta EE, not yet officially released but compatible with Java EE 8. Although the various application servers are likely to share some of the implementation details, they are also very different. If you compare the internals of application servers, you will see that they all apply their own approach of implementing the specifications and running the server. Some servers also provide some vendor-specific commercial features that should make using the application server for your purposes a more optimal experience.

Eclipse MicroProfile

Note that next to the Jakarta EE specifications, several application servers also implement the specifications from Eclipse MicroProfile. Like Jakarta EE, this is a specifications-based framework that is also being developed under the stewardship of the Eclipse Foundation. MicroProfile provides you, among other features, with the ability to run your application server in a scalable environment like a cloud. This is a fit for orchestrators and monitors because these are operating on the MicroProfile endpoints that are exposed for health checks and metrics.

Lean and tidy enterprise applications

If you look at the picture above, you can see that the application server runs on Java and exposes the various Jakarta EE, and possibly MicroProfile specifications to run Java-based enterprise applications. This means  you can compile your enterprise applications against the matching specifications to make them compatible with the application server. This has the advantage that you don’t have to include the implementations of the specifications in your build artifacts (often in the form of a WAR (Web ARchive). That leads to enterprise applications that only contain your business logic, therefore often just a few kilobytes in size. Your enterprise application becomes essentially an extension of the application server itself.

Easy development

To start developing Jakarta EE-based enterprise applications, you only have to create a Maven-based Java project that contains the following dependency:

<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>8.0</version>
    <scope>provided</scope>
</dependency>

This is currently a legacy Java EE 8 dependency, but it will soon be replaced by a Jakarta EE counterpart. Since Jakarta EE  and Java EE 8 are to remain compatible in regard to the specifications, the dependencies should be drop-in replacements.

In case your application server also supports MicroProfile, you can also include this dependency in your Maven project:

<dependency>
    <groupId>org.eclipse.microprofile</groupId>
    <artifactId>microprofile</artifactId>
    <version>2.2</version>
    <type>pom</type>
</dependency>

These dependencies alone provide you with full and seamless access to the complete specification sets of Jakarta EE and MicroProfile in your project. If you start coding in your IDE, you should be able to access and compile against the Java classes, interfaces and annotations from the specifications that are exposed by the Maven dependencies.

Deploying your enterprise application

By using Maven’s Jakarta EE and MicroProfile dependencies for building enterprise applications, you can also easily build and deploy your application on your application server. Usually, you only have to tell Maven that you want your application built as a WAR (Web ARchive) which implicitly contains the internal file structure that is understood by the application server.

<packaging>war</packaging>

When you have chosen an application server to run your enterprise application on, you can download and unzip it before configuring your IDE to deploy your enterprise application onto the application server.

When you want to deploy your code on the application server, you can easily do so by using the (re)deploy option in your IDE. Maven will then (re)build your enterprise application and deploy it on the (running) application server. Since the WAR is usually only kilobytes in size, this should only take milliseconds. This should save you lots of development time and provide you with a pleasant development experience at the same time.

Additional Powers

But that is not all. Using an application server should provide you with a machine that has been optimized by a vendor to handle high loads of request and data. As I explained earlier, the whole application server consists of several components. These are all tuned and optimized to run in harmony to let the application server run with optimal performance and stability on the available resources. Yes, this can take lots of RAM and CPU cycles, but you should ask yourself if this really is a problem. This phenomenon has not yet been solved by rightsizing frameworks either, and should be justified when it provides you with the desired performance and stability.

Another benefit is patching and upgrading the application server. Since the internals of the whole application server are available to you, details like what’s in it and how it works are perfectly transparent. You can use this to your advantage because it allows you to tune the application server to your needs, or replace parts of the application server when patches or upgrades made available by the vendor.

Conclusion

An application server is, of course, no silver bullet, but other concepts, including the “rightsizing” frameworks aren’t either. However, there is a place for application servers in the modern world.

The question you should ask yourself when you are considering using application servers is: do you really need microservices? I personally don’t think that is necessarily true. Sometimes you just want scalable services. And that’s an angle of approach where Jakarta EE and the appliance of application servers really shine through.

Due to the monolithic approach of building and running enterprise applications, an application server should relieve you of the architectural, infrastructural and operational overhead that you implicitly get when you build on a pure microservices-based architecture.

By using application servers, you can still build scalable enterprise applications, and with the addition of MicroProfile, these are also are a fit for scalable environments. And because an application server is tuned with performance, stability and ease of development in mind, it should be a solid base for your project when it aligns with Jakarta EE’s angle of approach in building present-day enterprise applications.


by Edwin Derks at May 31, 2019 07:48 AM

Reading and Writing Configuration Files with JSON-B

by admin at May 31, 2019 07:47 AM

JSON-B ships with Java EE 8 and is already included in the API:

<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>8.0</version>
    <scope>provided</scope>
</dependency>    
In standalone applications, like e.g. CLI, you will have to add the SPI (Service Provider Implementation) dependency:

<dependency>
    <groupId>org.eclipse</groupId>
    <artifactId>yasson</artifactId>
    <version>1.0.3</version>
</dependency>        
<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1.4</version>
</dependency>    
Public POJO fields are serialized per default, private field serialization needs customization.

The following POJO:


import java.nio.file.Files;
import java.nio.file.Paths;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.json.bind.JsonbConfig;

public class Configuration {

    public String workshop;
    public int attendees;

    private final static String CONFIGURATION_FILE = "airhacks-config.json";

    public Configuration save() {
        Jsonb jsonb = JsonbBuilder.create(new JsonbConfig().withFormatting(true));
        try (FileWriter writer = new FileWriter(CONFIGURATION_FILE)) {
            jsonb.toJson(this, writer);
        } catch (IOException ex) {
            throw new IllegalStateException(ex);
        }
        return this;

    }

    public static Configuration load() {
        if (!Files.exists(Paths.get(CONFIGURATION_FILE))) {
            return new Configuration().save();
        }
        try (FileReader reader = new FileReader(CONFIGURATION_FILE)) {
            return JsonbBuilder.create().fromJson(reader, Configuration.class);
        } catch (IOException ex) {
            throw new IllegalStateException(ex);
        }
    }
}    

...is directly written:

@Test
public void loadAndSave() {
    Configuration configuration = Configuration.load();
    configuration.attendees = 13;
    configuration.workshop = "Cloudy Jakarta EE";
    configuration.save();
}    

to:

{
    "attendees": 13,
    "workshop": "Cloudy Jakarta EE"
}    
JSON-B provides additional features like e.g. formatting, which are not available in JSON-P.

jwtenizr.sh uses the above approach (see Configuration.java to store the private and public keys, issuer, as well as the JWT location.

Also checkout: "Reading and Writing Configuration Files with JSON-P"

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.


by admin at May 31, 2019 07:47 AM

Reading and Writing Configuration Files with JSON-P

by admin at May 30, 2019 09:55 AM

JSON-P ships with Java EE 8 and is already included in the API:

<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>8.0</version>
    <scope>provided</scope>
</dependency>    
In standalone applications, like e.g. CLI, you will have to add the SPI (Service Provider Implementation) dependency:

<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1.4</version>
</dependency>    
JsonReader reads the configuration from InputStream:

    public final static String CONFIGURATION_FILE = "duke-config.json";

    public static JsonObjectBuilder load() throws FileNotFoundException {
        try (JsonReader reader = Json.createReader(new FileInputStream(CONFIGURATION_FILE))) {
            return Json.createObjectBuilder(reader.readObject());
        }
    }    
and the JsonWrite serializes an in-memory instance into a stream:

    public static void write(JsonObject configuration) {
        try (JsonWriter writer = Json.createWriter(new FileOutputStream(CONFIGURATION_FILE))) {
            writer.writeObject(configuration);
        } catch (FileNotFoundException ex){}
    }    
An JsonObject is a typed Map<String, JsonValue>, the values can be directly access with a key:

public static String getValue(String key) {
    JsonObject configuration = null;
    try {
        configuration = load().build();
    } catch (FileNotFoundException ex) {    }
    return configuration.getString(key);
}
jwtenizr.sh uses the above approach (see Configuration.java to store the private and public keys, issuer, as well as the JWT location.

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.


by admin at May 30, 2019 09:55 AM

[En] Custom Field Serialization with JSON-B and JAX-RS / JAVA EE 8 / Payara 5

by Altuğ Bilgin Altıntaş at May 30, 2019 07:41 AM

In JSON-B private fields of an object are not serialized by default. Beyond that, you would want to serialize your custom fields according to your business logic. Let’s start with an example:

public class Picture {

private String name;

private int size;

private String content;

  public Picture(String name, int size, String content) {
    this.name = name;
    this.size = size;
    this.content = content;
  }

}

Let’s say you want to show “name” and “size” but you don’t want to show your “content” field.  All three variables are private so in order to make a distiction, you could use self-made annotation.

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MetaData {

}

After that, you could use MetaData self-made annotation class in Picture class.

public class Picture {

@MetaData
private String name;

@MetaData
private int size;

private String content;

   public Picture(String name, int size, String content) {
     this.name = name;
     this.size = size;
     this.content = content;
   }
}

Let’s implement business strategy

public class AljoschaStrategy implements PropertyVisibilityStrategy {

   private boolean everything;

   public AljoschaStrategy(boolean everything) {
     this.everything = everything;
   }

   @Override
   public boolean isVisible(Field field) {

      if (this.everything) {
        return true;
      }

      return field.isAnnotationPresent(MetaData.class);
   }

   @Override
   public boolean isVisible(Method method) {
    return false;
   }
}

In order to activate the business strategy, we have to implement ContextResolver. Please don’t forget to use generics

@Provider
public class Strategy implements ContextResolver<Jsonb>{

@Override
public Jsonb getContext(Class type) {

   JsonbConfig config = new JsonbConfig().
    withPropertyVisibilityStrategy
      (new AljoschaStrategy(false));

   return JsonbBuilder.newBuilder().
     withConfig(config).
     build();
  }
}

And last our JAX-RS rest services

@Path("ping")
@Produces(MediaType.APPLICATION_JSON)
public class PingResource { 

   @GET
   public JsonObject ping() {
     return new Ping("duke", "istanbul").toJson(); 
   }

   @GET
   @Path("picture")
   public Picture picture(@Context HttpHeaders headers) {
     return new Picture("aljoscha", 42, "nice face");
   }
}

In order to run

curl -i localhost:8080/advanced/resources/ping/picture

Result :

{“name”:”aljoscha”,”size”:42}%

 

 


by Altuğ Bilgin Altıntaş at May 30, 2019 07:41 AM

Jakarta EE, A de facto standard in the making

by David R. Heffelfinger at May 28, 2019 10:06 PM

I’ve been involved in Java EE since the very beginning, Having written one of the first ever books on Java EE. My involvement in Java EE / Jakarta EE has been on an education / advocacy role. Having written books, articles, blog posts and given talks in conferences about the technology. I advocate Jakarta EE not because I’m paid to do so, but because I really believe it is a great technology. I’m a firm believer that the fact that Jakarta EE is a standard, with multiple competing implementations, results in very high quality implementations, since Jakarta EE avoids vendor lock-in and encourages competition, benefiting developers.


Oracle’s donation of Java EE to the Eclipse Foundation was well received and celebrated by the Java EE community. Many prominent community members had been advocating for a more open process for Java EE, which is exactly what Jakarta EE, under the stewardship from the Eclipse Foundation provides.


There are some fundamental changes on how Jakarta EE is managed, that differ from Java EE, that benefit the Jakarta EE community greatly.

Fundamental differences between Java EE and Jakarta EE Management


Some of the differences in the way Jakarta EE is managed as opposed to Java EE are that there is no single vendor controlling the technology, there is free access to the TCK and there is no reference implementation.

No single company controls the standard

First and foremost, we no longer have a single company as a steward of Jakarta EE. Instead, we have several companies who have a vested interest in the success of the technology working together to develop the standard. This has the benefit that the technology is not subject to the whims of any one vendor, and, if any of the vendors loses interest in Jakarta EE, others can easily pick up the slack. The fact that there is no single vendor behind the technology makes Jakarta EE very resilient, it is here to stay.

TCK freely accessible

Something those of us involved heavily in Jakarta EE (and Java EE before), take for granted, but that may not be clear to others, is that Jakarta EE is a set of specifications with multiple implementations. Since the APIs are defined in a specification, they don’t change across Jakarta EE implementations, making Jakarta EE compliant code portable across implementations. For example, a Jakarta EE compliant application should run with minimal or no modifications on popular Jakarta EE implementations such as Apache Tomee, Payara, IBM’s OpenLiberty or Red Hat’s Thorntail


One major change that Jakarta EE has against Java EE is the fact that the Technology Compatibility Kit (TCK) is open source and free. The TCK is a set of test to verify that a Jakarta EE implementation is 100% compliant with all Jakarta EE specifications. With Java EE, organizations wanting to create a Java EE implementation, had to pay large sums of money to gain access to the TCK, once their implementation passed all the tests, their implementation was certified as Java EE compatible. The fact that the TCK was not freely accessible became a barrier to innovation, as smaller organizations and open source developers not always had the funds to get access to the TCK. Now that the TCK is freely accessible, the floodgates will open, and we should see a lot more quality implementations of Jakarta EE.

No reference implementation

Another major change between Java EE and Jakarta EE is that Java EE had the concept of a reference implementation. The idea behind having a Java EE reference implementation was to prove that suggested API specifications were actually feasible to implement. Having a reference implementation, however, had a side effect. If the reference implementation implemented something that wasn’t properly defined in the specification, then many developers expected all Java EE implementations to behave the same way, making the reference implementation a de-facto Java EE specification of sorts. Jakarta EE does away with the concept of a reference implementation, and will have multiple compatible implementations instead. The fact that there isn’t a reference implementation in Jakarta EE will result in more complete specifications, as differences in behavior between implementations will bring to light deficiencies in the specifications, these deficiencies can then be addressed by the community.

Conclusion

With multiple organizations with a vested interest in Jakarta EE’s success, a lowered barrier of entry for new Jakarta EE implementations, and better specifications Jakarta EE will become the de-facto standard in server-side Java development.



by David R. Heffelfinger at May 28, 2019 10:06 PM

Asynchronous JAX-RS: Timeout Configuration and Handling

by admin at May 28, 2019 06:57 AM

Asynchronous JAX-RS request can be configured with a timeout, as well as, custom timeout handling:

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.Response;

@Path("ping")
public class PingResource {

    @GET
    public void ping(@Suspended AsyncResponse response) {
        response.setTimeout(1, TimeUnit.SECONDS);
        response.setTimeoutHandler(this::onTimeout);
        //managed thread pools omitted
        CompletableFuture.supplyAsync(this::heavyThinking).thenAccept(response::resume);
    }

    String heavyThinking() {
        try {
            Thread.sleep(1000 * 2);
        } catch (InterruptedException e) {}
        return "42";
    }

    public void onTimeout(AsyncResponse response) {
        response.resume(Response.status(204).header("info", "late, but o.k").build());
    }

}

CLI: curl -i http://localhost:8080/jaxrs-async-timeout/resources/ping yields:


HTTP/1.1 204 No Content
Server: Payara Server  5.191 #badassfish
info: late, but o.k    

Project created with javaee8-essentials-archetype, the 4kB ThinWAR was built and deployed with: wad.sh in 2.4s

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.

by admin at May 28, 2019 06:57 AM

Securing JAX-RS Endpoints with JWT

by admin at May 27, 2019 03:10 AM

Install jwtenizr.sh by downloading jwtenizr.jar and execute java -jar jwtenizr.jar

JWTenizr will generate:

  1. jwtenizr-config.json with public, private key and target folder of microprofile-config.properties
  2. jwt-token.json: with Minimum MP-JWT Required Claims, a sample principal and a few groups. UPN becomes the Java EE principal, the groups are automatically mapped to Java EE roles.
  3. token.jwt: with information loaded from: jwt-token.json and can be used as input for automated system tests
  4. microprofile-config.properties comprising the public key an the issuer: copy to your WAR/src/main/resources/META-INF
  5. curl command. Is ready to use for testing with Authorization header and included token: curl -i -H'Authorization: Bearer eyJraW¢...(generated JWT token)' http://localhost:8080[RESOURCE and SUB-RESOURCES]

The JWT's claims and Principal become directly injectable and you can rely on the stock @RolesAllowed or @PermitAll annotations to guard methods.

See jwtenizr.sh with quarkus in (from scratch) action:

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.

by admin at May 27, 2019 03:10 AM

From Webscale Java over CDI to javax--airhacks.fm Podcast

by admin at May 26, 2019 02:21 PM

Subscribe to airhacks.fm podcast via: spotify| iTunes| RSS

The #38 airhacks.fm episode with Mark Struberg about the Apache's road to CDI, web scale projects, fire fighting and the javax namespace issue is available for download.

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.

by admin at May 26, 2019 02:21 PM

[En] How to resolve Ambiguous error in Jakarta EE with 3 different approach ?

by Altuğ Bilgin Altıntaş at May 24, 2019 03:11 PM

The problem :

Imagine that you have an interface like this

public interface Notification {
   void send(String message);
}

If you implement 2 versions of this interface like this

public class NotificationImpl implements Notification{

  @Override
  public void send(String message) {
     System.out.println(" --> " + message);
  }
}
public class NotificationImpl2 implements Notification{

  @Override
  public void send(String message) {
    System.out.println("--2 " + message);
  }
}

You could get an error like this if you don’t specify which implementation you exactly want to use

Exception during lifecycle processing
org.glassfish.deployment.common.DeploymentException: CDI deployment failure:WELD-001409: Ambiguous dependencies for type Notification with qualifiers @Default
at injection point [BackedAnnotatedField] @Inject com.airhacks.ping.boundary.Pingy.notification
at com.airhacks.ping.boundary.Pingy.notification(Pingy.java:0)
Possible dependencies:

 

Solution 1 – Use @Alternative

@Alternative
public class NotificationImpl implements Notification{

  @Override
  public void send(String message) {
    System.out.println(" --> " + message);
  }
}

@Alternative tag makes other implementation default

Solution 2 – Use javax.enterprise.inject.Instance

In this solution, you will call all implementations.

@Stateless
@Interceptors(CallTracer.class)
public class Pingy {

  @PersistenceContext
  EntityManager entityManager;

  @Inject
  Instance<Notification> notifications; // --> important

  @PostConstruct
  public void init() {
    System.out.println(" initilizaze...");

    System.out.println(" --> " + this.notifications.isAmbiguous());
    System.out.println(" --> " + this.notifications.isUnsatisfied());
    for (Notification notification : notifications) {
       notification.send("hey jowsal ....... "); //--> important
    }
}
....

Solution 3 – Use @Qualifier

In this solution, we will use @Qualifier within custom homemade annotations in order to increase readability.

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.TYPE})
public @interface Age {
   Time value();

   enum Time {
     RECENT, OLD
   }
}

Usage could be like that :

@Stateless
@Interceptors(CallTracer.class)
public class Pingy {

  @PersistenceContext
  EntityManager entityManager;

  @Inject
  @Age(Age.Time.OLD) // important
  Notification notification;

  @PostConstruct
  public void init() {
    System.out.println(" initilizaze...");
    notification.send("hey jowsal");
}

Hava fun…


by Altuğ Bilgin Altıntaş at May 24, 2019 03:11 PM

Election time for Jakarta EE Working Group Committees!

by Tanja Obradovic at May 24, 2019 10:02 AM

The Jakarta EE Working Group charter identifies three key committees to drive the various facets of the working group for which there are elected positions to be filled: the Steering Committee, the Specification Committee, and the Marketing and Brand Committee.

The elected positions are to represent each of the Enterprise Members, Participant Members, and Committer Members.  Note that Strategic Members each have a representative appointed to these committees.

This way, we are announcing that the Foundation will hold elections on behalf of the working group using the proposed timetable listed below. This mimics the process used by other working groups as well as the process used by the Eclipse Foundation itself for filling the elected positions on our Board.

All members are encouraged to consider nominating someone for the positions, and self-nominations are welcome. The period for nominations will open later this week and will run through June 4th.  Nominations may be sent to elections@eclipse.org.

Once nominations are closed, we will inform all working group members of the candidates and will distribute ballots via email to those eligible to vote.  The election process will follow the Eclipse “Single Transferable Vote” method, as defined in the Eclipse Bylaws.  

The winning candidates will be announced on this mailing list immediately after the elections are concluded.  

Election Schedule

Nomination period:  May 24 - June 4 (self-nominations are welcome)

Election period:  June 11 - June 25

Winning candidates announced:  June 27

 

The following positions will be filled as part of this election:

 

Steering Committee

Two seats allocated for Enterprise Members

One seat allocated for Participant Members

One seat allocated for Committer Members

Specification Committee

Two seats allocated for Enterprise Members

One seat allocated for Participant Members

One seat allocated for Committer Members

Marketing and Brand Committee

Two seats allocated for Enterprise Members

One seat allocated for Participant Members

One seat allocated for Committer Members


by Tanja Obradovic at May 24, 2019 10:02 AM

JVM vs. Native: Scaling from 0 to 20 Nodes with quarkus.io

by admin at May 23, 2019 10:15 AM

How long does it take to scale a Java EE-like application based on quarkus.io and created with quarkee from 0 to 20 nodes and back with kubernetes. The same application was started on a JVM and a native image.

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.


by admin at May 23, 2019 10:15 AM

Jakarta EE and the great naming debate

May 21, 2019 03:49 PM

At JavaOne 2017 Oracle announced that they would start the difficult process of moving Java EE to the Eclipse Software Foundation. This has been a massive effort on behalf of Eclipse, Oracle and many others and we are getting close to having a specification process and a Jakarta EE 8 platform. We are looking forward to being able to certify Open Liberty to it soon. While that is excellent news, on Friday last week Mike Milinkovich from Eclipse informed the community that Eclipse and Oracle could not come to an agreement that would allow Jakarta EE to evolve using the existing javax package prefix. This has caused a flurry of discussion on Twitter, from panic, confusion, and in some cases outright FUD.

To say that everyone is disappointed with this outcome would be a massive understatement of how people feel. Yes this is disappointing, but this is not the end of the world. First of all, despite what some people are implying, Java EE applications are not suddenly broken today, when they were working a week ago. Similarly, your Spring apps are not going to be broken (yes, the Spring Framework has 2545 Java EE imports, let alone all the upstream dependencies). It just means that we will have a constraint on how Jakarta EE evolves to add new function.

We have got a lot of experience with managing migration in the Open Liberty team. We have a zero migration promise for Open Liberty which is why we are the only application server that supports Java EE 7 and 8 in the same release stream. This means that if you are on Open Liberty, your existing applications are totally shielded from any class name changes in Jakarta EE 9. We do this through our versioned feature which provide the exact API and runtime required by the specification as it was originally defined. We are optimistic about for the future because we have been doing this with Liberty since it was created in 2012.

The question for the community is "how we should move forward from here?" It seems that many in the Jakarta EE spec group at Eclipse are leaning towards quickly renaming everything in a Jakarta EE 9 release. There are advantages and disadvantages to this approach, but it appears favoured by David Blevins, Ian Robinson, Kevin Sutter, Steve Millidge. While I can see the value of just doing a rename now (after all, it is better pull a band aid off fast than slow), I think it would be a mistake if at the same time we do not invest in making the migration from Java EE package names to Jakarta EE package names cost nothing. Something in Liberty we call "zero migration".

Jakarta EE will only succeed if developers have a seamless transition from Java EE to Jakarta EE. I think there are four aspects to pulling off zero migration with a rename:

  1. Existing application binaries need to continue to work without change.

  2. Existing application source needs to continue to work without change.

  3. Tools must be provided to quickly and easily change the import statements for Java source.

  4. Applications that are making use of the new APIs must be able to call binaries that have not been updated.

The first two are trivial to do: Java class files have a constant pool that contains all the referenced class and method references. Updating the constant pool when the class is loaded will be technically easy, cheap at runtime, and safe. We are literally talking about changing javax.servlet to jakarta.servlet, no method changes.

The third one is also relatively simple; as long as class names do not change switching import statements from javax.servlet.* to jakarta.servlet.* is easy to automate.

The last one is the most difficult because you have existing binaries using the javax.servlet package and new source using the jakarta.servlet package. Normally this would produce a compilation error because you cannot pass a jakarta.servlet class somewhere that takes a javax.servlet class. In theory we could reuse the approach used to support existing apps and apply it at compile time to the downstream dependencies, but this will depend on the build tools being able to support this behaviour. You could add something to the Maven build to run prior to compilation to make sure this works, but that might be too much work for some users to contemplate, and perhaps is not close enough to zero migration.

I think if the Jakarta EE community pulls together to deliver this kind of zero migration approach prior to making any break, the future will be bright for Jakarta EE. The discussion has already started on the jakarta-platform-dev mail list kicked off by David Blevins. If you are not a member you can join now on eclipse.org. I am also happy to hear your thought via twitter.


May 21, 2019 03:49 PM

Persistence for Java Microservices in Kubernetes via JPA

by Niklas Heidloff at May 21, 2019 03:14 PM

Over the last weeks I’ve worked on an example application that demonstrates how Java EE developers can get started with microservices. The application is a full end-to-end sample which includes a web application, business logic, authentication and now also persistence. It runs on Kubernetes and Istio and there are scripts to easily deploy it.

Get the cloud-native-starter code from GitHub.

Java Persistence API

In the example I use a full open source Java stack with OpenJ9, OpenJDK, Open Liberty and MicroProfile. In order to deploy the microservices to Kubernetes, I’ve created an image. Read my article Dockerizing Java MicroProfile Applications for details.

Open Liberty provides some pretty good guides. One guide is specifically about JPA: Accessing and persisting data in microservices. I don’t want to repeat everything here, but only highlight the changes I had to do to run this functionality in a container, rather than via a local Open Liberty installation.

Here is a short description of JPA:

JPA is a Java EE specification for representing relational database table data as Plain Old Java Objects (POJO). JPA simplifies object-relational mapping (ORM) by using annotations to map Java objects to tables in a relational database. In addition to providing an efficient API for performing CRUD operations, JPA also reduces the burden of having to write JDBC and SQL code when performing database operations and takes care of database vendor-specific differences.

Configuration of the Sample Application

The following diagram shows the simplied architecture of the cloud-native-starter example. A web application invokes through Ingress the Web-API service that implements a backend-for-frontend pattern. The Web-API service invokes the Articles service which stores data in a SQL database on the IBM Cloud. Obviously you can use any other SQL database instead.

In order to access the Db2 on the IBM Cloud, first the driver needs to be downloaded via Maven. Note that the driver does not go into the war files together with the business logic of the microservices, but it needs to be copied in a certain Open Liberty directory: /opt/ol/wlp/usr/shared/resources/jcc-11.1.4.4.jar

Next you need to define in server.xml information about the driver and the data source.

<server description="OpenLiberty Server">
    <featureManager>
        <feature>webProfile-8.0</feature>
        <feature>microProfile-2.1</feature>
    </featureManager>

    <httpEndpoint id="defaultHttpEndpoint" host="*" httpPort="8080" httpsPort="9443"/>

    <library id="DB2JCCLib">
        <fileset dir="${shared.resource.dir}" includes="jcc*.jar"/>
    </library>

    <dataSource id="articlejpadatasource"
              jndiName="jdbc/articlejpadatasource">
        <jdbcDriver libraryRef="DB2JCCLib" />
        <properties.db2.jcc databaseName="BLUDB"
            portNumber="50000"
            serverName="DB2-SERVER"         
            user="DB2-USER" 
            password="DB2-PASSWORD" />
  </dataSource>
</server>

Next the persistence unit needs to be define in persistence.xml.

The tricky part was for me to figure out the right location for this file. In order for all Maven versions to build it correctly I put it in ‘src/main/resources/META-INF/persistence.xml’. This produces an articles.war file with the internal structure ‘classes/META-INF/persistence.xml’.

<persistence version="2.2"
    xmlns="http://xmlns.jcp.org/xml/ns/persistence" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence 
                        http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd">
    <persistence-unit name="jpa-unit" transaction-type="JTA">
        <jta-data-source>jdbc/articlejpadatasource</jta-data-source>
        <properties>
            <property name="eclipselink.ddl-generation" value="create-tables"/>
            <property name="eclipselink.ddl-generation.output-mode" value="both" />
        </properties>
    </persistence-unit>
</persistence>

Usage of JPA in Java

Once all the configuration has been done, writing the Java code is simple.

First you need to define the Java class which represents the entries in a table. Check out the code of ArticleEntity.java with the five columns id, title, url, author and creation date. As defined in persistence.xml this table is created automatically.

The CRUD operations for articles are defined in ArticleDao.java. The code is pretty straight forward. The only thing that confused me, was that I have to begin and commit transactions manually for the create operation. In the Open Liberty sample this was not necessary. I’m trying to find out what the difference is.

In JPADataAccess.java the logic is implemented to add and read articles. The ArticleDao is injected. Again, the code looks simple. The lesson that I learned here is, that dependency injection only seems to work when the upper layers that invoke this code use dependency injection and @ApplicationScoped as well.

How to run the Example

I’ve written scripts to create the SQL database and create the Articles service. Check out the documentation to run the sample yourself on Minikube or the IBM Cloud Kubernetes Service.

Once installed the OpenAPI API Explorer can be used to create a new article.

The table is displayed in the Db2 console.

The data in the table can be displayed in the console as well.

To learn more about microservices built with Java and MicroProfile, check out the cloud-native-starter repo.

The post Persistence for Java Microservices in Kubernetes via JPA appeared first on Niklas Heidloff.


by Niklas Heidloff at May 21, 2019 03:14 PM

Authorization in Microservices with MicroProfile

by Niklas Heidloff at May 20, 2019 08:55 AM

I’ve been working on an example that demonstrates how to get started with cloud-native applications as a Java developer. The example is supposed to be a full end-to-end sample application which includes the topis authentication and authorization, since that functionality is required by most applications. This article describes how to check authorization in microservices implemented with Java EE and Eclipse MicroProfile.

Get the code of the example application cloud-native-starter from GitHub.

Previously I blogged about how to do authorization with Istio. In general as much as possible of the functionality of the Kubernetes and Istio platforms should be leveraged when building microservices. However, some functionality needs to be implemented in the business logic of the application. One such scenario is fine grained authorization that only the application can determine. For example in a project management application only the application knows the owners of specific tasks.

OpenID Connect and JWT

Before I describe the sample, let me give you some background and explain my requirements.

In order to authenticate and authorize users, I’d like to use the standard OpenID Connect 1.0 and OAuth 2.0 which can be used with many existing identify providers. In the context of enterprise applications you want to leverage existing organization directories. IBM App ID, for example, acts as an identity provider or identity provider proxy. For simple tests you can define test users in a cloud directory. For production usage App ID can be configured to work against third-party providers such as Active Directory Federation Services via SAML.

The other nice thing about OpenID Connect for developers is, that you don’t have to understand the internals of the different identity providers, but can use standardized and easy APIs. As responses of successful OAuth dances, you get access tokens and user tokens as JSON Web Token (JWT).

Cloud-Native Sample Application

There are five services in the application. The services, except of the managed one, are available as open source and run in Kubernetes clusters with Istio. In my case I utilize Minikube locally or the IBM Cloud Kubernetes Service.

  • Web-App: Simple web application built with Vue.js which provides login functionality for users and stores tokens locally
  • Web-App Hosting: Nginx based hosting of the Vue.js resources
  • Authentication: Node.js microservice which handles the OAuth dance and returns tokens to the web application
  • Web-API: Provides an unprotected endpoint ‘/getmultiple’ to read articles and a protected endpoint ‘create’ to create a new article
  • IBM App ID: Contains a cloud directory with test users and acts as an OpenID identity provider

Check out my other article Authenticating Web Users with OpenID and JWT that explains how the tokens are retrieved and how they are stored in the web application.

Authorization via MicroProfile

Eclipse MicroProfile supports controlling user and role access to microservices with JSON Web Token. Let’s take a look at the sample.

From the web application the endpoint ‘/manage’ of the Web API service can be invoked. Only the user ‘admin@demo.email’ is allowed to invoke this endpoint.

For the user ‘user@demo.email’ an error is thrown.

Watch the animated gif to see the flow in action.

This is the Java code that checks authorization:

public class Manage {
   @Inject
   private JsonWebToken jwtPrincipal;

   @POST
   @Path("/manage")
   @Produces(MediaType.APPLICATION_JSON)
   public Response manage() {
      String principalEmail = this.jwtPrincipal.getClaim("email");
      if (principalEmail.equalsIgnoreCase("admin@demo.email")) {
         JsonObject output = Json.createObjectBuilder().add("message", "success").build();
         return Response.ok(output).build();
      }
      else {			
         JsonObject output = Json.createObjectBuilder().add("message", "failure").build();
         return Response.status(Status.FORBIDDEN).entity(output).type(MediaType.APPLICATION_JSON).build();
      }
   }
}

The tricky part to get this working was the configuration of the Liberty server. Thanks a lot to Chunlong Liang for figuring this out.

In order to check the validation of the JWT token, MicroProfile needs to contact App ID via ‘https’. When using Istio to check authorization, this needs to be done too. The difference is that Istio already comes with the public key of App ID. For MicroProfile applications running in Open Liberty the key needs to be imported into the validation keystore first. It sounds like for WebSphere Liberty this is not necessary either, but I haven’t tested it.

<server description="OpenLiberty Server">
    <featureManager>
        <feature>webProfile-8.0</feature>
        <feature>microProfile-2.1</feature>
        <feature>mpJwt-1.1</feature>
        <feature>appSecurity-3.0</feature>
    </featureManager>

    <mpJwt id="jwt"   
        issuer="https://us-south.appid.cloud.ibm.com/oauth/v4/xxx"
        jwksUri="https://us-south.appid.cloud.ibm.com/oauth/v4/xxx/publickeys"
	    userNameAttribute="sub"
	    audiences="ALL_AUDIENCES"/>  

    <sslDefault sslRef="RpSSLConfig"/>
    <ssl id="RpSSLConfig" keyStoreRef="defaultKeyStore" trustStoreRef="validationKeystore"/> 
    <keyStore id="defaultKeyStore" location="keystore.jceks" type="JCEKS" password="secret" />
    <keyStore id="validationKeystore" location="/config/key.jks" type="jks" password="changeit"/>
</server>

In order to import the public App ID key, you need to download the key first. After this you can use keytool to import it:

keytool -import -file /Users/nheidloff/Desktop/wildcardbluemixnet.crt -alias certificate_alias -keystore /Users/nheidloff/git/cloud-native-starter/auth-java-jee/keystore.jks -storepass keyspass

The example application contains this key already. When you want to use another OpenID Connect provider, you need to import the key as just described.

The other issue I ran into was, that App ID doesn’t return an JWT token in the right format for MicroProfile. Fortunately the claims ‘sub’ (subject/user) and ‘audiences’ can be configured in server.xml too.

To run the example yourself, follow these instructions.

The post Authorization in Microservices with MicroProfile appeared first on Niklas Heidloff.


by Niklas Heidloff at May 20, 2019 08:55 AM

QuarkEE - the Java EE-stic quarkus.io

by admin at May 20, 2019 03:31 AM

The opinionated quarkus.io quickstarter (maven archetype):

mvn archetype:generate -DarchetypeGroupId=com.airhacks -DarchetypeArtifactId=quarkee-archetype

creates an empty, ready to use, quarkus project with common extensions (JSON-B, JSON-P, MicroProfile Metrics, Microprofile Fault Tolerance, Swagger (...)) in a Java EE-stic out-of-the-box fashion:

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.

by admin at May 20, 2019 03:31 AM

Jakarta EE / MicroProfile Testing and Quality over Statistics--airhacks.fm Podcast

by admin at May 19, 2019 12:49 PM

Subscribe to airhacks.fm podcast via: spotify| iTunes| RSS

The #37 airhacks.fm episode with Andrew Guibert (@andrew_guibert) about Java EE, Jakarta EE and MicroProfile testing is available for download.

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.

by admin at May 19, 2019 12:49 PM

Update for Jakarta EE community: May 2019

by Tanja Obradovic at May 18, 2019 10:46 AM

The Jakarta EE community is the driving force behind the future of cloud-native Java. Active participation represents the best way to drive the vendor-neutral and rapid innovation necessary to modernize enterprise systems for cloud use cases. That said, we’d like to make sure that the community is kept up-to-speed with the latest developments in the Jakarta EE ecosystem.

We’re launching a monthly email update for the Jakarta EE community which seeks to highlight news from various committee meetings related to this platform. There are a few ways to get a grip on the work that has been invested in Jakarta EE so far, so if you’d like to learn more about Jakarta EE-related plans and get involved in shaping the future of cloud-native Java, read on. We’d also like to use this opportunity to invite you to get involved in EE4J projects and join the conversation around the Jakarta EE Platform.

Without further ado, let’s have a look at what has happened this month:

Update on Jakarta EE Rights to Java Trademarks

The process of migrating Java EE to the Eclipse Foundation has been a collaborative effort between the Eclipse Foundation staff and the many contributors, committers, members, and stakeholders that are participating. The Eclipse Foundation and Oracle have agreed that the javax package namespace will not be evolved by the Jakarta EE community. Furthermore, Java trademarks such as the existing specification names will not be used by Jakarta EE specifications.

Since the ratified Jakarta EE specifications will be available under a different license (the Eclipse Foundation Specification License), we recommend that you update your contributor and committer agreements.

Read more about the implications and what’s next for the Jakarta EE Working Group in Mike Milinkovich’s latest blog.

In order to evolve Jakarta EE, we must transition to a new namespace. In an effort to bootstrap the conversation, the Jakarta EE Specification Committee has prepared two proposals (Big-bang Jakarta EE 9, Jakarta EE 10 new features and incremental change in Jakarta EE 9 and beyond) on how to make the move into the new namespace smoother. These proposals represent a starting point, but the community is warmly invited to submit more proposals.

Community discussion on how to transition to the jakarta namespace will conclude Sunday, June 9th, 2019.

EFSP v1.1

Version 1.1 of the Eclipse Foundation Specification Process was approved on March 20, 2019. The EFSP leverages and augments the Eclipse Development Process (EDP), which defines important concepts, including the Open Source Rules of Engagement, the organizational framework for open source projects and teams, releases, reviews, and more.
 

JESP v1.0

Jakarta EE Specification Process v1.0 was approved on April 3, 2019. Therefore, the Jakarta EE Specification Committee now adopts the EFSP v1.1 as the Jakarta EE Specification Process with a few modifications, including the fact that any changes or revisions of the Jakarta EE Specification Process must be approved by a Super-majority of the Specification Committee.

 

TCK process:

Work on the TCK process is in progress, with Tomitribe CEO David Blevins leading the effort. The TCK process is expected to be completed in the near future. The document will shed light on aspects such as the materials a TCK must possess in order to be considered suitable for delivering portability, the process for challenging tests and how to resolve them and more.      
 

Jakarta EE 8 release

Jakarta EE 8 is a highly-anticipated release, especially since it represents the first release that’s completely based on Java EE to ensure backward compatibility. It relies on four pillars of work, namely specifications for the full platform, TCKs, including documents on how to use them, a compatible implementation for the release of Jakarta EE 8, and marketing aspects such as branding, logo usage guidelines, and marketing and PR activities.

All parties involved are far along with the planning process and work on specifications has already started. Please look at Wayne Beaton’s blogs on the work in progress with regard to specification project names and specification scopes.

 

EE4J GitHub

Get involved in Eclipse EE4J! There are currently three projects that you can be a part of, namely Specification Document Names, Jakarta Specification Project Names, and Jakarta Specification Scope Statements (for the specifications). Furthermore, there are plenty of repos that require your attention and involvement.

But before you dive right in, you should read the latest blog from the Jakarta EE Specification committee, which recently approved a handful of naming standards for Jakarta EE Specification projects. While you’re at it, you should read Wayne Beaton’s blog on why changing the names of the specifications and the projects that contain their artifacts is a necessary step.

Head over to GitHub and join the conversation!
 

Jakarta EE Platform

There’s no better time to get involved in the work for the Jakarta EE Platform than the present. As of now, the projects that demand the community’s attention are the Jakarta EE 8 Platform Specification, which is meant to keep track of the work involved with creating the platform specification for Jakarta EE 8, Jakarta EE 9 Platform Specification, intended to keep track of the work involved with creating the platform specification for Jakarta EE 9 and Jakarta EE.Next Roadmap Planning, which seeks to define a roadmap and plan for the Jakarta EE 9 release.

Community Engagement

Speaking of community engagement, there are a few ways to get a grip on the work that has been invested in Jakarta EE so far, learn more about Jakarta EE-related plans and get involved in shaping the future of cloud-native Java. One way to do that is by reading Tanja Obradovic’s blog series on how to get involved.

You should also be aware of the newly-created Jakarta EE community calendar, which is now open to the public and offers an overview of all the activities surrounding Jakarta EE. The community is invited to participate in Jakarta Tech Talks, which take place on a monthly basis, attend Jakarta EE Update monthly calls (the next one is on May 8), help build the Jakarta EE wiki with all relevant links and look for opportunities to engage and become part of the community.

Last but not least, the Jakarta EE Developer Survey will be released in the next few days. Head over to jakarta.ee to discover the latest trends, the community’s top priorities regarding the future of Jakarta EE and more. Stay tuned!

Conclusion:

Thank you for your interest in Jakarta EE. To help us build tomorrow’s enterprise Java platform, join the Jakarta EE community now or get involved by becoming a contributor or committer to one of the EE4J projects.   

Help steer Jakarta EE toward its exciting future by joining the Jakarta EE working group!


by Tanja Obradovic at May 18, 2019 10:46 AM

I am an Incrementalist: Jakarta EE and package renaming

by BJ Hargrave (noreply@blogger.com) at May 17, 2019 05:11 PM


Eclipse Jakarta EE has been placed in the position that it may not evolve the enterprise APIs under their existing package names. That is, the package names starting with java or javax. See Update on Jakarta EE Rights to Java Trademarksfor the background on how we arrived at this state.

So this means that after Jakarta EE 8 (which is API identical to Java EE 8 from which it descends), whenever an API in Jakarta EE is to be updated for a new specification version, the package names used by the API must be renamed away from java or javax. (Note: some other things will also need to be renamed such as system property names, property file names, and XML schema namespaces if those things start with java or javax. For example, the property file META-INF/services/javax.persistence.PersistenceProvider.) But this also means that if an API does not need to be changed, then it is free to remain in its current package names. Only a change to the signature of a package, that is, adding or removing types in the package or adding or removing members in the existing types in the package, will require a name change to the package.

There has been much discussion on the Jakarta EE mail lists and in blogs about what to do given the above constraint and David Blevins has kindly summed up the two main choices being discussed by the Jakarta EE Specification Committee: https://www.eclipse.org/lists/jakartaee-platform-dev/msg00029.html.

In a nutshell, the two main choices are (1) “Big Bang” and (2) Incremental. Big Bang says: Let’s rename all the packages in all the Jakarta EE specifications all at once for the Jakarta EE release after Jakarta EE 8. Incremental says: Let’s rename packages only when necessary such as when, in the normal course of specification innovation, a Jakarta EE specification project wants to update its API.

I would like to argue that Jakarta EE should chose the Incremental option.

Big Bang has no technical value and large, up-front community costs.

The names of the packages are of little technical value in and of themselves. They just need to be unique and descriptive to programmers. In source code, developers almost never see the package names. They are generally in import statements at the top of the source file and most IDEs kindly collapse the view of the import statements so they are not “in the way” of the developer. So, a developer will generally not really know or care if the Jakarta EE API being used in the source code is a mix of package names starting with java or javax, unchanged since Jakarta EE 8, and updated API with package names starting with jakarta. That is, there is little mental cost to such a mixture. The Jakarta EE 8 API are already spread across many, many package names and developers can easily deal with this. That some will start with java or javax and some with jakarta is largely irrelevant to a developer. The developer mostly works with type and member names which are not subject to the package rename problem.

But once source code is compiled into class files, packaged into artifacts, and distributed to repositories, the package names are baked in to the artifacts and play an important role in interoperation between artifacts: binary compatibility. Modern Java applications generally include many 3rdparty open source artifacts from public repositories such as Maven Central and there are many such artifacts in Maven Central which use the current package names. If Jakarta EE 9 were to rename all packages, then the corpus of existing artifacts is no longer usable in Jakarta EE 9 and later. At least not without some technical “magic” in builds, deployments, and/or runtimes to attempt to rename package references on-the-fly. Such magic may be incomplete and will break jar signatures and will complicate builds and tool chains. It will not be transparent.

Jakarta EE must minimize the inflection point/blast radius on the Java community caused by the undesired constraint to rename packages if they are changed. The larger the inflection point, the more reason you give to developers to consider alternatives to Jakarta EE and to Java in general. The Incremental approach minimizes the inflection point providing an evolutionary approach to the package naming changes rather than the revolutionary approach of the Big Bang.

Some Jakarta EE specification may never be updated. They have long been stable in the Java EE world and will likely remain so in Jakarta EE. So why rename their packages? The Big Bang proposal even recognizes this by indicating that some specification will be “frozen” in their current package names. But, of course, there is the possibility that one day, Jakarta EE will want to update a frozen specification. And then the package names will need to be changed. The Incremental approach takes this approach to all Jakarta EE specifications. Only rename packages when absolutely necessary to minimize the impact on the Java community.

Renaming packages incrementally, as needed, does not reduce the freedom of action for Jakarta EE to innovate. It is just a necessary part of the first innovation of a Jakarta EE specification.

A Big Bang approach does not remove the need to run existing applications on earlier platform versions.  It increases the burden on customers since they must update all parts of their application for the complete package renaming when the need to access a new innovation in a single updated Jakarta EE specification when none of the other Jakarta EE specifications they use have any new innovations. Just package renames for no technical reason.  It also puts a large burden on all application server vendors. Rather than having to update parts of their implementations to support the package name changes of a Jakarta EE specification when the specification is updated for some new innovation, they must spend a lot of resources to support both old and new packages name for the implementations of all Jakarta EE specifications.

There are some arguments in favor of a Big Bang approach. It “gets the job done” once and for all and for new specifications and implementations the old java or javax package names will fade from collective memories. In addition, the requirement to use a certified Java SE implementation licensed by Oracle to claim compliance with Eclipse Jakarta EE evaporates once there are no longer any java or javax package names in a Jakarta EE specification. However, these arguments do not seem sufficient motivation to disrupt the ability of all existing applications to run on a future Jakarta EE 9 platform.

In general, lazy evaluation is a good strategy in programming. Don’t do a thing until the thing needs to be done. We should apply that strategy in Jakarta EE to package renaming and take the Incremental approach. Finally, I am reminded of Æsop’s fable, The Tortoise & the Hare. “The race is not always to the swift.”


by BJ Hargrave (noreply@blogger.com) at May 17, 2019 05:11 PM

Dead javax, Singleton performance, exactly once, DB authentication, refresh tokens, Kafka, distributed failures--62nd airhacks.tv

by admin at May 15, 2019 08:40 AM

62nd airhacks.tv episode with the following topics:
"javax and Jakarta EE's future, singleton performance, exactly once delivery, DB authentication and refresh tokens, Kafka Java EE integration, distributed failures with microprofile, openjdk, oauth and refresh tokens, JSF and memory, green field architectures, javafx, embedded space, and interactive code review":
Any questions left? Ask now: and get the answers at the next airhacks.tv. See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.

by admin at May 15, 2019 08:40 AM

[EN] Simple @JsonbCreator example

by Altuğ Bilgin Altıntaş at May 14, 2019 08:00 PM

Here is a simple scenario;  I will call a rest URL with POST with curl and system will create the entity object on the fly. curl -H 'Content-Type:application/json' -d '{"number":23, "numberOfSeats":"23"}' -X POST http://localhost:8080/airport/resources/flights Let’s start with the boundary layer @Stateless @Path("flights") public class FlightsResource...

by Altuğ Bilgin Altıntaş at May 14, 2019 08:00 PM

Using ConfigMaps To Configure MicroProfile Applications

by admin at May 14, 2019 04:48 AM

Injecting values from ConfigMap into a MicroProfile (Configuration) / Java EE application. The project was created with Java EE 8 / MicroProfile essentials archetype and deployed with payara-s2i image to OpenShift:

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.

by admin at May 14, 2019 04:48 AM

Renaming Jetty from javax.* to jakarta.*

by gregw at May 13, 2019 07:20 AM

The Issue The Eclipse Jakarta EE project has not obtained the rights from Oracle to extend the Java EE APIs living in the javax.* package. As such, the Java community is faced with a choice between continuing to use the

by gregw at May 13, 2019 07:20 AM

javax and future of Jakarta EE, TX, quarkus, startup, Java FX, MicroProfile, openJDK support, Green Field Architectures--or 62nd airhacks.tv

by admin at May 13, 2019 07:09 AM

Topics for the 62nd airhacks.tv: https://gist.github.com/AdamBien/001c1bad3f868a8508783569e192ea3d:
  1. Cloudy airhacks
  2. Jakarta EE and the javax issue (see post) and the future of Jakarta EE
  3. It it worth to use @Singleton
  4. Server-specific injection and server detection
  5. Exactly once delivery with Java EE without XA
  6. Fetching a principal from a database
  7. persistence.xml location
  8. Jakarta EE with Kafka
  9. Dealing with distributed system failures with or without MicroProfile
  10. openjdk compatibility concerns
  11. oauth implementation and refresh tokens
  12. green field architectures discussions (openshift, kubernetes, docker etc.)
  13. understanding existing code bases
  14. handing viewscoped in JSF
  15. Java FX and embedded space
  16. @Counted and @Named MicroProfile bug
  17. Thoughts on quarkus and specifications

Ask questions during the show via twitter mentioning me: http://twitter.com/AdamBien (@AdamBien) or using the hashtag: #airhacks. You can join the Q&A session live each first Monday of month, 6 P.M at airhacks.tv or http://www.ustream.tv/channel/adambien

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.

by admin at May 13, 2019 07:09 AM

Java Native Database--Airhacks.fm Podcast

by admin at May 12, 2019 06:51 PM

Subscribe to airhacks.fm podcast via: spotify| iTunes| RSS

An airhacks.fm conversation with Markus Kett (@MarkusKett) about:

C64 and sports games, Weiden is not in Bavarian Forest, soccer as motivation for programming, writing first programs in basic with 17, writing contacts management, PCs are boring machines, but good for business, Java is the best programming language, Pentium 1 was introduced at CEBIT in 1993, the dream about an own booth at CEBIT came true, webdesign software based on applets (XPage) was very successful at SYSTEMS in Munich, Markus was the business man and had no time for programming - like Steve Jobs, self-financing with selling products, competing with Microsoft and Adobe, writing a 4GL Java-based development environment like Visual Basic called XDev, Java Developers don't like the Drag and Drop programming experience, building an IDE from scratch, discussions with Sun Microsystems about StarOffice integration, migrating from Swing to SWT and Eclipse, using Vaadin as UI technology, connecting beautiful UI to DB was too hard, databases have more types than Java what makes code generation hard, in 4GL the database comes first, RapidEclipse is free but commercial support is available, XDev provides tool and project support, RapidClipse understands rich database types and generates JPA POJOs, Hibernate importer, how to write queries in Java, implementing JPA-SQL is based on xtext by itemis and generates JPA-QL from SQL, storing data is still too complicated, serialization looked promising but was too unsecure and only entire objects can be serialized, Kryo, Fast Serializer, JetStream (renamed to Microstream) serializer, the database engine stores objects in any file storage, there is no impedance mismatch, the native Java storage engine, queries are performed with Java 8+ streams, JCA connector passes transactions and security context to the application server, JCA prototypical implementation, kubernetes persistent volumes, Bavarian Forrest is like Canada, the largest walking robot, Roding race car, being a TV host on Giga, constant 30k downloads and the XDev TV, DVDs were more successful than TV, JCon and the coding keynote, Java EE as secret weapon at JCon, stealing (adapting) the "no slides" ideas, the world first free, physical, Java magazine JAVAPRO with 8500 readers, community prefers Java-only conference,
Markus Kett on twitter: @MarkusKett. JetStream was renamed to MicroStream.

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.

by admin at May 12, 2019 06:51 PM

The Cloud Native Imperative — Results from the 2019 Jakarta EE Developer Survey

by Mike Milinkovich at May 10, 2019 03:17 PM

The results of the 2019 Jakarta EE Developer Survey are out. Almost 1,800 Java developers from around the world have spoken. Taken together with the engagement and response to my recent posts on the future of Jakarta EE (see my latest blog here), the survey makes clear the developer community is focused on charting a new course for a cloud native future, beginning with delivering Jakarta EE 8. The Java ecosystem has a strong desire to see Jakarta EE, as the successor to Java EE, continue to evolve to support microservices, containers, and multi-cloud portability.

Organized by the Jakarta EE Working Group, the survey was conducted over three weeks in March 2019. Just like last year (see the 2018 results here), Jakarta EE member companies promoted the survey in partnership with the London Java Community, Java User Groups, and other community stakeholders. Thank you to everyone who took the time to participate. Access the full findings of the survey here.

Some of the highlights from this year’s survey include:

  • The top three community priorities for Jakarta EE are: better support for microservices, native integration with Kubernetes (tied at 61 percent), followed by production quality reference implementations (37 percent). To move mission-critical Java EE applications and workloads to the cloud, developers will need specifications, tools, and products backed by a diverse vendor community. Jakarta EE Working Group members have committed to deliver multiple compatible implementations of the Jakarta EE 8 Platform when the Jakarta EE 8 specifications are released.
  • With a third of developers reporting they are currently building cloud native architectures and another 30 percent planning to within the next year, cloud native is critically important today and will continue to be so;
  • The number of Java applications running in the cloud is projected to substantially increase, with 32 percent of respondents expecting that they will be running nearly two-thirds of their Java applications in the cloud within the next two years;
  • Microservices dominates as the architecture approach to implementing Java in the cloud, according to 43 percent of respondents;
  • Spring/Spring Boot again leads as the framework chosen by most developers for building cloud native applications in Java;
  • Eclipse Microprofile’s adoption has surged, with usage growing from 13 percent in 2018 to 28 percent today;
  • Java continues to dominate when it comes to deploying applications in production environments. It comes as no surprise that most companies are committed to protecting their past strategic investments in Java.

Once again, thanks to everyone who completed the survey and to the community members for their help with the promotion.

Let me know what you think about this year’s survey findings. We are open to suggestions on how we can improve the survey in the future, so please feel free to share your feedback.


by Mike Milinkovich at May 10, 2019 03:17 PM

The Cloud is Driving the Future of the Java Ecosystem and Jakarta EE: Eclipse Foundation Survey Results

by Debbie Hoffman at May 09, 2019 02:54 PM

The 2019 Jakarta EE developer survey results are in - and they show cloud deployments have increased since last year with 62% of Java developers currently building or planning cloud native architectures within the year.


by Debbie Hoffman at May 09, 2019 02:54 PM

Frequently Asked Questions About Jakarta EE 8

by Mike Milinkovich at May 08, 2019 12:00 PM

I’d like to thank the community for the level of engagement we’ve seen in response to my post from last week.   This post, which again represents the consensus view of the Jakarta EE Steering Committee, answers some questions about Jakarta EE 8, which is planned as the initial release of Jakarta EE, and is intended to be fully compatible with Java EE 8, including use of the javax namespace.   We thought it would be useful to reiterate the messages we have been delivering about this release.

Note that this post is not about future Jakarta releases where the namespace will be changed. There is a vigorous discussion going on right now on the jakarta-platform-dev@eclipse.org list (archive), so if you are interested in that topic, I would suggest you participate there. We expect that it will be about a month before the Jakarta EE Spec Committee will determine the next steps in the Jakarta EE roadmap.

Will Jakarta EE 8 break existing Java EE applications that rely upon javax APIs?

No, Jakarta EE 8 will not break existing existing Java EE applications that rely upon javax APIs.   We expect Jakarta EE 8 to be completely compatible with Java EE 8. We expect Jakarta EE 8 to specify the same javax namespace, and the same javax APIs and the same behavior as is specified in Java EE 8.    We expect that implementations that pass the Java EE 8 TCKs will also pass the Jakarta EE 8 TCKs, because the Jakarta EE 8 TCKs will be based on the same sources as the Java EE 8 TCKs. Jakarta EE 8 will not require any changes to Java EE 8 applications or their use of javax APIs.

What will Jakarta EE 8 consist of?

The Jakarta EE 8 specifications will:

  • Be fully compatible with Java EE 8 specifications
  • Include the same APIs and Javadoc using the same javax namespace
  • Provide open source licensed Jakarta EE 8 TCKs that are based on, and fully compatible with, the Java EE 8 TCKs.
  • Include a Jakarta EE 8 Platform specification that will describe the same platform integration requirements as the Java EE 8 Platform specification.
  • Reference multiple compatible  implementations of the Jakarta EE 8 Platform when the Jakarta EE 8 specifications are released.
  • Provide a compatibility and branding process for demonstrating that implementations are Jakarta EE 8 compatible.

Will there be Jakarta EE 8 compatible implementations?

Yes.  Multiple compatible implementations of the Jakarta EE 8 Platform will be available when the Jakarta EE 8 specifications are released.  We expect that any Java EE 8 compatible implementation would also be Jakarta EE 8 compatible, and the vendors in the Jakarta EE Working Group intend to certify their Java EE 8 compatible implementations as Jakarta EE 8 compatible.  In addition, because the Jakarta EE TCKs are available under an open source license, we will “lower the bar” for other technology providers to demonstrate Jakarta EE compatibility for their implementations. The lower cost and more liberal Jakarta EE trademark licensing will allow more technology providers to leverage and strengthen the Jakarta EE brand in the Enterprise Java community.  Jakarta EE 8 will provide a new baseline for the evolution of the Jakarta EE technologies, under an open, vendor-neutral community-driven process.

What is the process for delivery of Jakarta EE 8

The process for delivery of Jakarta EE 8 specifications will be fully transparent and will follow the Jakarta EE Specification Process.  Expect to see in coming weeks the delivery of initial, draft Jakarta EE 8 component specifications corresponding to Java EE 8 component specifications.  These will contain Javadoc defining the relevant APIs, and TCKs for compatibility testing. To publish specification text, we need to acquire copyright licenses for this text.  We have obtained Oracle and IBM’s copyright licenses for their  contributions, and intend to obtain the remaining copyright licenses required to publish the text of the Jakarta EE 8 Platform specification, and as much as possible of the component specifications. If you contributed to the Java EE specifications at the JCP in the past, expect to be contacted by the Eclipse Foundation to provide a license to use your contributions in Jakarta EE going forward. Providing such a license will be an important step in supporting the new specification process and the Jakarta EE community.  You will see these draft specifications evolve to final specifications in an open community process. Join the specification projects and participate!

When will Jakarta EE 8 be delivered?

The Jakarta EE Working Group intends to release final Jakarta EE 8 specifications by the fall of 2019.    This is an open community-driven effort, so there will be transparency into the process of driving the Jakarta EE 8 specifications, delivery of the Jakarta EE 8 TCKs, and Jakarta EE 8 compatible implementations.


by Mike Milinkovich at May 08, 2019 12:00 PM

Transitioning Jakarta EE to the “jakarta” namespace

by Ivar Grimstad at May 07, 2019 11:55 AM

As described in Jakarta Going Forward, we need to transition the Jakarta EE specifications to the jakarta.* namespace/base package. After long and intense discussions in the Jakarta EE Specification, we have proposed two possible ways forward to kick-start the discussions on this thread.

In this post, I am highlighting some of the content of the initial post to the mailing list for reference.

Proposal 1: Big-bang Jakarta EE 9, Jakarta EE 10 New Features

The heart of this proposal is to do a one-time move of API source from the javax.* namespace to the jakarta.* namespace with the primary goal of not prolonging industry cost and pain associated with the transition.

https://www.eclipse.org/lists/jakartaee-platform-dev/msg00029.html

Proposal 2: Incremental Change in Jakarta EE 9 and beyond

Evolve API source from javax.* to the jakarta.* namespace over time on an as-needed basis. The most active specifications would immediately move in Jakarta EE 9. Every Jakarta EE release, starting with version 10 and beyond may involve some javax.* to jakarta.* namespace transition.

https://www.eclipse.org/lists/jakartaee-platform-dev/msg00029.html

Other Proposals

Other proposals should incorporate the following considerations and goals:

The new namespace will be jakarta.*

APIs moved to the jakarta.* namespace maintain class names and method signatures compatible with equivalent class names and method signatures in the javax.* namespace.

Even a small maintenance change to an API would require a javax.* to jakarta.* change of that entire specification. Examples include:
– Adding a value to an enum
– Overriding/adding a method signature
– Adding default methods in interfaces
– Compensating for Java language changes

Binary compatibility for existing applications in the javax.* namespace is an agreed goal by the majority of existing vendors in the Jakarta EE Working Group and would be a priority in their products. However, there is a strong desire not to deter new implementers of the jakarta.* namespace from entering the ecosystem by requiring they also implement an equivalent javax.* legacy API.

There is no intention to change Jakarta EE 8 goals or timeline.

Community discussion on how to transition to the jakarta.* namespace will conclude Sunday, June 9th, 2019.

https://www.eclipse.org/lists/jakartaee-platform-dev/msg00029.html

Contribute

There are already a lot of contributions and lively discussions going on. Please make sure you join the Jakarta EE Platform Developer Discussions mailing list https://accounts.eclipse.org/mailing-list/jakartaee-platform-dev to take part in the conversation. At the time of writing this post, the number of subscribers to the list has more than doubled! Another proof of the passion and commitment in the Jakarta EE community!


by Ivar Grimstad at May 07, 2019 11:55 AM

Java EE, Jakarta EE and the Dead "javax"

by admin at May 07, 2019 09:38 AM

Eclipse Foundation won't get the rights to use Oracle's Java trademarks with the following implications:
"...
  1. The javax package namespace may be used within Jakarta EE specifications but may be used “as is” only. No modification to the javax package namespace is permitted within Jakarta EE component specifications. Jakarta EE specifications that continue to use the javax package namespace must remain TCK compatible with the corresponding Java EE specifications.
  2. Jakarta EE component specifications using the javax package namespace may be omitted entirely from future Jakarta EE Platform specifications.
  3. Specification names must be changed from a “Java EE” naming convention to a “Jakarta EE” naming convention. This includes acronyms such as EJB, JPA or JAX-RS.
..."
[from https://eclipse-foundation.blog/2019/05/03/jakarta-ee-java-trademarks/].

Trademarks / licensing issues are quite complex, if you are interested in some background, listen to airhacks.fm episode: #13 From Java EE over EE4j to Jakarta EE with Mike Milinkovich

The javax namespace issue was known for years (see e.g. Reza's Joint Community Open Letter on Java EE Naming and Packaging), now we have a clear resolution. All the Java EE specifications / projects are going to be renamed with the "Jakarta" prefix (see Renaming Java EE Specifications for Jakarta EE) anyway.

Consistency, clarity and simplicity are crucial for the success of Jakarta EE. A clear cut e.g. renaming all packages from javax to e.g. jakarta would introduce a consistent look and feel and branding. A single package strategy is better, than a mix of javax and jakarta namespaces.

Forcing projects to migrate (=search "javax" and replace with "jakarta") or introducing breaking changes every 20 years (J2EE 1.2 was introduced in December 12, 1999) is acceptable. Such a migration could even introduce an opportunity to remove superfluous patterns, layers, indirections and libraries.


by admin at May 07, 2019 09:38 AM

Transitioning Java EE to the Jakarta EE namespace

by Edwin Derks at May 07, 2019 04:10 AM

A few days ago, the Eclipse Foundation has announced on their blog that the Java brand is no longer allowed in future versions of the Jakarta EE platform. That means that Oracle allows Jakarta EE to use the Java EE related code and artificats as-is, until a modification occurs on these items from where they must be rebranded to the Jakarta EE brand. Knowing the situation of Oracle moving away from Java EE while keeping the brand’s name and logo, this really didn’t come as a surprise to me. Actually, I think it was a job well done by both the negotiators from Eclipse and Oracle to get this out of the negotiatons.

What did surprise me, is mostly the reactions to this on Twitter. Several people were against this, sharing their disagreement, even have called it a ‘debacle’. I have only seen few people like me that were relevied that a decision was made in the first place, and take it up from there. In my personal opinion, this situation was inevitable and would surface at some moment in time, which apparently was at moment of the blog post’s announcement. Am I really the only one who was not surprised?

In any case, from my point of view, what does it mean for me as a Jakarta EE transitioning developer? It means roughly that I (maybe among other changes) will have to change my Maven artifact's names to the Jakarta branded versions, and change the imports of my Java code to the jakarta.* namespace. The Jakarta framework will at that time probably be in some hybrid situation, supporting both Java EE and Jakarta EE specifications. Of course: this is not going to be an ideal situation. But remember that Jakarta EE is going to be compatible with Java EE 8 for a while. Performing the transition during this period should have the least impact.

This is a hurdle that I, and my fellow developers alike, will have to overcome. Simple because that’s the decision that has been made, and we have to live with that. But if you look at the big picture, is this transition actually such an interesting phenomenon? I don’t think so, because after the transition, Jakarta EE will fall completely in line with any other Java based enterprise development framework which is also not allowed to use the Java brand in their own code and brand. Jakarta EE will therefore become a self-maturing framework that happens to run on Java, and suffer the same evolutionary consequenses of that language like any other Java-based framework.

So please, dear Jakarta EE community, unite and embrance this transition. Let’s pick up the glove and make this thing happen. We have work to do…


by Edwin Derks at May 07, 2019 04:10 AM

80% Code Coverage is Not Enough--Airhacks.fm Podcast

by admin at May 05, 2019 04:09 PM

Subscribe to airhacks.fm podcast via: spotify| iTunes| RSS

An airhacks.fm conversation with James Wilson (@jgwilson42) about:

the result of pressing the break button on a BBC computer, and ZX Spectrum, Space Invaders with Basic, extending minecraft with Java, accidental tester career, best interviewees got programmer jobs, hackers and testers, developers like the happy path, unit test coverage is useless without good asserts, is 80% code coverage a valuable target?, code coverage was used as a motivation for writing tests, reflection utilities to increase code coverage, getters / setters never brake, Code as a Crime Scene book, methods longer than a screen are problematic, the ratio between trivial and good asserts, a good javadoc and unit tests follow similar principles, system tests are the most important one, unit testing is good for checking error scenarios, the more tests you have, the easier it is to locate errors, the Law of Triviality requires standard names for test categories, integration testing and system testing, reusing system tests as clients and stress tests, UK retailer goes down, take the max load and double it, jbmc is bytecode verification tool, diffblue cover generates unit tests, generating unit tests quickly for legacy backends, playground, What is the AI in “AI for Code”? blogpost, diffblue blog, @diffbluehq
James Wilson on twitter: @jgwilson42.

Checkout: javaeetesting.com - the online test about Unit-, Integration-, and Stress Testing and see you at airhacks.com.

by admin at May 05, 2019 04:09 PM

Jakarta Going Forward

by Ivar Grimstad at May 05, 2019 06:03 AM

The agreement between the Eclipse Foundation and Oracle regarding rights to Java trademarks has been signed! This is truly an important milestone for Jakarta EE since we will now be able to move forward with Jakarta EE.

As outlined in https://eclipse-foundation.blog/jakarta-ee-java-trademarks, there are two major areas of impact on the Jakarta EE projects:

  • Java Trademarks
  • The javax.* Namespace

Java Trademarks

One part of the agreement is regarding the use of Java trademarks. The implications for Jakarta EE is that we have to rename the specifications and the specification projects. This work is ongoing and is tracked in our specification renaming board on GitHub. The EE4J PMC has published the following Naming Standard for Jakarta EE Specifications in order to comply with the trademark agreement.

The javax Namespace

The major topic of the agreement is around the use of the javax namespace. The agreement permits Jakarta EE specifications to use the javax namespace as is only. Changes to the API must be made in another namespace.

While the name changes can be considered cosmetic changes, the restrictions on the use of the javax.* namespace come with some technical challenges. For example, how are we going to preserve backwards compatibility for applications written using the javax.* namespace?

The Jakarta EE Specifications Committee has come up with the following guiding principle for Jakarta EE.next:

Maximize compatibility with Jakarta EE 8 for future versions without stifling innovation.

With the restrictions on the use of the javax.* namespace, it is necessary to transition the Jakarta EE specifications to a new namespace. The Jakarta EE Specification Committee has decided that the new namespace will be jakarta.*.

How and when this transition should happen is now the primary decision for the Jakarta EE community to make. There are several possible ways forward and the forum for these discussions is the Jakarta EE Platform mailing list.

Mailing List: jakartaee-platform-dev@eclipse.org

Please make sure that you subscribe to the mailing list and join in on the discussion. We hope that we will be able to reach some form of consensus within a month that can be presented to the Specification Committee for approval.

An Opportunity

While the restrictions on the use of Java trademarks and the javax.* namespace impose both practical as well as technical challenges, it is also an opportunity to perform some housekeeping.

By renaming the specifications, we can get a uniform, homogeneous naming structure for the specifications that makes more sense and is easier on the tongue than the existing. By having clear and concise names, we may even get rid of the need for abbreviations and acronyms.

The shift from javax.* to jakarta.* opens up for the possibility to differentiate the stable (or legacy) specifications that have played their role from the ones currently being developed.


by Ivar Grimstad at May 05, 2019 06:03 AM

Thoughts about Jakarta EE future without ‘javax’

by dmitrykornilov at May 03, 2019 06:14 PM

This week Mike Milinkovich announced that Oracle and the Eclipse Foundation agreed that the javax package cannot be evolved by Jakarta EE community and Java trademarks cannot be used in Jakarta EE specifications. How critical is it to Jakarta EE community? Can Jakarta EE survive without javax namespace? Here are my thoughts about it.

For sure, it would be much better to evolve existing APIs in javax packages without any restrictions. But we have what we have and I am not going to do complaining and blaming here. There were reasons to do it this way. On the other hand, finally, the uncertainties with Java trademarks are gone. It’s very important because Jakarta EE progress is not blocked anymore. Javax package restrictions draw a clear line separating Java EE and Jakarta EE, separating past and future. Javax becomes a legacy. All innovations will belong to jakarta namespace. Now it’s clear that javax packages cannot be modified and community needs to find a way how to evolve specifications. And there are some options how it can be done. We need to maximize compatibility with Jakarta EE 8 for future versions without stifling innovation. It’s what Jakarta EE Spec Committee agreed on.

In my opinion the best would be to make a big-bang javax->jakarta package rename to untie the community hands and allow modifications and APIs evolution. It will break the backwards compatibility which was always an important part of Java EE platform and we should not forget about it. There are thousands of Java EE applications and it won’t be wise to remove backwards compatibility requirements. A good option is to create a special backwards compatibility profile in Jakarta EE platform. This profile should contain a frozen Java EE 8 APIs and will allow to run Java EE 8 applications on future versions of Jakara EE Platform. This profile can be optional to allow new potencial Jakarta EE vendors concentrate only on innovations, but I am sure that all big players such Oracle and IBM will support it anyway.

This kind of solution is not new for the industry. For example, in 2006 Sony released PlayStation 3 system which used new architecture and was not compatible with the previous PlayStation 2 system on the hardware level. They solved it by adding PS2 chip to the first versions of PS3 consoles allowed to run PS2 games on it.

Another sample is a process of changing CPU in Apple Macintosh computers from PowerPC to Intel. They provided a simulator allowing running PowerPC application on new Intel based computers for some limited time until most of the applications migrated to the new platform.

How the backwards compatibility can be implemented technically? One of the obvious and straightforward solutions is supplying two implementations: one is supporting javax and and another supporting jakarta. Javax implementations are already exist as part of Java EE 8. Jakarta implementations can be created by forking javax implementations and make necessary modifications.

Another way is patching application binaries at runtime or build time. Runtime solution can be accomplished using JavaAgent and build time via tooling and build plugins.

To simplify migration to jakarta package on the source level, the community may think of creating IDE plugins replacing javax with jakarta the clever way with one click.

I am working in different Jakarta EE committees and see the intention of participants to remain committed to Jakarta EE work, finish Jakarta EE 8 and push it forward to provide a robust, compatible and innovative enterprise platform.


by dmitrykornilov at May 03, 2019 06:14 PM

Jakarta EE 8 and Beyond

by Steve Millidge at May 03, 2019 01:10 PM

Today the Eclipse Foundation have announced an Update on Jakarta EE Rights to Java Trademarks which has dramatic implications for the future of Java EE and Jakarta EE. The Payara team have only recently learned about this - so we thought we would blog about how we feel this impacts customers and users of the Payara Platform. We'll also give our thoughts on how Jakarta EE should evolve given the constraints outlined in Mike Milinkovich's blog from the Eclipse Foundation.


by Steve Millidge at May 03, 2019 01:10 PM

Update on Jakarta EE Rights to Java Trademarks

by Mike Milinkovich at May 03, 2019 10:00 AM

Summary of progress to date and implications of the agreement between Eclipse and Oracle on Jakarta EE and use of Java trademarks and the javax namespace.

Introduction

The migration of Java EE to the Eclipse Foundation has been an enormous effort on behalf of the Eclipse Foundation staff and the many contributors, committers, members, and stakeholders that are participating.

This post was reviewed and represents the consensus view of the Jakarta EE Steering Committee.

Earlier this year GlassFish 5.1 was certified at Eclipse using the Java EE 8 TCK at the Eclipse Foundation. Since then under the direction of the working group the community established a Jakarta EE Specification Process (JESP) for the evolution of the Jakarta EE specs at the Eclipse Foundation. Specification projects are being created for all of the Jakarta EE specifications. The TCK process is being refined for Jakarta EE in concert with the new Jakarta EE compatibility logo. This is all being done in support of the Jakarta EE 8 release.

Progress to Date

The Jakarta community has been busy.

  • Oracle contributed GlassFish and the Java EE APIs and TCKs to Jakarta EE.
  • The Jakarta EE Working Group was formed and supporting committees to provide governance to the community and facilitate collaboration.
  • Eclipse GlassFish was certified with the Java EE TCK at the Eclipse Foundation.
  • The Eclipse Foundation Specification Process was created, and customization created and approved for the Jakarta EE Specification Process.
  • Specification projects are being created and work is underway now within the community to deliver the Jakarta EE 8 release later this year.
  • There is an initiative underway for Oracle, IBM, Red Hat and other members of the JCP to contribute their specification documents created at the JCP to Jakarta.

It had been the mutual intention of the Eclipse Foundation and Oracle to agree to terms that would allow the evolution of the javax package namespace in Jakarta EE specifications.   Unfortunately, following many months of good-faith negotiations, the Eclipse Foundation and Oracle have been unable to agree on terms of an agreement for the Eclipse Foundation community to modify the javax package namespace or to use the Java trademarks currently used in Java EE specifications.   Instead, Eclipse and Oracle have agreed that the javax package namespace cannot be evolved by the Jakarta EE community. As well, Java trademarks such as the existing specification names cannot be used by Jakarta EE specifications.  Because of the complexity and confidential nature of our negotiations, the Eclipse Foundation and Oracle have also agreed that we will not attempt to characterize here what has resulted in this outcome. It is the best outcome we could mutually achieve for the community. Some additional context is provided in the Eclipse Foundation Board and Jakarta EE Steering Committee meeting minutes.

What restrictions does this outcome impose on the Eclipse community?

Oracle’s Java trademarks are the property of Oracle and the Eclipse Foundation has no rights to use them.   The implications of this are as follows:

  1. The javax package namespace may be used within Jakarta EE specifications but may be used “as is” only.  No modification to the javax package namespace is permitted within Jakarta EE component specifications. Jakarta EE specifications that continue to use the javax package namespace must remain TCK compatible with the corresponding Java EE specifications.
  2. Jakarta EE component specifications using the javax package namespace may be omitted entirely from future Jakarta EE Platform specifications.
  3. Specification names must be changed from a “Java EE” naming convention to a “Jakarta EE” naming convention.  This includes acronyms such as EJB, JPA or JAX-RS.

In addition to the above, any specifications which use the javax namespace will continue to carry the certification and container requirements which Java EE has had in the past. I.e., implementations which claim compliance with any version of the Jakarta EE specifications using the javax namespace must test on and distribute containers which embed certified Java SE implementations licensed by Oracle. These restrictions do not apply to Jakarta EE specifications which do not utilize javax, including future revisions of the platform specifications which eliminate javax.

Note that the ratified Jakarta EE specifications will be available under a different license (the Eclipse Foundation Specification License). This is the reason why the Eclipse Foundation is currently asking the community to update their contributor and committer agreements.

What is next for the Jakarta EE Working Group?

The Jakarta EE Working Group including Oracle will continue to do what they set out to do: namely, move Java EE to the Eclipse Foundation. The group remains committed to creating a Jakarta EE 8 specification, logoed under the Eclipse Foundation’s Jakarta trademark. Further, the group is also committed to future versions of the Jakarta EE specifications that deliver on the original promises of innovation and evolution in cloud-native Java.

What does it mean for Jakarta EE to not modify the javax package namespace?

The Agreement does allow for modification and evolution under a new namespace, such as jakarta. It is expected that all future evolution and innovation will not use the javax namespace.

What happens to the Jakarta EE brand?

The Jakarta EE compatibility and the Jakarta EE member logos have both been decided on by the community and published. Work is underway to deliver the branding usage guidelines and supporting trademark license agreement. We expect to see the usage of these brands later this year.

Will there be a Jakarta EE 8?

Yes. The community is working hard to deliver the Jakarta EE 8 release, which is Java EE 8 delivered from Eclipse. We expect that many application servers will certify as Jakarta EE 8 compatible.

What happens beyond Jakarta EE 8?

The guiding principle for Jakarta EE 9 will be to maximize compatibility with Jakarta EE 8 for future versions without stifling innovation.  This will most likely involve two key topics: migration of some or all of the Jakarta EE specification source to a new namespace for future evolution; means to provide backwards compatibility with javax at a binary level, allowing old applications to run on Jakarta 9 implementations with some form of build or runtime tooling.

So while there will be a point in time where future versions of specifications will have to go through a source code incompatible change with respect to the previous javax based packages, this will be a straightforward transformation.

Further plans are being evolved by the Jakarta EE community via the Jakarta EE Platform Project. Your comments and participation are encouraged.

What does this mean for the EE4J projects?

The specification projects need to be renamed to not use Oracle’s Java trademarks. The Jakarta community gets to decide on the new names. This is an opportunity to tighten up the naming and get a better level of consistency. The future of Eclipse Enterprise for Java (EE4J) projects will be determined by the community who participate in those specifications and open source projects.

What is next for Eclipse GlassFish?

Work is underway at the Eclipse GlassFish project running the Jakarta EE 8 TCK and being ready to support its role in the TCK for interop testing. The future of Eclipse GlassFish will be determined by the community who participate in the project.

How will specs be updated beyond Jakarta EE 8?

Jakarta EE specifications will be updated according to the approved Jakarta EE Specification Process (JESP). The actual enhancements will be determined by the community who participate in those specification projects.


by Mike Milinkovich at May 03, 2019 10:00 AM

Jakarta EE Community Engagement

by Tanja Obradovic at May 02, 2019 05:35 PM

 

 

The intention of the blog is to list all the ways we currently (May 2019) engage with the community.

Social media

Jakarta EE on social media

  • Twitter: @JakartaEE

  • Facebook: Jakarta EE

  • LinkedIn Group: Jakarta.EE

Mailing lists

Subscribe to our mailing-lists https://jakarta.ee/connect/

Note: people involved in a specific project have additional mailing lists available to them.

Newsletter / Blogs / emails

Eclipse Newsletter - while the EF newsletter occurs monthly, once a quarter the newsletter is dedicated to Jakarta EE

Jakarta Blogs - https://jakartablogs.ee/

In addition to the above Jakarta blogs that are covering all Java Cloud related topics, we are adding the following

Meetings

Jakarta Tech Talks - open to community jakarta.ee-community@eclipse.org

Jakarta EE Update (formerly: Jakarta EE WG) calls - open to WG jakarta.ee-wg@eclipse.org  and wider community  jakarta.ee-community@eclipse.org

  • Use the time slot for occasional updates from Eclipse Foundation and strategic members (Executive Director and panel)  - Jakarta Town Hall

Jakarta Town Hall

We had 2 very successful instances of town hall meetings - first at EclipseCon Europe 2018 and A year in review in late January 2019

EF organized Events and Conferences

JakartaOne Live - virtual one-day event, targeting users and adopters. Planned for the second week of September 2019.

EclipseCon Europe - 4-day Eclipse event, with dedicated Cloud Native Java track, community day event scheduled, likely Jakarta Town Hall.  Scheduled for October 21-24, 2019.


by Tanja Obradovic at May 02, 2019 05:35 PM

How to install Payara 5 with NGINX and Let's Encrypt over Oracle Linux 7.x

May 02, 2019 12:00 AM

Payara SSL

From field experiences I must affirm that one of the greatest and stable combinations is Java Application Servers + Reverse Proxies, although some of the functionality is a clear overlap, I tend to put reverse proxies in front of application servers for the following reasons (please see NGINX page for more details):

  • Load balancing: The reverse proxy acts as traffic cop and could be used as API gateway for clustered instances/backing services
  • Web acceleration: Most of our applications nowadays use SPA frameworks, hence it is worth to cache all the js/css/html files and free the application server from this responsibility
  • Security: Most of the HTTP requests could be intercepted by the reverse proxy before any attempt against the application server, increasing the opportunity to define rules
  • SSL Management: It is easier to install/manage/deploy OpenSSL certificates in Apache/NGINX if compared to Java KeyStores. Besides this, Let's Encrypt officially support NGINX with plugins.

Requirements

To demonstrate this functionality, this tutorial combines the following stack in a classic (non-docker) way, however most of the concepts could be useful for Docker deployments:

  • Payara 5 as application server
  • NGINX as reverse proxy
  • Let's encrypt SSL certificates

It is assumed that a clean Oracle Linux 7.x (7.6) box will be used during this tutorial and tests will be executed over Oracle Cloud with root user.

Oracle Linux

Preparing the OS

Since Oracle Linux is binary compatible with RHEL, EPEL repository will be added to get access to Let's Encrypt. It is also useful to update the OS as a previous step:

yum -y update
yum -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm

Setting up Payara 5

In order to install Payara application server a couple of dependencies will be needed, specially a Java Developer Kit. For instance OpenJDK is included at Oracle Linux repositories.

yum -y install java-1.8.0-openjdk-headless
yum -y install wget
yum -y install unzip

Once all dependencies are installed, it is time to download, unzip and install Payara. It will be located at /opt following standard Linux conventions for external packages:

cd /opt
wget -O payara-5.191.zip https://search.maven.org/remotecontent?filepath=fish/payara/distributions/payara/5.191/payara-5.191.zip
unzip payara-5.191.zip
rm payara-5.191.zip

It is also useful to create a payara user for administrative purposes, to administrate the domain(s) or to run Payara as Linux service with systemd:

adduser payara
chown -R payara:payara payara5
echo 'export PATH=$PATH:/opt/payara5/glassfish/bin' >> /home/payara/.bashrc
chown payara:payara /home/payara/.bashrc

A systemd unit is also needed:

echo '[Unit]
Description = Payara Server v5
After = syslog.target network.target

[Service]
User=payara
ExecStart = /usr/bin/java -jar /opt/payara5/glassfish/lib/client/appserver-cli.jar start-domain
ExecStop = /usr/bin/java -jar /opt/payara5/glassfish/lib/client/appserver-cli.jar stop-domain
ExecReload = /usr/bin/java -jar /opt/payara5/glassfish/lib/client/appserver-cli.jar restart-domain
Type = forking

[Install]
WantedBy = multi-user.target' > /etc/systemd/system/payara.service
systemctl enable payara

Additionally if remote administration is needed, secure admin should be enabled:

sudo -u payara /opt/payara5/bin/asadmin --host localhost --port 4848 change-admin-password
systemctl start payara
sudo -u payara /opt/payara5/bin/asadmin --host localhost --port 4848 enable-secure-admin
systemctl restart payara

Payara Boot

Oracle Cloud default configuration will create a VNIC attached to your instance, hence you should check the rules in order to allow access to ports.

Ingres Rules

By default, Oracle Linux instances have a restricted set of rules in iptables and SELinux, hence ports should be opened with firewalld and SELinux should be configured to allow reverse proxy traffic:

firewall-cmd --zone=public --permanent --add-service=http
firewall-cmd --zone=public --permanent --add-service=https
firewall-cmd --zone=public --permanent --add-port=4848/tcp
setsebool -P httpd_can_network_connect 1

With this, the access is guaranteed to http+https+payara admin port.

Setting up NGINX reverse proxy

NGINX is available at EPEL:

yum -y install nginx
systemctl enable nginx

At this time your will need a FQDN pointing to your server, otherwhise Let's encrypt validation won't work. For this tutorial the ocl.nabenik.com domain will be used. If your domain propagated properly you should see a page like this:

NGINX Proxy

Don't worry the Fedora logo is due EPEL usage, but you're running Oracle Linux :).

Now it's time to setup NGINX as reverse proxy, an opinionated deployment option is to create a /etc/nginx/sites-available and /etc/nginx/sites-enabled structure inside NGINX configuration, to isolate/manage multiple domains with the same instance (aka virtual hosts).

mkdir -p /etc/nginx/sites-available
mkdir -p /etc/nginx/sites-enabled
mkdir -p /var/www/ocl.nabenik.com/
chown -R nginx:nginx /var/www/ocl.nabenik.com

echo 'server {
    server_name ocl.nabenik.com;

    gzip on;
    gzip_types      text/css text/javascript text/plain application/xml;
    gzip_min_length 1000;

    location ^~ /.well-known/acme-challenge/ {
        allow all;
        root /var/www/ocl.nabenik.com/;
        default_type "text/plain";
        try_files $uri =404;
    }

    location / {
        proxy_pass             http://localhost:8080;
        proxy_connect_timeout       300;
        proxy_send_timeout          300;
        proxy_read_timeout          300;
        send_timeout                300;
    }

    error_page  500 502 503 504  /50x.html;
    location = /50x.html {
        root  /usr/share/nginx/html;
    }

    listen 80;
}' > /etc/nginx/sites-available/ocl.nabenik.com.conf

To enable the new host, a symlink is created on sites-enabled:

ln -s /etc/nginx/sites-available/ocl.nabenik.com.conf /etc/nginx/sites-enabled/ocl.nabenik.com.conf

After that you should include the following line inside /etc/nginx/nginx.conf, just before config file ending.

include /etc/nginx/sites-enabled/*.conf;

It is also useful to check your configuration with nginx -t, if all works property you should reach payara after NGINX reload.

Reverse Payara

Setting up Let's Encrypt

Once the reverse proxy is working, certbot should be enough to add an SSL certificate, the plugin itself will create a challenge at ^~ /.well-known/acme-challenge/, hence the proxy exclusion is mandatory (as reflected in the previous configuration step).

yum install -y certbot-nginx
certbot --nginx -d ocl.nabenik.com

One of the caveats of using certbot is the dependency of python version. Another alternative if you find any issues is to install it with pip

yum install -y python-pip
pip install certbot-nginx
certbot --nginx -d ocl.nabenik.com

If everything works as expected, you should see the Payara page under SSL.

Payara SSL

Finally and most importantly, Let's Encrypt certificates are valid just for 90 days, hence you could add certification renewal (crontab -e) as a cron task

15 3 * * * /usr/bin/certbot renew --quiet

May 02, 2019 12:00 AM

#HOWTO: Create nice-looking JSF 2.3 applications with PrimeFaces 7.0

by rieckpil at May 01, 2019 08:23 AM

With the release of PrimeFaces 7.0 in March 2019, PrimeTek team introduced over 500 improvements featuring new components, new modern free themes, font icons, better performance various enhancements on accessibility and security. The new modern free themes were the first thing I noticed while browsing through the PrimeFaces component showcase page especially the Nova-Light theme. Besides the premium themes (e.g. Barcelona, Poseidon, Omega …) you’ll now get nice-looking themes for free.

To not only show you how this new theme looks like but to demonstrate how easy & fast you can create applications with JSF and PrimeFaces components, I created a small demo application. The application contains a form for entering data, a feature-rich data table, a chart and some general UI elements like a header and a footer and was made within 2 hours (some troubleshooting with the components included). I won’t go into a technical explanation of the source code in this blog post and will rather focus on demonstrating the productivity with JSF and the PrimeFaces components (the source code is available on GitHub).

The following technologies were used: Java 8, Java EE 8, OmniFaces 3.2, PrimeFaces 7.0 running on Payara 5.191.

For those of you who can wait, give it the first try at https://jsf-demo.riecks.io/index.xhtml.

Getting started

A good place to start is the PrimeFaces showcase page where you get an overview of all available components with sample code snippets to show you how the component looks like and how to use it. You’ll both get the required XHTML code alongside the backing bean for the component demo.

For my demo application, I decided to structure the content like the following: header, content, footer. JSF provides a simple way to insert commonly used markup templates and therefore I created a header.xhtml and footer.xhtml file and include it on every page. The header contains a menu bar to navigate through the application and was made with the Menubar component of PrimeFaces. I could pick the showcase Menubar, adjust the menu items and was ready. For the footer, I decided to just show some text on every page.

The main page contains three PrimeFaces Panels to structure the content a little bit. Common charts like BarChart, LineChart, PieChart, etc. are also part of the component library of PrimeFaces. At the latest when integrating charts while using SPA frameworks, you would now need to evaluate a new library, include it to your project, learn its specific API, see how it integrates and create an interface to provide the data. With JSF you just have to expose the chart’s data model object with a backing bean, prepare the data basis with custom Java code (e.g. fetch data from a database via JPA) and you are done:

Data representation

The most common use case for nearly every web application is to visualize data in a table and to be able to filter, search and modify it. Achieving this with a JavaScript-based application, you now have to find the next library and put up with the pros and cons of integrating external libraries. With the feature-rich DataTable component from PrimeFaces, I was able to visualize data with the following features: pagination, context menu, column filtering, column sorting, column selection in under 30 minutes.

CRUD (Create, Read, Update, Delete) operations are also quite easy to achieve with this component as you don’t have to design and implement any e.g. REST-based interfaces. You can find a blog post about a CRUD table with JSF, PrimeFaces, and JPA here.

Entering data

Just visualizing data without creating it, is boring. With JSF, no problem!

The Input components from PrimeFaces cover nearly every use case. To show you a selection of them, I decided to use a dropdown input with searching capability, an input with masking (e.g. tax id, card numbers), a slider, a toggle switch, and a date picker. Some of the input fields are backend by server-side data and some are static.

For validating the input you can make use of Bean Validation (@NotNull, @Future, @Size …) within your backing bean and get validation out of the box. Compared to a SPA application, where you have to double check the data (at the input/before sending and at the interface) this to this is really pleasant.

Final thoughts

Don’t get me wrong, I don’t want to badmouth any SPA framework or JavaScript library (as I am also using them), I just want to show you a (maybe forgotten) way to create nice-looking applications and make you aware of carefully considering the pros and cons.

If you’ve not yet tried JSF, I would recommend it. With some basic HTML + CSS knowledge, you can easily create a simple application in minutes. PrimeFaces also gives you a wide variety of ready-to-use components and you can focus on business logic. Writing just Java code (except some HTML) for your whole application is also a nice advantage as you don’t need to maintain the frontend written in a different language. The integration with other Java EE standards (e.g. CDI, EJB, Security …) is also really nice and makes e.g. authorization and authentication easier. Once you are familiar with the concepts of JSF (read this book for an excellent JSF intro & deep-dive), you’ll be way more productive and can rely on only one tech-stack.

Most of the time I would prefer JSF for a company internal application (no fancy animations/graphics/pixel-perfect UIs required) and at least consider the technology for an application with external users (if the available components meet your requirements).

For more information, just browse through my other blog posts about JSF or subscribe to my #NEWSLETTER, where I also write about JSF:

The full codebase for this example is available at GitHub with instruction on how to run it on your machine. In addition, I’ve deployed this application and you can give it a try right now.

Have fun using JSF with PrimeFaces,

Phil


by rieckpil at May 01, 2019 08:23 AM

Back from Devoxx France 2019

by Jean-François James at April 30, 2019 03:21 PM

From 16 to 19 April took place the 8th edition of Devoxx France in Paris at the Palais des Congrés. It aimed to be the main event for passionate French developers. Indeed it is clearly « the place to be » during these 3 days: a unique opportunity to recharge your batteries, to meet interesting people, to get new […]

by Jean-François James at April 30, 2019 03:21 PM

The Payara Monthly Roundup for April 2019

by Jadon Ortlepp (Jadon.Ortlepp@Payara.fish) at April 30, 2019 02:29 PM

Hello and welcome to the second issue of our monthly round up where we feature a curated list of interesting articles and videos created by the community that we have enjoyed and found interesting. Cant wait until the end of the month? then visit our twitter page where we post all these articles as we find them! 


by Jadon Ortlepp (Jadon.Ortlepp@Payara.fish) at April 30, 2019 02:29 PM

Getting started with Java EE 8, Java 11, Eclipse for Java Enterprise and Wildfly 16

April 30, 2019 12:00 AM

Eclipse 2019

In this mini-tutorial we will demonstrate the configuration of a pristine development environment with Eclipse, JBoss Tools and Wildfly Application Server on MacOS.

From JBoss with love

If you have been in the Java EE space for a couple of years, Eclipse IDE for Java Enterprise Developers is probably one of the best IDE experiences, making an easy task the creation of applications with important EE components like CDI, EJB, JPA mappings, configuration files and good interaction with some of the important application servers (TomEE, WebLogic, Payara, Wildfly, JBoss).

In this line, Red Hat develops the Eclipse variant "CodeReady Studio" giving you and IDE with support for Java Enterprise Frameworks, Maven, HTML 5, Red Hat Fuse and OpenShift deployments.

To give support to its IDE, Red Hat also publishes CodeReady plugins as an independent project called JBoss Tools, enabling custom Enterprise Java development environments with Eclipse IDE for Java Enterprise developers as basis, which we demonstrate in this tutorial.

Why? For fun. Or as in my case, I don't use the entire toolset from Red Hat.

Requirements

In order to complete this tutorial you will need to download/install the following elements:

1- Java 11 JDK from Oracle or any OpenJDK distro
2- Eclipse IDE for Enterprise Java Developers
3- Wildfly 16

Installing OpenJDK

Since this is an OS/distribution dependent step, you could follow tutorials for Red Hat's OpenJDK, AdoptOpenJDK, Ubuntu, etc. At this time, Wildfly has Java 11 as target due new Java-LTS version scheme.

For MacOS one convenient way is AdoptOpenJDK tap.

First you should install Homebrew

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

After that and if you want an specific Java version, you should add AdoptOpenJDK tap and install from there. For instance if we like a OpenJDK 11 instance we should type:

brew tap AdoptOpenJDK/openjdk
brew cask install adoptopenjdk11

If all works as expected, you should have a new Java 11 environment running:

Java 11

Eclipse IDE for Enterprise Java Developers

Eclipse offers collections of plugins denominated Packages, each package is a collection of common plugins aimed for a particular development need. Hence to simplify the process you could download directly Eclipse IDE for Enterprise Java Developers.

Eclipse Enterprise

On Mac you will download a convenient .dmg file that you should drag and drop on the Applications folder.

Eclipse Install

The result is a brand new Eclipse Installation with Enterprise Java (Jakarta EE) support.

Eclipse IDE

JBoss Tools

To install the "Enterprise Java" Features to your Eclipse installation, go to JBoss Tools main website at https://tools.jboss.org/ you should double check the compatibility with your Eclipse version before installing. Since Eclipse is lauching new versions each quarter the preferred way to install the plugins is by adding the update URL .

First, go to:

Help > Install New Software… > Work with:

And add the JBoss Tools URL http://download.jboss.org/jbosstools/photon/development/updates/

JBoss Repo

After that you should select the individual features, a minimal set of features for developers aiming Jakarta EE is:

  • JBoss Web and Java EE Development: Support for libraries and tools like DeltaSpike, Java EE Batch, Hibernate, JavaScript, JBoss Forge
  • JBoss Application Server Adapters: Support for JBoss, Wildfly and OpenShift 3
  • JBoss Cloud and Container Development Tools: Support for Vagrant, Docker and Red Hat Containers development kit
  • JBoss Maven support: Integrations between Maven and many EE/JBoss APIs

JBoss Tools

Finally you should accept licenses and restart your Eclipse installation.

Wildfly 16

Wildfly distributes the application server in zip or tgz files. After getting the link you could do the install process from the CLI. For example if you wanna create your Wildfly directory at ~/opt/ you should execute the following commands

mkdir ~/opt/
cd ~/opt/
wget https://download.jboss.org/wildfly/16.0.0.Final/wildfly-16.0.0.Final.zip
unzip wildfly-16.0.0.Final.zip

It is also convenient to add an administrative user that allows the creation of DataSources, Java Mail destinations, etc. For instance and using again ~/opt/ as basis:

cd ~/opt/wildfly-16.0.0.Final/bin/
./add-user.sh

Wildfly Admin

The script will ask basic details like user name, password and consideration on cluster environments, in the end you should have a configured Wildfly instance ready for development, to start the instance just type:

~/opt/wildfly-16.0.0.Final/bin/standalone.sh

To check your administrative user, go to http://localhost:9990/console/index.html.

Wildfly Dashboard

Eclipse and Wildfly

Once you have all set, it is easy to add Wildfly to your Eclipse installation. Go to servers window and add a new server instance, the wizard is pretty straight forward so screenshot are added just for reference:

Wildfly 16

Wildfly 16 local

Wildfly Home

If you wanna go deep on server's configuration, Eclipse allows you to open the standalone.xml configuration file directly from the IDE, just check if the application server is stopped, otherwhise your configuration changes will be deleted.

Wildfly Standalone

Testing the environment

To test this application I've created a nano-application using an Archetype for Java EE 8. The application server and the IDE support Java 11 and the deployment works as expected directly from the ide.

Wildfly EE


April 30, 2019 12:00 AM

[En] How to activate microprofile metrics in OpenLiberty

by Altuğ Bilgin Altıntaş at April 26, 2019 01:20 PM

In Jakarta EE Microprofile you can use Metrics easily.  No need for Hystrix project.  The simple code in order to show how to use Metrics in the codebase @GET @Path("all") @Metered public List<Ping> getAllPings() { return pingBean.getAllPings() ; } @POST @Counted(monotonic = true) public Ping save(Ping...

by Altuğ Bilgin Altıntaş at April 26, 2019 01:20 PM

#HOWTO: Messaging with JMS using Payara with embedded OpenMQ broker

by rieckpil at April 25, 2019 01:26 PM

Messaging is a key concept for distributed enterprise applications. There are a lot of use cases, where you don’t want or need a sync response you get with e.g. a REST call and can use async messaging: IoT (sensor data), event streaming, data duplication, etc. With the hype of Kafka and other highly-distributed messaging solutions, you may forget that there is already a sophisticated and proven messaging standard within Java/Jakarta EE: JMS (Java Message Service).

For this Java EE standard, I’m providing a simple introduction for sending and receiving JSON messages with this blog post. The technology setup is the following: Java 8, Java EE 8, Payara 5.191 and H2 for storing the messages.

JMS prerequisites

As Payara already comes with OpenMQ, which implements the Java Message Service (JMS) standard, you don’t have to set up an external JMS broker (e.g ActiveMQ, RabbitMQ ..) for this example and can use the embedded version (think twice if you use this in production).

The connection pool for the embedded OpenMQ is preconfigured and we can directly make use of it via its JNDI name jms/__defaultConnectionFactory. If you want to connect to an external broker you would have to set up the connection manually (take a look at this excellent example for ActiveMQ from Steve Millidge itself).

With JMS you can make use of two different concepts for delivering our messages: Topics (publish & subscribe) and Queues (point-to-point). In this example, I’m using a javax.jms.Queue but the code would look quite similar for using a Topic.

The JMS Queue or Topic has to be first configured within Payara as a JMS Destination Resource and can be configured either via the Payara admin panel (Resources – JMS Resources – Destination Resources) or using asadmin:

asadmin create-jms-resource --restype javax.jms.Queue --property Name=STOCKS jms/stocks

You have to specify the resource type (Topic or Queue), the physical name of the resource within the broker (will be created if it doesn’t exist) and the JNDI name.

Let’s start coding

The Maven project for this showcase is a simple and thin Java EE project:

<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>de.rieckpil.blog</groupId>
  <artifactId>messaging-with-jms-using-payara</artifactId>
  <version>1.0-SNAPSHOT</version>

  <packaging>war</packaging>

  <dependencies>
    <dependency>
      <groupId>javax</groupId>
      <artifactId>javaee-api</artifactId>
      <version>8.0</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>

  <build>
    <finalName>messaging-with-jms-using-payara</finalName>
  </build>

  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <failOnMissingWebXml>false</failOnMissingWebXml>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  </properties>
</project>

In this showcase I’m sending random stock information (using JSON with JSONP) every two seconds with a simple EJB timer:

@Singleton
public class StockPublisher {

  @Resource(lookup = "jms/__defaultConnectionFactory")
  private ConnectionFactory jmsFactory;

  @Resource(lookup = "jms/stocks")
  private Queue jmsQueue;

  private String[] stockCodes = { "MSFT", "GOOGL", "AAPL", "AMZN" };

  @Schedule(second = "*/2", minute = "*", hour = "*", persistent = false)
  public void sendStockInformation() {

    TextMessage message;

    try (Connection connection = jmsFactory.createConnection();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageProducer producer = session.createProducer(jmsQueue)) {

      JsonObject stockInformation = Json.createObjectBuilder()
          .add("stockCode", stockCodes[ThreadLocalRandom.current().nextInt(stockCodes.length)])
          .add("price", ThreadLocalRandom.current().nextDouble(1.0, 150.0))
          .add("timestamp", Instant.now().toEpochMilli()).build();

      message = session.createTextMessage();
      message.setText(stockInformation.toString());

      producer.send(message);

    } catch (JMSException e) {
      e.printStackTrace();
    }
  }
}

For sending messages, you first have to create a connection via the JMS ConnectionFactory, then create a Session and finally a message producer for the concrete topic or queue. You can access the required resources via their JNDI names as configured before.

Receiving messages is achieved with so-called Message-Driven Beans (MDB) which implement the MessageListener interface and are configured (which topic or queue to listen) using the @MessageDriven annotation. In this example, I’m sending and receiving the message within the same application (for simplicity) and store the provided information in the embedded H2 database of Payara:

@MessageDriven(name = "stockmdb", activationConfig = {
    @ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = "jms/stocks"),
    @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue") })
public class StockListener implements MessageListener {

  @PersistenceContext
  private EntityManager em;

  @Override
  public void onMessage(Message message) {

    TextMessage textMessage = (TextMessage) message;

    try {
      System.out.println("A new stock information arrived: " + textMessage.getText());

      JsonReader jsonReader = Json.createReader(new StringReader(textMessage.getText()));
      JsonObject stockInformation = jsonReader.readObject();

      em.persist(new StockHistory(stockInformation));
    } catch (JMSException e) {
      e.printStackTrace();
    }
  }

}

Once deployed to Payara, the console output looks like the following:

[#|2019-04-25T13:04:08.007+0000|INFO|Payara 5.191||_ThreadID=186;_ThreadName=orb-thread-pool-1 (pool #1): worker-2;_TimeMillis=1556197448007;_LevelValue=800;|
  A new stock information arrived: {"stockCode":"MSFT","price":148.55312721701924,"timestamp":1556197448002}|#]

[#|2019-04-25T13:04:10.012+0000|INFO|Payara 5.191||_ThreadID=188;_ThreadName=orb-thread-pool-1 (pool #1): worker-3;_TimeMillis=1556197450012;_LevelValue=800;|
  A new stock information arrived: {"stockCode":"AMZN","price":77.60891905653475,"timestamp":1556197450003}|#]

[#|2019-04-25T13:04:12.009+0000|INFO|Payara 5.191||_ThreadID=190;_ThreadName=orb-thread-pool-1 (pool #1): worker-4;_TimeMillis=1556197452009;_LevelValue=800;|
  A new stock information arrived: {"stockCode":"MSFT","price":8.593186941846369,"timestamp":1556197452002}|#]

The JPA entity StockHistory looks like the following:

@Entity
public class StockHistory {

  @Id
  @GeneratedValue
  private Long id;

  @Column(nullable = false)
  private String stockCode;

  @Column(nullable = false)
  private Double price;

  @Column(nullable = false)
  private Instant timestamp;

  public StockHistory(JsonObject json) {
    this.stockCode = json.getString("stockCode");
    this.price = json.getJsonNumber("price").doubleValue();
    this.timestamp = Instant.ofEpochMilli(json.getJsonNumber("timestamp").longValue());
  }

       // further constructors, getters & setters 
}

For the sake of completeness, this is the persistence.xml for this small application:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd">
  <persistence-unit name="prod" transaction-type="JTA">
    <properties>
      <property
        name="javax.persistence.schema-generation.database.action" value="drop-and-create" />
    </properties>
  </persistence-unit>
</persistence>

You can find the full code on GitHub with a step-by-step guide to run this example locally on your machine with Docker. If you are looking for a simple JMS quickstart with Open Liberty, have a look at one of my previous posts.

Keep sending/receiving messages,

Phil


by rieckpil at April 25, 2019 01:26 PM

MicroProfile and Jakarta EE -- The Lightweight Stuff Session

by admin at April 24, 2019 04:54 AM

An itkonekt session for building a MicroProfile / Java EE application from scratch. Metrics, OpenAPI, FaultTolerance, Configuration, multi-server deployments, ThinWARs, and even reactive (easter) eggs included:

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.


by admin at April 24, 2019 04:54 AM

Back to the top

Submit your event

If you have a community event you would like listed on our events page, please fill out and submit the Event Request form.

Submit Event