Česky   |  Deutsch   |  English   |  Español   |  Français   |  Indonesia   |  日本語   |  한글   |  Polski   |  Português (BR)   |  Türkçe   |  中文   |  正體中文   |  Your Language  
PlanetNetbeans
Planet NetBeans is an aggregation of NetBeans related musings from all over the Blogosphere.
Adam Bien - February 19, 2018 01:59 PM
Java EE 8: Manipulating JsonObjects with JsonPatch

JSON-P (JSR-374) from Java EE 8 comes with JSON Patch support, which can be used for manipulation (patching) of JsonObject instances (see also Java EE 8 and JSON-P Simplify System Testing with JSON Patch):


@Test
public void patch() {
    JsonObject sub = Json.createObjectBuilder().
            add("name", "EE4J").
            build();

    JsonObject initial = Json.createObjectBuilder().
            add("fact", "Java EE is nice").
            add("myth", "Java EE is heavyweight").
            add("future", sub).
            build();

    JsonPatch patch = Json.createPatchBuilder().
            add("/version", "8").
            replace("/fact", "Java EE rocks").
            replace("/future/name", "Jakarta EE").
            remove("/myth").
            build();

    JsonObject result = patch.apply(initial);
    System.out.println("result = " + result);
}

Output:

result = {"fact":"Java EE rocks","future":{"name":"Jakarta EE"},"version":"8"}

JSON-P comes as a single maven dependency:


<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1.2</version>
</dependency>

See you at Java EE Workshops at MUC Airport, particularly at the Effective Java EE 8 workshop
Real World Java EE Workshops [Airport Munich]>

Adam Bien - February 17, 2018 06:43 AM
Java EE, Thin WARs, Microservices and Continuous Delivery at Otto

Bastian, please introduce yourself (feel free to share your twitter, linkedin, github etc. accounts)

My name is Bastian Sperrhacke and I am a software developer and technical lead in a ten people team called "Verfügbarkeit" (availability) at Otto GmbH & Co. KG. There are three business analysts, six developers (including me) and one teamlead responsible for the product availability calculation and the product sell services. We are one of many teams in the backend IT of Otto. You can find me at @deratzmann and Bastian Sperrhacke.

What are you building with Java EE?

We build our latest system for additional sell services for products offered in a shop with Java EE 7. For example, if you want to add an additional warranty to your mobile phone or want to get rid of your old washing machine while receiving the new one, there is a business case called "article service" which abstracts these kind of cases. We build this system as a Java EE microservice and offer REST Services for our frontends and shops.

Can you share with us some geeky numbers like e.g. TX per seconds, heap sizes, thinnest WARs etc -- whatever Java EE devs might find interesting.

Currently our WAR file is about 300kb, the biggest file inside is our swagger documentation file (71kb). From commit to production we are live in about 7 minutes with our continuous delivery pipeline, including Unit-, Integration-, System- and Performancetests. Our software is running since begin of February 2018 and had 5280823 requests in the last week.

Are you happy with Java EE so far? Is Java EE productive?

Yes, I am very happy with Java EE. It provides me a standardized way to code, is well documented and highly used. With Java EE you can become productive in minutes, no bloated configuration or dependency hell anywhere. Just code your business requirements.

Which application servers, tools or IDEs are you using?

First of all we use the Payara full server, it is very fast and productive, well documented. It provides the stable Java EE API and the innovative, fast moving microprofile. The Payara team is very nice, I got to know them at JavaOne last year. Relating IDEs it is up to each team member to use his favorite IDE or editor. Most of us (including me) are using netbeans, very nice, fast and lean IDE. For our pipeline we use Jenkins. Our docker containers are orchestrated by docker swarm.

You are using the Boundary Control Entity pattern to structure your applications. What were your experiences, challenges and findings so far?

The first big challenge was to structure the class and the packages in a business, not a technical driven way. So no more "persistence", "valueobjects" or "service" package. For decades developers learned to structure in a technical way. But for new guys in a team it is hard, to find a business case implementation in such a structure. The ECB pattern is the easiest way to fit in that context. You start with an entity and a service called boundary. There is no easier way. And if (and only if) the boundary "gets too big", you refactor the non-standalone functions out to a so called control. In my opinion this way leads to a clearly arranged code, not overengineered, just fitted to the current required business case.

How important are standards for you? Does your application depend on application server specific APIs?

Standards are very important for me. When you are professionally developing products, you have to ask yourself: Do I technically need an early adopter software or a long lasting lean product. In real world projects the truth lies between these two approaches. And Java EE is a perfect fit for that. First you get a quite stable API, which is continuously evolving. Since Java EE was transferred from Oracle to the community, I think there will be much more drive behind it. Let's have a look at the great companies standing behind the microprofile initiative. This initiative is also responsible for a quite innovative de facto standardization. Using one of the application servers like Payara means, I get the API stability of Java EE and a fast evolving feature set of the microprofile. In our project we currently use the microprofile-config-api and plan to use the new fault-tolerance-api. Furthermore we use some Payara specific implementations like the Jackson API. We also planned to use the build-in Hazelcast for distributed job scheduling and caching.

Which Java EE APIs are you using in your products?

Generally we use EJB, JPA, CDI, Bean Validation, Jax-RS, JTA and JSF.

You attended JavaOne last year. What was your impression?

This was my first time at JavaOne and also my first time in the US. It was amazing and I hope to get a chance for a second visit in the near future. I attended as much sessions as I could get. It was exhausting but worth it. Hopefully I can introduce some ideas in our daily business.

Can you share any resources (blogs, etc feel free to promote yourself) with us?

I get my newest info from twitter. I read tweets and blogs from Vlad Mihalcea, Thorben Janssen (hellish good JPA specialists), Sebastian Daschner (Java EE evangelist), Payara (Java EE Server) and last but not least Adam Bien. :)

Bastian, thank you for the interview!


Real World Java EE Workshops [Airport Munich]>

Adam Bien - February 16, 2018 09:38 AM
Java EE 8 and JSON-P Simplify System Testing with JSON Patch

JSON-P (JSR-374) from Java EE 8 comes with JSON Patch support, which is useful for system testing.

A JSON object returned from a HTTP endpoint can be easily compared to a local representation loaded from a file:


import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonPatch;
import javax.json.JsonReader;
import static org.junit.Assert.assertTrue;
import org.junit.Test;

public class JSONPDiffTest {

    @Test
    public void subtraction() {
        //e.g. server result
        JsonObject actual = Json.createObjectBuilder().
                add("a", 21).
                add("b", 1).
                build();

        try (JsonReader reader
                = Json.createReader(this.getClass().getResourceAsStream("/expected.json"))) {
            JsonObject expected = reader.readObject();
            JsonPatch diff = Json.createDiff(expected, actual);
            assertTrue(diff.toString(), diff.toJsonArray().isEmpty());
        }
    }
}    

The code above loads the file src/test/resources/expected.json with the content:


{
    "a": 21,
    "b": 2
}    

and compares it to the actual instance.

The result is:

java.lang.AssertionError: [{"op":"replace","path":"/b","value":1}]

JSON-P comes as a single maven dependency:


<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1.2</version>
</dependency>

See you at Java EE Workshops at MUC Airport, particularly at the Java EE CI/CD, Testing and Quality workshop
Real World Java EE Workshops [Airport Munich]>

NetBeans – Enrico Scantamburlo - February 11, 2018 08:42 PM
Make Ant great again with NetBeans

My company NetBeans RCA is based on Apache Ant, Ant is a build tool for Java that was very popular when I started programming and many IDE used it to build. The NetBeans platform build system was totally based on Ant and this was very good because it allowed customizing the build process. We are currently using it to generate files to be included in the NBMs (the NetBeans Module), to update version numbers, to copy files, to upload files to our server …

Unfortunately, nowadays Ant lost popularity to Maven and Gradle which allows also to automatically download the necessary libraries, however, we have some many stuff built in Ant and we became experts at using it that it is not worth moving to Maven, that is currently also supported by the NetBeans Platform.

For those like me that are still using Ant, I would like to share some tips.

Install the Important Files plugin

If you create a new Java Application project (Not Maven) in NetBeans, the project is based on Ant, but you do not see its build script file unless you press CTRL+2 and search in the Files window. But, when you create a NetBeans Module project you get an Important Files node that shows all the configuration files used to build that module.

You can have the same node if you install a plugin called ImportantFiles 4 JavaSE. It will add a node with the build script and the properties files used to configure the module.

The build file will be listed as Build Script, Buildscript or build.xml .

How to launch easily  any Ant targets

Once you got access to the build file, if you expand it you will see the list of all available targets, you can run them by right-clicking on them and selecting Run Target. From this menu, you can also debug and inspect the targets by choosing Properties. The coolest feature is Create Shortcut… This action will create an item on the toolbar, on the menu or a keyboard shortcut to launch the task, it will only be visible when the project is open. I find it very convenient when I am working with my custom Ant targets that  I have to run often.

Another way to run an Ant Target is to right click on the build script node, choose Run Target and then the target you want to run. If the target you want to run is not present you might have to expand the Other Targets submenu. At the beginning, I was lost about why some targets appear at other targets and others don’t, then  I discovered it works like the -p Ant command line option: it lists only the targets that have a description. To add a description to a target, just add a description attribute with some text in it.

 

<target name="Hello World" description="It says Hello World" >
    <echo message="Hello World" />
</target>

How to customize the build process

When you open the build file there is a huge comment that explains how to customize the build process, in particular, it explains how to launch your own targets before or after any step in the build process.For instance, there are these two examples: one to add obfuscation after the build:

 

<target name="-post-compile">
    <obfuscate>
       <fileset dir="${build.classes.dir}"/>
    </obfuscate>
</target>

another to override the execution to launch your own executable

<target name="run" depends="AntApplication-impl.jar">
     <exec dir="bin" executable="launcher.exe">
          <arg file="${dist.jar}"/>
     </exec>
</target>

Hint for NetBeans Platform developers:  how to run the same target on all modules

It happened to me that I had to run the same target on all my modules in a suite. You can do it in this way:

Create a new Target that depends from -init and use subant 

<subant buildpath="${modules.sorted}" target="spotbugs" inheritall="false" inheritrefs="fakse" failonerror="false" />
Photo by Mikhail Vasilyev on Unsplash

Adam Bien - February 07, 2018 03:46 PM
What is a Mixin?

In this screencast I implement and use a Mixin with stock JavaScript / ES2015 (ES6):

"In object-oriented programming languages, a Mixin is a class that contains methods for use by other classes without having to be the parent class of those other classes (...)":

See you at Single Page Applications (SPAs) -- the "no frameworks, no migrations" approach, at Munich Airport, Terminal 2 or webstandards.training (online).


Real World Java EE Workshops [Airport Munich]>

Adam Bien - February 05, 2018 05:34 AM
Database Authentication, Microservices with JSF, Denormalization, DB Audits, JAX-RS Audit, Devs and Ops -- or 47th airhacks.tv

Questions and topics for the 47th airhacks.tv -- a monthly Questions and Answers show:

  1. Database Authentication: SSH vs. username / password
  2. Microservices with JSF frontend -- architectural discussion
  3. How to modularize WARs
  4. Dealing with denormalized databases
  5. Java EE authentication (Active Directory)
  6. Identity preservation and audits in DB
  7. JAX-RS authentication and principal delegation to EJB / CDI
  8. Development in intranet environment
  9. Reducing coupling between Javascript components like e.g. in React
  10. Developers and operations -- their roles in the future
  11. DeltaSpike project review -- with or without @Repository
  12. Impact of 3rd party libraries on build performance -- with some numbers
  13. Unpredictable, long running transactions
  14. Propagating principals from JAX-RS to EJBs
  15. Why it is a bad idea to resend a password on each request?
  16. Dealing with security in projects like e.g. credit card processing

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 Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.
Real World Java EE Workshops [Airport Munich]>

Adam Bien - February 01, 2018 09:03 AM
Using Vaadin Date Picker as WebComponent

WebComponents are an interesting set of browser APIs to implement entire applications from scratch. However: WebComponents were also designed for reuse, so you can easily include 3rd-party (like e.g. Vaadin) components with your application.

In this screencast I'm integrating a Vaadin Date Picker WebComponent with plain JavaScript / ES 6. From scratch, in 6 minutes:

See you at Structuring Single Page Applications (SPA)s / Progressive Web Applications (PWA)s with WebComponents -- the "no frameworks, no migrations" approach, at Munich Airport, Terminal 2 or webcomponents.training (online).
Real World Java EE Workshops [Airport Munich]>

Adam Bien - January 31, 2018 03:05 PM
FN, Serverless and Exploded Servers -- airhacks.fm

A smalltalk :-) with Shaun Smith, @shaunmsmith, Director of Product Management for Oracle Serverless and Fn project committer.

From TopLink, EclipseLink over fnproject.io to Fn Java Functions Developer Kit (screencast), exploded application servers, Docker and serverless architectures or the 5th episode of airhacks.fm.

Subscribe to airhacks.fm podcast via: iTunes or RSS

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


Real World Java EE Workshops [Airport Munich]>

Adam Bien - January 29, 2018 02:11 PM
2018 Predictions

My 2018 predictions:

  1. Thin WARs become mainstream. Packaging the infrastructure together with the business logic although only <1% changes is not reasonable in containerized environments and slow. Fast turnaround cycles are crucial for productivity. Developers infected with "Thin WAR" mindset thrive for Micro WARs with fast deployments. It is common in green field Java EE 7 projects to have WARs smaller than 1 MB.
  2. Microservices become just another solution for a problem and not a general architecture. It is perfectly fine to deploy a single, small, WAR containing everything: a macroservice / microlith.
  3. Serverless overuse: serverless architectures claim to safe costs and to simplify operations. This is not true for all use cases -- I expect first reports of failing serverless projects due additional implementation complexity and plumbing. However: combining "traditional" Thin WARs with serverless endpoints brings the best of both worlds together. Servers for the main load and functions for (infrequent) events.
  4. OpenLiberty could become the killer Java EE 8 / Java 9 application server. Small, lightweight and with interesting production features.
  5. SQL revival: Modern relational databases like e.g PostgreSQL will regain traction.
  6. JMS revival: there is a lack of popular common messaging API in microservice context. JMS 2.0 is just an API and could be implemented by many messaging services. JMS API with a "funky" implementation could (should) gain traction.
  7. I got the first requests about Java 9 modules within microservices. There should be a buzz around additional module complexity introduced with "premature modularization" in second half of 2018 (or earlier).
  8. Fat Clients are back: Service Workers, Cache API, Progressive Web (Offline) Apps, IndexedDB, "offline first" encourage developers to put more and more logic on the client. This is exactly how Fat Client is defined.
  9. The year of "UseThePlatform": more and more "enterprise" projects will move away from JavaScript frameworks to plain WebStandards. Frequent migrations are expensive and come with no additional value.
  10. Server Side Rendering (SSR): server side rendering is a viable architecture for SPAs / PWAs. Java Server Pages have a bad name, but are a fast and capable serverside templating technology with great tool support.
  11. Raise of WebComponents (v1): Custom Elements, Shadow DOM together with ES 6 are a viable alternative to JavaScript frameworks. The longer you wait, the leaner your application becomes.
  12. Frameworks known from Java ecosystem like Vaadin Elements and Prime Elements become a popular WebComponent-compatible UI widget provider.
  13. HTTP/2 and Webstandards will dramatically simplify the JavaScript build pipeline. No build is the best build.
  14. JavaScript (ES 7+) will become more and more similar to Java. Now Java developers can become easily webapp developers with 20+ years experience :-)

My 2017 predictions were...


Real World Java EE Workshops [Airport Munich]>

DukeScript - January 29, 2018 04:17 AM
We Love Kotlin & MVVM!

We Love Kotlin!

Kotlin looks like the Java 2.0 everyone was calling for. It is simple (compared to Scala), powerful and expressive (compared to Java) programming language. With its strong company support it has the potential to offer viable and safe alternative for existing Java developers.

Kotlin offers the language we all have been waiting for!

We Love MVVM!

DukeScript project is a long time supporter of using the Model-View-ViewModel approach for coding client side applications in Java. We are obsesed by portability. We target any Java virtual machine in any incarnation. Write your application once and package it for desktop, Android, iOS or a browser. Kotlin targets JVM too and as such we explored ways to bring the whole DukeScript ecosystem to Kotlin - the result is great!

Kotlin brings the DukeScript concepts to absolutely new levels! The language keep type-safety as known from Java, yet it allows the developers to be far more expressive. Kotlin is a natural fit for writing the MVVM models!

The Result

This is the result: kt-mvvm.org. A website!? Yes, a website! We believe kt-mvvm.org can serve as a great starting point. It can help you explore the power of MVVM together with the flexibility of Kotlin. Give it a try!

Continue reading at kt-mvvm.org and contribute by forking the GitHub repositories or talking back.

APIDesign - Blogs - January 25, 2018 06:51 AM
Singletonizer API Design Pattern

Recently I have successfully used the singletonizer API design pattern in Graal's Graph I/O API javadoc. The result ain't that bad, right?

--JaroslavTulach 06:51, 25 January 2018 (UTC)

Adam Bien - January 22, 2018 10:18 AM
Using lit-html with WebComponetns (Custom Elements and Shadow DOM)

WebComponents can use ES 6 Template Literals to render dynamic contents out-of-the-box [see e.g. webcomponents.training ].

In this screencast an efficient (~500 unminified LoC), ES 6 template titeral-based, template library: lit-html was used to render only the "dirty" parts of the DOM tree.

See you at Structuring Single Page Applications (SPA)s / Progressive Web Applications (PWA)s with WebComponents -- the "no frameworks, no migrations" approach, at Munich Airport, Terminal 2 or webcomponents.training (online).


Real World Java EE Workshops [Airport Munich]>

Adam Bien - January 19, 2018 09:11 AM
Web Components in Unsupported Browsers

What happens to Web Components (Custom Elements and Shadow DOM) in unsupported browsers? In this screencast I'm creating a Custom Element with Shadow DOM from scratch and run the sample in Firefox, Safari and Chrome. Patching (aka polyfill) included:

See you at Structuring Single Page Applications (SPA)s / Progressive Web Applications (PWA)s with WebComponents -- the "no frameworks, no migrations" approach, at Munich Airport, Terminal 2 or webcomponents.training (online).


Real World Java EE Workshops [Airport Munich]>

Adam Bien - January 16, 2018 11:37 AM
Metrics, ServerSockets, SSE, WebSockets, Smelling DAOs, JPA Historization, SLSB scalability, Killing EJBs, Logging, ELK, Docker, Kubernetes, Openshift, Licensing, Obfuscation -- or 46th airhacks.tv

This time "Metrics, ServerSockets, SSE, WebSockets, Homework / Code Review of a basic CRUD, Smelling DAOs, JPA Historisation, SLSB design for scalability, Killing EJBs, Logging, ELK, Docker, Kubernetes, Openshift, Licensing, Obfuscation" were discussed.

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

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.
Real World Java EE Workshops [Airport Munich]>

Adam Bien - January 15, 2018 05:41 AM
Web Components On-Demand Workshops

After covering the "basics" in WebStandards igniter, now 50+ episodes of continuous Web Components (Custom Elements, Shadow DOM, CSS 3 styling, Templates, ES 6 imports) coding workshop is available: webcomponents.training. No installation, no dependencies, no builds: only vanilla web (browser) standards, without any external frameworks or dependencies, were used.

Are you already building, or still migrating? Learn once, apply anywhere :-):

Web Components from AdamBien on Vimeo.

See you also at: PWAs / SPAs with Web Components Workshop at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting.
Real World Java EE Workshops [Airport Munich]>

Adam Bien - January 11, 2018 08:34 AM
Pipeline-specific timeouts with CompletableFuture#orTimeout and JAX-RS 2.1

CompletableFuture#orTimeout (>= Java 9) method

"...exceptionally completes this CompletableFuture with a TimeoutException if not otherwise completed before the given timeout. ..."
and is therefore well suited to set a pipeline-specific timeout.

The method AsyncResponse#setTimeout sets the max timeout per request:


import static java.util.concurrent.CompletableFuture.supplyAsync;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
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); //global timeout
        supplyAsync(this::answer).
                thenAccept(response::resume).
                orTimeout(100, TimeUnit.MILLISECONDS). //pipeline specific timeout
                exceptionally((t) -> handleTimeout(response::resume, t));
    }

    Void handleTimeout(Consumer<Response> consumer, Throwable t) {
        consumer.accept(Response.status(503).
                header("cause", "timeout in the pipeline").
                header("exception", t.toString()).
                build());
        return null;
    }

    public String answer() {
        try {
            Thread.sleep(200);
            return "42 + " + System.currentTimeMillis();
        } catch (InterruptedException ex) {
            throw new IllegalStateException("cannot sleep");
        }
    }
}

The request: curl -i http://localhost:8080/completable-timeout/resources/ping returns:


HTTP/1.1 503 Service Unavailable
X-Powered-By: Servlet/4.0
cause: timeout in the pipeline
exception: java.util.concurrent.TimeoutException
(...)

See you at Java EE 8 / Java 9 / Web Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.
Real World Java EE Workshops [Airport Munich]>

Adam Bien - January 10, 2018 08:49 AM
Java 9's StackWalker

The Java 9's StackWalker class allows stack walking without instantiating an Exception.

The following unit test:


package com.airhacks;

import java.lang.StackWalker.StackFrame;
import org.junit.Before;
import org.junit.Test;

public class StackWalkerBasicsTest {

    private StackWalker walker;

    @Before
    public void init() {
        this.walker = StackWalker.getInstance();
    }

    @Test
    public void walkTheStack() {
        this.walker.forEach(this::print);
    }

    void print(StackFrame frame) {
        String className = frame.getClassName();
        String methodName = frame.getMethodName();
        int lineNumber = frame.getLineNumber();
        System.out.println(className + "." + methodName + ":" + lineNumber);
    }
}

Writes the following output:


com.airhacks.StackWalkerBasicsTest.walkTheStack:24
org.junit.runners.model.FrameworkMethod$1.runReflectiveCall:50
org.junit.internal.runners.model.ReflectiveCallable.run:12
org.junit.runners.model.FrameworkMethod.invokeExplosively:47
org.junit.internal.runners.statements.InvokeMethod.evaluate:17
org.junit.internal.runners.statements.RunBefores.evaluate:26
org.junit.runners.ParentRunner.runLeaf:325
org.junit.runners.BlockJUnit4ClassRunner.runChild:78
org.junit.runners.BlockJUnit4ClassRunner.runChild:57
org.junit.runners.ParentRunner$3.run:290
org.junit.runners.ParentRunner$1.schedule:71
org.junit.runners.ParentRunner.runChildren:288
org.junit.runners.ParentRunner.access$000:58
org.junit.runners.ParentRunner$2.evaluate:268
org.junit.runners.ParentRunner.run:363
org.apache.maven.surefire.junit4.JUnit4Provider.execute:252
org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet:141
org.apache.maven.surefire.junit4.JUnit4Provider.invoke:112
org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray:189
org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke:165
org.apache.maven.surefire.booter.ProviderFactory.invokeProvider:85
org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess:115
org.apache.maven.surefire.booter.ForkedBooter.main:75    

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.
Real World Java EE Workshops [Airport Munich]>

Adam Bien - January 09, 2018 10:21 AM
Building a Web Component with Java EE 8 Backend

In this screencast I created a Java EE 8 application with JAX-RS endpoint and JSON-B serialization from scratch, then developed a Custom Element (part of the Web Components specification) which talks to the Java EE 8 backend in 6 mins. No external dependencies were used in frontend and backend.


Real World Java EE Workshops [Airport Munich]>

Adam Bien - January 08, 2018 10:16 AM
Homework Review, JPA history, Business Metrics, Sanity, WebSockets, SSE, XMPP, Logging, Licensing or Questions for the 46th airhacks.tv

Questions for the 46th airhacks.tv:

  1. Surprise
  2. Interactive review of a CRUD homework assignment
  3. JPA history
  4. Testing and embedded integration tests
  5. Getting rid of EJBs
  6. Business metrics with Java EE
  7. THE DAOs smell and Deltaspike Data
  8. Asynchronous JAX-RS resource
  9. Docker swarm vs. kubernetes vs. openshift
  10. SLSB command pattern vs. one bean with multiple methods
  11. How to stay sane (sanity is subjective :-)
  12. Server Push: WebSockets vs. SSE
  13. ServerSocket handling with Java EE -- or how to XMPP with Java EE
  14. Logging with java.util.logging and what about ELK?
  15. Java EE and obfuscation
  16. Licensing Java EE applications
  17. The Pair class and Apache Commons

Any questions left? Ask now: or wait a month.

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


Real World Java EE Workshops [Airport Munich]>

DukeScript - December 24, 2017 05:53 AM
iOS with Multi OS Engine

Christmas 2017 is here and a new version of DukeScript archetypes brings a new way to launch your application on iOS.

Version 0.20 gives you support for Multi OS Engine!

How hard is it to try? Easy, fairly easy. First of all use one of the Maven archetypes to create and build your project:

$ mvn archetype:generate \
  -DarchetypeGroupId=com.dukescript.archetype \
  -DarchetypeArtifactId=knockout4j-archetype \
  -DarchetypeVersion=0.20 \
  -Dmoepath=client-ios \
  -DartifactId=moetest \
  -DgroupId=com.acme.demo \
  -Dversion=1.0-SNAPSHOT
$ cd moetest
$ mvn install

Assuming the Maven build has succeeded, you are ready to execute your project. To do that, you have to select proper target device. You can use moe:listSimulators command of the client-ios subproject. For example, if you are interested in iPhone X, use:

$ mvn -f client-ios/pom.xml moe:listSimulators | grep iPhone.X

The ID of your iPhone X simulator gets printed and you can perform the final step. Launch your application in an iOS simulator:

$ mvn -f client-ios/pom.xml moe:launch -Dmoe.launch.simulatorId=_theSelectedID_

Heuréka. Your application is running:

XCode

After performing the above steps you may feel like a master of the Maven command line interface! However sometimes it is more convenient to use an IDE. As such the DukeScript archetype for Multi OS Engine also comes with support for XCode:

$ open client-ios/xcode/ios.xcodeproj/

In the XCode interface you can configure the deployment options of your application in the traditional XCode way. You can execute your application in the simulator as well as on the device:

Enjoy the new support for Multi OS Engine. Read more about the standard structure of the archetypes in our introduction tutorial. If some detail isn’t clear yet, don’t hesitate checking our getting started guide. Alternatively consider reading the Java Everywhere book.

Merry Christmas and Happy New Year!

Adam Bien - December 21, 2017 02:18 PM
Reactive JAX-RS 2.1 Client Combined with Asynchronous Resource and CompletableFuture

The reactive JAX-RS 2.1 client integrates seamlessly with asynchronous JAX-RS resources and Java 8+CompletableFuture:

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


Real World Java EE Workshops [Airport Munich]>

APIDesign - Blogs - December 18, 2017 11:46 AM
Is Spring the Sole Reason why Java is Becoming the new COBOL?

Is there anything good on Spring that wouldn't be seen ridiculous by non-enterprise-Java users?

--JaroslavTulach 11:46, 18 December 2017 (UTC)

Adam Bien - December 17, 2017 01:11 PM
4th airhacks.fm Episode: "Micro Java EE"

4th episode "Micro Java EE" of airhacks.fm podcast with special guest, Payara CEO, Steve Millidge is available. We discussed Microservices, Cloud Native Java EE, Microprofile, EE4J, Thin WARs, Ueber JARS and Fat JARs.

Subscribe to airhacks.fm podcast via: RSS iTunes


Real World Java EE Workshops [Airport Munich]>

Adam Bien - December 08, 2017 05:20 AM
From BeanShell and Kotlin over Deadlocked Conversations to AWS, Authentication and Java PWAs -- 45th airhacks.tv is available

From BeanShell over deadlocked conversations to AWS and authentication. The 45th airhacks.tv is available:

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

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.
Real World Java EE Workshops [Airport Munich]>

Adam Bien - December 07, 2017 07:57 AM
Serializing and Deserializing a POJO with LocalDate into JSON using JSON-B and Java EE 8

To serialize a POJO with JSON-B from Java EE 8 containing a java.time.LocalDate, you can either use the default format, or specify the serialization format with @JsonbDateFormat annotation:


import java.time.LocalDate;
import javax.json.bind.annotation.JsonbCreator;
import javax.json.bind.annotation.JsonbDateFormat;
import javax.json.bind.annotation.JsonbProperty;

public class Developer {

    public LocalDateTime birthdate;

    @JsonbDateFormat(value = "yyyy-MM-dd")
    public LocalDate firstHack;

    @JsonbCreator
    public Developer(
            @JsonbProperty("birthdate") LocalDateTime birthdate, 
            @JsonbProperty("firstHack") LocalDate firstHack) {
        this.birthdate = birthdate;
        this.firstHack = firstHack;
    }
}

Now the Developer can be serialized and deserialized with a javax.json.bind.Jsonb instance:


import java.time.LocalDate;
import java.time.Month;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;

public class DateSerializationTest {
    
    private Jsonb jsonb;
    
    @Before
    public void init() {
        this.jsonb = JsonbBuilder.
        newBuilder().
        build();
    }

    @Test
    public void serialize() {
        Developer developer = new Developer(LocalDateTime.of(1995, Month.MARCH, 12, 12, 42), 
                LocalDate.of(1998, Month.MARCH, 12));
        String serialized = this.jsonb.toJson(developer);
        System.out.println("serialized = " + serialized);
        assertThat(serialized, containsString("birthdate"));

    }

    @Test
    public void deserialize() {
        String deserialzed = " {\"birthdate\":\"1995-03-12T12:42:00\",\"firstHack\":\"1998-03-12\"}";
        Developer duke = this.jsonb.fromJson(deserialzed, Developer.class);
        assertThat(duke.birthdate.getYear(), is(1995));
    }

}

To run the example as JUnit test, you will need the following dependencies:


<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1</version>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.eclipse</groupId>
    <artifactId>yasson</artifactId>
    <version>1.0</version>
    <scope>runtime</scope>
</dependency>

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


Real World Java EE Workshops [Airport Munich]>

Adam Bien - December 06, 2017 08:11 AM
EM switching, BeanShell, Kotlin, JPA and JDBC, AWS, Authentication, XA, PWAs, SPAs and Java, JSON-B or the last airhacks.tv in 2017

Questions for the 45th, and very last, airhacks.tv show in 2017:

  1. About BeanShell
  2. Header parameters behind apache
  3. Switching between persistence units / EntityManager
  4. Thoughts on Kotlin
  5. Deadlocked conversations
  6. JPA and JDBC pooling
  7. Which AWS instance to take?
  8. Upgrading GlassFish without downtime
  9. Java EE 8 authentication and redirect / forward
  10. Dealing with complex components like tables in the "No Dependencies, Java EE-like" web development
  11. How to handle database connections in the clouds
  12. Two DBs with or without XA
  13. Java's answer to PWAs and SPAs
  14. CompletableFuture, JAX-RS and exception handling
  15. Form authentication and encryption
  16. JSON-B and LocalDateTime mapping
  17. JAX-WS, connection timeout, transaction timeout and dealing with rollbacks

Any questions left? Ask now, or wait a year.

Ask questions during the show via twitter mentioning me: http://twitter.com/AdamBien (@AdamBien) or using the hashtag: #airhacks or the live chat: http://www.ustream.tv/channel/adambien

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.
Real World Java EE Workshops [Airport Munich]>

Adam Bien - December 05, 2017 06:30 AM
Monitoring Java EE Appservers with Prometheus and Grafana

Monitoring und visualising built-in Java EE metrics (payara.fish) with prometheus, grafana and a little help of a 16kB side car firehose:

See you at Java EE Microservices. Is Munich's airport too far? Learn from home: javaeemicro.services and Java EE Performance, Monitoring and Troubleshooting


Real World Java EE Workshops [Airport Munich]>

Adam Bien - December 04, 2017 05:03 AM
Java EE 8 on Java 9 - From Install to Deployment with OpenLiberty Server

Download, install, configure openliberty.io and deploy a sample Java EE 8 application with Java 9 features under 10 minutes with Maven:

See you at Java EE 8 on Java 9, at Munich Airport, Terminal 2
Real World Java EE Workshops [Airport Munich]>

Adam Bien - December 03, 2017 10:47 AM
Using Java 9 HTTP Client with JUnit and Maven

Java 9 comes with built-in HTTP (2) client (incubator status):


import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.time.Duration;
import jdk.incubator.http.HttpClient;
import jdk.incubator.http.HttpRequest;
import jdk.incubator.http.HttpResponse;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertThat;
import org.junit.Before;
import org.junit.Test;

public class HttpClientTest {

    private HttpClient client;

    @Before
    public void init() {
        this.client = HttpClient.newHttpClient();
    }

    @Test
    public void get() throws IOException, InterruptedException {
        URI uri = URI.create("http://airhacks.com");
        HttpRequest getRequest = HttpRequest.newBuilder(uri).
                GET().
                timeout(Duration.ofMillis(500)).
                build();
        HttpResponse<String> response = this.client.send(getRequest,
                HttpResponse.BodyHandler.asString(Charset.defaultCharset()));
        String payload = response.body();
        assertThat(payload, containsString("java"));
    }
}

The HTTP client resides in jdk.incubator.httpclient module and has to be "required". The module-info.java resides in src/main/java:

module com.airhacks.http {
    requires jdk.incubator.httpclient;
}

You will need the maven-compiler-plugin at least in the version > 3.6.1


<build>
<plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.7.0</version>
    </plugin>
</plugins>
</build>    

Now the unit tests compiles, but the execution fails with:


java.lang.NoClassDefFoundError: Ljdk/incubator/http/HttpClient;
    at java.base/java.lang.Class.getDeclaredFields0(Native Method)
    at java.base/java.lang.Class.privateGetDeclaredFields(Class.java:3024)
    at java.base/java.lang.Class.getDeclaredFields(Class.java:2205)    

Although the module is declared, it has to be still added with the following JVM argument:


<properties>
    <argLine>--add-modules jdk.incubator.httpclient</argLine>
(...)
</properties>
See you at Java EE 8 on Java 9, at Munich Airport, Terminal 2
Real World Java EE Workshops [Airport Munich]>

Adam Bien - December 02, 2017 06:20 AM
Time travelling with Bean Validation 2.0 and Java EE 8

With Java EE 8 and Bean Validation 2.0 JSR-380 you can time travel by passing an adjusted java.time.Clock instance to the clockProvider method:


import java.time.Clock;
import java.time.Duration;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
(...)

public class BeanValidationTest {

private Validator validator;

@Before
public void init() {
    ValidatorFactory factory = Validation
            .byDefaultProvider()
            .configure()
            .clockProvider(this::configureClockWithFutureTime)
            .buildValidatorFactory();
    this.validator = factory.getValidator();
}

Clock configureClockWithFutureTime() {
    return Clock.offset(Clock.systemDefaultZone(), Duration.ofSeconds(10));
}


Now you can configure whether your vacations are already over:

        
import java.util.Date;
import javax.validation.constraints.PastOrPresent;

public class Vacations {

    @PastOrPresent
    private Date date;

    public Vacations() {
        this.date = new Date();
    }
}


@Test
public void vacationsAreOver() {
    Set<ConstraintViolation<Vacations>> violations = this.validator.validate(new Vacations());
    assertTrue(violations.isEmpty());
}

...or whether you have to work again:


import java.util.Date;
import javax.validation.constraints.Future;

public class Development {

    @Future
    private Date date;
    public Development() {
        this.date = new Date();
    }
}
//....
@Test
public void weAreWorkingNow() {
    Set<ConstraintViolation<Development>> violations = this.validator.validate(new Development());
    boolean rightMessage = violations.stream().
            map(violation -> violation.getMessage()).
            allMatch(message -> "must be a future date".equalsIgnoreCase(message));
    assertTrue(rightMessage);
    assertFalse(violations.isEmpty());
}

}

To run the bean validation as a JUnit test, you will need the following dependencies:


<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.0.5.Final</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.el</artifactId>
    <version>3.0.0</version>
    <scope>test</scope>
</dependency>

See you at Java EE 8 on Java 9, at Munich Airport, Terminal 2


Real World Java EE Workshops [Airport Munich]>