Java EE 8, JSON-B and java.util.Optional Serialization and Deserialization

A class with java.util.Optional field:


public class MessageWithOptionalField {

    private String content;
    private Optional<String> optionalInfo;

    public MessageWithOptionalField() {

    }


    public MessageWithOptionalField(String content) {
        this.content = content;
        this.optionalInfo = Optional.empty();
    }

    public MessageWithOptionalField(String content, String optionalInfo) {
        this.content = content;
        this.optionalInfo = Optional.of(optionalInfo);
    }
    
    public String toString() {
        return "MessageWithOptionalField{" + "content=" + content + ", optionalInfo=" + optionalInfo + '}';
    }
}        

...serializes into JSON using JSON-B and PrivateVisibilityStrategy (omitting superfluous accessors) via JAX-RS resource:


@GET
public List<MessageWithOptionalField> messageWithOptional() {
    return Arrays.asList(new MessageWithOptionalField("hello without world"), new MessageWithOptionalField("hello", "world"));
}  
into the following JSON string:

[{"content":"hello without world"},{"content":"hello","optionalInfo":"world"}]    
The deserialization from a json without the optional field, e.g. {"content":"hello"} and e.g. using the following JAX-RS endpoint:

@POST
public String save(MessageWithOptionalField message) {
    return message.toString();
}

yields: MessageWithOptionalField{content=hello, optionalInfo=null}

A json string containing the optional value: {"content":"hello","optionalInfo":"world"} yields: MessageWithOptionalField{content=hello, optionalInfo=Optional[world]}

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.


NEW: Online Workhop Effective WebApps without Frameworks is also coming to: MUC Airport.

Airport MUC workshops: Web (SPA, PWAs, Offline, Desktop, Mobile) Applications Essentials and Effective Web Applications. No migrations. #usetheplatform

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

From Java Ray Tracers to AR, MR, VR and XR--airhacks.fm podcast

A conversation (subscribe) with Josh Marinacci, (@joshmarinacci) about the first Java class, 1995 and early Java, Ian Smith, building ray tracers with JDK 1.0, why Sun had great programmers, speed vs. safety, Snow Crash without cell phones, metaverse scalability, 3d interface with Swing and Mozilla with hubs, project wonderland and open wonderland, windows look and feel with Swing, Amy Fowler, Jeff Dickins from Swing Team, Window native controls look with Swing, progress bar is the hardest thing, Matisse GUI builder, JSR-296, Swing Application Framework, JSR-295 beans binding, smartphones killed Swing, Java FX as flash competitor, Tesla car configurator with Swing, f3 and Chris Oliver, Java Store before Mac Store, Palm and WebOS, WebOS built-in Java, why HP cancelled WebOS, LG WebOS, Awesome Box 5000 widgets, point and shoot camera with Android at Nokia research, high websockets scalability with pubnub, block functions and edge computing, VR, AR, mixed reality at mozilla, MDN -- the JS JCP, JavaScript like Java, JavaScript -- no batteries included, anonymous inner classes in JS, AR, VR, MR, XR, the XR-spec with security backed in, WebXR Device API:, VRML and GLTF, USDZ, Firefox refactoring, servo and rust, lightspeed adoption of CSS grid, trying VR now, Firefox reality , browsing 2d in 3d, a call for VR activities, themed multi-user virtual places: Mozilla Hubs, be social, have fun, airhacks.tv in 3D, three.js and a-frame for content creation, amazon sumerian, web assembly -- the XR accelarator, web assembly and asm, browser as VM, contact josh: https://twitter.com/joshmarinacci, mail: josh@josh.earth.

Subscribe to airhacks.fm podcast via: RSS iTunes

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.


NEW: Online Workhop Effective WebApps without Frameworks is also coming to: MUC Airport.

Airport MUC workshops: Web (SPA, PWAs, Offline, Desktop, Mobile) Applications Essentials and Effective Web Applications. No migrations. #usetheplatform

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

Java EE 8: converting java.util.Properties or Map into JsonObject

Java EE 8 / JSON-P 1.1 come with a convenience JsonCollector, which simplifies the conversion of Properties and Maps into an JsonObject


import java.util.Properties;
import static java.util.stream.Collectors.toMap;
import javax.json.Json;
import static javax.json.Json.createValue;
import javax.json.JsonObject;
import javax.json.JsonValue;
import javax.json.stream.JsonCollectors;

//...
        
@GET
@Path("/system-properties")
public JsonObject systemProperties() {

    Properties properties = System.getProperties();
    Map<String, JsonValue> map = properties.entrySet().
            stream().
            collect(toMap(k -> k.toString(), v -> createValue(v.getValue().toString())));
    return map.entrySet().stream().collect(JsonCollectors.toJsonObject());
}    

@GET
@Path("/environment-variables")
public JsonObject environmentVariables() {
    Map<String, JsonValue> environment
            = System.getenv().
                    entrySet().
                    stream().
                    collect(toMap(Map.Entry::getKey, v -> createValue(v.getValue())));
    return environment.entrySet().stream().collect(JsonCollectors.toJsonObject());
}


The code is taken from: https://github.com/AdamBien/ping

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


NEW: Online Workhop Effective WebApps without Frameworks is also coming to: MUC Airport.

Airport MUC workshops: Web (SPA, PWAs, Offline, Desktop, Mobile) Applications Essentials and Effective Web Applications. No migrations. #usetheplatform

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

WebStandards with WeightLess Backend in 25mins -- InfoShare 2018 live coding

Full Profile Java EE 8 + MicroProfile setup, REST, Prometheus metrics, no-frameworks, HTML 5 frontend with Docker deployment.

In 25 mins and from scratch:

Checkout a deeper dive Architecting Future-Proof Fullstack Applications -- from infoShare 2018

Interested in pragmatic, "no migrations" backends and frontends? Join Web applications 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.


NEW: Online Workhop Effective WebApps without Frameworks is also coming to: MUC Airport.

Airport MUC workshops: Web (SPA, PWAs, Offline, Desktop, Mobile) Applications Essentials and Effective Web Applications. No migrations. #usetheplatform

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

Clearer JAX-RS 2.1 Client Error Messages

If you try to connect with a too slow HTTP endpoint or too ambitious configured timeouts:


import java.util.concurrent.TimeUnit;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import org.junit.Before;
import org.junit.Test;

public class JAXRSClientExceptionTest {

private WebTarget airhacksTarget;

@Before
public void initClient() {
    Client client = ClientBuilder.newBuilder().
    
            connectTimeout(2, TimeUnit.MILLISECONDS).
            readTimeout(2, TimeUnit.MILLISECONDS).
                
            build();
    this.airhacksTarget = client.target("https://jakarta.ee");
}

@Test
public void connect() {
    this.airhacksTarget.request().get(String.class);
}
}

You will get the ProcessingException with wrapped cause:

    javax.ws.rs.ProcessingException: java.net.SocketTimeoutException: connect timed out
	at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:284)
	at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:278)
	at org.glassfish.jersey.client.JerseyInvocation.lambda$invoke$1(JerseyInvocation.java:767)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:316)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:298)
	at org.glassfish.jersey.internal.Errors.process(Errors.java:229)
	at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:414)
	at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:765)
	at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:428)
	at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:324)
	at com.airhacks.JAXRSClientExceptionTest.connect(JAXRSClientExceptionTest.java:32)
    (...)	
Caused by: java.net.SocketTimeoutException: connect timed out
	at java.net.PlainSocketImpl.socketConnect(Native Method)
	at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
	at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
	at java.net.Socket.connect(Socket.java:589)
(...)

A try-catch block:


@Test
public void connectWithNicerError() {
    try {
        this.airhacksTarget.request().get(String.class);
    
    } catch (ProcessingException ex) {
		Throwable cause = ex.getCause();
        String errorName = cause.getClass().getSimpleName(); //null checks skipped
        String message = errorName + ":" + cause.getMessage();
        System.out.println(message);
        //rethrow or handle
    }
        
}

...makes the error message clear:

SocketTimeoutException:connect timed out or SocketTimeoutException:Read timed out

See you at "Build to last" effectively progressive applications with webstandards only -- the "no frameworks, no migrations" approach, at Munich Airport, Terminal 2 or effectiveweb.training (online).


NEW: Online Workhop Effective WebApps without Frameworks is also coming to: MUC Airport.

Airport MUC workshops: Web (SPA, PWAs, Offline, Desktop, Mobile) Applications Essentials and Effective Web Applications. No migrations. #usetheplatform

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

From Modern UI over ThreadPools to SSE -- 55th airhacks.tv

This time we are covering:

"SSE, Interactive Code Review, Fluid Calculations, Modern UI with Java, ThreadPools and Paths, JDBC Health, EclipseLink vs. Hibernate, Closing Streams" (topics and questions), or 55th airhacks.tv

Any questions left? Ask now: https://gist.github.com/AdamBien/4a3ad4c69c1ccfd0d3b3e02a21adfefb 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.


NEW: Online Workhop Effective WebApps without Frameworks is also coming to: MUC Airport.

Airport MUC workshops: Web (SPA, PWAs, Offline, Desktop, Mobile) Applications Essentials and Effective Web Applications. No migrations. #usetheplatform

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

A Note on Data Transfer Objects (DTO)s

  1. Data Transfer Objects (DTOs) are introduced to decouple (JPA) entities from the UI
  2. DTOs are also motivated by their typesafe nature
  3. Lacking typesafety, JSON-P JsonObjects are not used as DTOs
  4. Most DTOs are exposed as HTTP/JSON
  5. Often 3rd party libraries are used to map a DTO into a JSON
  6. Sometimes DTOs are called Value Objects
  7. The vast majority of DTOs remains identical to entities over the entire lifecycle of a project
  8. Copying data between DTOs and entities requires series of getter-setter invocations
  9. DTOs are growing, the mapping logic is extracted into dedicated "mappers"
  10. DTOs and mappers introduce a significant amount of untested code, which disturbs the code coverage statistics
  11. Getters and setters, constructor tests are written to increase the code coverage
  12. Now: structural JPA entity code changes, affect DTOs, mappers and the corresponding unit tests
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.


NEW: Online Workhop Effective WebApps without Frameworks is also coming to: MUC Airport.

Airport MUC workshops: Web (SPA, PWAs, Offline, Desktop, Mobile) Applications Essentials and Effective Web Applications. No migrations. #usetheplatform

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

Architecting Future-Proof Fullstack Applications -- from infoShare 2018

Architecting Future-Proof Fullstack Applications, from infoShare 2018, on-stage live hacking WebStandards frontend with Microservice backend in 50 minutes:

Interested in "no frameworks, no migrations" frontends? Checkout: effectiveweb.training/ ...or pragmatic microservices? Checkout: javaeemicro.services

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.


NEW: Online Workhop Effective WebApps without Frameworks is also coming to: MUC Airport.

Airport MUC workshops: Web (SPA, PWAs, Offline, Desktop, Mobile) Applications Essentials and Effective Web Applications. No migrations. #usetheplatform

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

Java, Caching and How the Information Flows--airhacks.fm podcast

An airhacks.fm podcast conversation with with Cameron Purdy, (@cpurdy) about: graphics programming, Wolfenstein, peek and pokes, programming in one sitting, structured programming and Pascal, no gosub, just goto, thoughts on Java, forming Tangosol in 2000, developers don't have budgets, J2EE scalability problems, TCPM, TCMP at XKCD, unlimited connections via UDP and early Java, Tangosol and Oracle coherence, distributed caching, learning on the job, dying servers, messaging and message order, blockchain and distributed caching, consistent caching, merkle tree, shrinking data domains, partition assignment strategies, partitioning and sharding, JINI and JavaSpaces, JGroups and Bela Ban, GigaSpaces, job scheduling, resource leasing, "Compound interest is the most powerful force in the universe" [Albert Einstein], survivor bias, usability optimizations, focus on application specific challenges, searching for exponential impact, having fun in team, attracting good engineers, daily improvements, the progress experience, avoid being noticed, fixing everything, the CAP truism, a different take on consistency, Java is not a concurrent language, there is no concept of "now", guaranteed order is the expensive part, consistency is the side effect of order, information is flowing, former Senior Vice President of Java Development still likes hacking, Cameron's new startup xqiz.it. Contact cameron on twitter: @cpurdy

Subscribe to airhacks.fm podcast via: RSS iTunes

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.


NEW: Online Workhop Effective WebApps without Frameworks is also coming to: MUC Airport.

Airport MUC workshops: Web (SPA, PWAs, Offline, Desktop, Mobile) Applications Essentials and Effective Web Applications. No migrations. #usetheplatform

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

Browser Storage Size Estimation

Used and available browser storage size estimation:

Watch remaining 81 episodes at: effectiveweb.training. Also checkout airhacks.io and particularly webstandards.training and webcomponents.training workshops.

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.


NEW: Online Workhop Effective WebApps without Frameworks is also coming to: MUC Airport.

Airport MUC workshops: Web (SPA, PWAs, Offline, Desktop, Mobile) Applications Essentials and Effective Web Applications. No migrations. #usetheplatform

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

Online Workshops
realworldpatterns.com
...the last 150 posts
...the last 10 comments
License