Adam Bien's Weblog

Thursday Aug 28, 2014

DTO: The Exceptions From The Rule

Most JavaEE applications do not need a Data Transfer Object at all. Built-in support for JSON and XML does the transport job already. However, DTOs are still useful for special case handling like:

  1. Transferring a custom subset, superset (multiple entities) of entity data at once
  2. Dedicated optimizations like sophisticated JAXB mapping, customization of binary transfer e.g. hooks in http://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html
  3. Role-dependent dataset: specific roles are only allowed to see specific data attributes. However, a http://docs.oracle.com/javaee/7/api/javax/json/JsonObject.html would solve such a job perfectly as well.
  4. Client-dependent view: native clients may request a different view to data as it can be provided by stock entities. Client may require a DTO per view independently of the organization on the server.
  5. Client technology may expect different contents e.g. a JavaFX client may expect a http://docs.oracle.com/javafx/2/api/javafx/beans/property/StringProperty.html instead of a plain String.

DTOs do not have to be justified in all the use cases above. The reason for introduction is obvious: a DTO is significantly different to the persistent domain object, or the technology forces you to introduce a DTO.

[See also an in-depth discussion in the "Real World Java EE Patterns--Rethinking Best Practices" book (Second Iteration, "Green Book"), page 273 in, chapter "Data Transfer Object", particularly the strategies "Generic DTO", "Client-specific DTO"]

See you at Java EE Workshops at MUC Airport or on demand and in a location very near you: airhacks.io!


Special Events: Java 8 with Java EE 7: "More Power with Less Code", 13th October, 2014 and Java EE 7: "Testing and Code Quality", 14th October, 2014

A book about rethinking Java EE Patterns

Monday Aug 25, 2014

JavaEE 7 Retired The DTO

The classic DTO solves the following problem:

"You want to transfer multiple data elements over a tier."

Back in the days a DTO was implemented as a Serializable anemic Java class only equipped with field accessors.

In Java EE the https://jax-rs-spec.java.net became a de-facto standard for remoting, so the implementation of Serializable interface is no more required. To transfer data between tiers in Java EE 7 you get the following options for free:

  1. JAXB: the popular application servers offer JSON, XML serialization for "free".
    
    @Entity
    @XmlRootElement
    @XmlAccessorType(XmlAccessType.FIELD)
    @NamedQuery(name = Registration.findAll, query = "SELECT r FROM Registration r")
    public class Registration {
    
        private static final String PREFIX = "com.airhacks.workshops.business.registrations.entity.Registration.";
        public static final String findAll = PREFIX + "all";
    
    
        @Id
        @GeneratedValue
        @XmlTransient
        private long id;
    
        @XmlTransient
        @Transient
        private BiFunction<Boolean, Integer, Integer> taxCalculator;
    
        private int numberOfDays;
        private int numberOfAttendees;
        private boolean vatIdAvailable;
        
        //...
    
    }
    
    
    [Registration.java from https://github.com/AdamBien/javaee-bce-archetype]
  2. With the introduction of Java API for JSON Processing, you can also directly serialize parts of your objects into JSON:
    
    @Path("health")
    @Produces(MediaType.APPLICATION_JSON)
    public class HealthResource {
    
        @Inject
        ServerWatch watch;
    
    
        @GET
        @Path("/current-memory")
        public JsonObject availableHeap() {
     JsonObjectBuilder builder = Json.createObjectBuilder();
    	builder.add("Available memory in mb", this.watch.availableMemoryInMB()).
    	add("Used memory in mb", this.watch.usedMemoryInMb());
    	return builder.build();
        }
        
        //...
    }
    
    
    [HealthResource.java from project ping]

Both approaches transport the data without any binary coupling to the origin object. The decoupling is even higher, as it was the case with the "traditional" (=code duplication) DTO implementation.

[See also an in-depth discussion in the "Real World Java EE Night Hacks--Dissecting the Business Tier" book, page 273 in, chapter "Data Transfer Object"]

See you at Java EE Workshops at MUC Airport or on demand and in a location very near you: airhacks.io!


Special Events: Java 8 with Java EE 7: "More Power with Less Code", 13th October, 2014 and Java EE 7: "Testing and Code Quality", 14th October, 2014

A book about rethinking Java EE Patterns

Saturday Aug 23, 2014

NetBeans Rocks: Installation and Setup

NetBeans installation is fast and easy: no plugins, no configuration:

Enjoy Java hacking!


Special Events: Java 8 with Java EE 7: "More Power with Less Code", 13th October, 2014 and Java EE 7: "Testing and Code Quality", 14th October, 2014

A book about rethinking Java EE Patterns

Friday Aug 22, 2014

Mocking JPA EntityManager with Query

EntityManager is an interface and can be easily mocked out with https://code.google.com/p/mockito/.

At the same time the EntityManager is also a factory, which creates Query instance, which in turn creates results. Mocking a query involves therefore a three step (=three lines process):


public class RegistrationsTest {

    Registrations cut;

    @Before
    public void init() {
        this.cut = new Registrations();
        this.cut.priceCalculator = mock(VatCalculator.class);

        this.cut.em = mock(EntityManager.class);

		//...
    }

    void mockQuery(String name, List<Registration> results) {

        Query mockedQuery = mock(Query.class);
        when(mockedQuery.getResultList()).thenReturn(results);
        when(this.cut.em.createNamedQuery(name)).thenReturn(mockedQuery);

    }

After this step you can easily return whatever results you like:


    @Test
    public void convertEmptyListToJson() {

        mockQuery(Registration.findAll, Collections.EMPTY_LIST);

        final JsonArray result = this.cut.allAsJson();
        assertNotNull(result);
        assertTrue(result.isEmpty());
    }

If you would like to ignore the parameters, or react to specific query parameters, the method Query::setParameter needs to be mocked as well:


  when(mockedQuery.setParameter(Matchers.anyString(), Matchers.anyObject())).thenReturn(mockedQuery);

See the entire unit test: RegistrationsTest.java. The whole example is available as maven archetype.

Usually complex queries are going to be encapsulated in dedicated controls, so it is easier to mock out the whole control instead.

Interested in Java EE Code Quality and Testing? See you at http://workshops.adam-bien.com/about-testing.htm or regular http://airhacks.com


Special Events: Java 8 with Java EE 7: "More Power with Less Code", 13th October, 2014 and Java EE 7: "Testing and Code Quality", 14th October, 2014

A book about rethinking Java EE Patterns

Thursday Aug 21, 2014

How To Deal With J2EE and Design Patterns

Patterns are clearly defined as:

"In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design."
[http://en.wikipedia.org/wiki/Software_design_pattern].

If you encounter a design challenge, you are supposed to search in a catalog for the description, compare the Motivation (Forces) or Applicability. If they match, you can apply the ideas from the pattern to solve your problem. Patterns are not a genius solution to a problem, rather than a standardized compromise. Usually you are going to implement flavors of the design patterns without even knowing it.

In Java Enterprise community patterns seem to have their own live. They are going to be applied regardless their problem definition or context. The most misused pattern in the Java Enterprise community is the DTO. DTO was clearly defined as a solution for a distribution problem. DTO was meant to be a coarse-grained data container which efficiently transports data between processes (tiers). In J2EE DTO was absolutely necessary, CMP Entity Beans were not serializable. Martin Fowler also defines defines DTO as:

"An object that carries data between processes in order to reduce the number of method calls."
According to the definitions DTOs were never meant to carry data within a JVM...

Even more suspicious is the popularity of the DAO pattern. The solution statement starts as:

"The DAO implements the access mechanism required to work with the data source. The data source could be a persistent store like an RDBMS, an external service like a B2B exchange, a repository like an LDAP database, or a business service accessed via CORBA Internet Inter-ORB Protocol (IIOP) or low-level sockets."

DAO was always meant as a procedural encapsulation of inconvenient or not standardized data sources. An object oriented flavor, the Domain Store pattern uses DAO to access JDBC and provides an object oriented access to the store. Interestingly the Domain Store looks like a slightly modified version of the ...JPA Entity Manager.

Some projects are wrapping Entity Manager with an empty delegate and call it "DAO". Such an approach is actually the opposite of the origin intention...

Java EE 5 killed the majority of the J2EE Patterns. Their "Problem" and "Forces" descriptions do not apply any more. Java EE 6 and 7 killed the remaining patterns, only the Application Service is still useful.

If you take the pattern definitions seriously and look at some "enterprise" projects you are not going to understand the design. Patterns are going to be applied without having a problem and are considered as future "insurance": "...in case JPA disappears, I only have to change the implementation of the DAO..."

How to deal with patterns? Apply them if you encounter a problem. Java EE design is "bottom-up" rather than "top-down", as it was the case in the old J2EE world.

[See also an in-depth discussion in the "Real World Java EE Night Hacks--Dissecting the Business Tier" book, page 259 in, chapter "Data Access Object"]

We spend some time to eliminate J2EE and GoF patterns one by one with Java EE 7 and Java 8 during the Java EE Architectures "airhacks" workshops at MUC airport.


Special Events: Java 8 with Java EE 7: "More Power with Less Code", 13th October, 2014 and Java EE 7: "Testing and Code Quality", 14th October, 2014

A book about rethinking Java EE Patterns

Wednesday Aug 20, 2014

igniter.fx 1.9.2 released--The Java 8 Edition

A new version of igniter.fx -- the maven "wizard" which creates a sample Java FX MVP application is released.

The 1.9.2 edition demonstrates afterburner's 1.6.0 capabilities like asynchronous FXML loading and view-dependent object injection.


@FXML
Pane lightsBox;
//...
LightView view = new LightView((f) -> red);
view.getViewAsync(lightsBox.getChildren()::add);


A passed constructor parameter (an int in the example below) can be conveniently injected into the presenter. Each presenter instance receives its own value:

public class LightPresenter{

    @FXML
    Circle light;

    @Inject
    int red;


See the full code: DashboardPresenter.java

igniter.fx is open source: https://github.com/AdamBien/igniter.fx

To create a an igniter.fx 1.9.2 maven project execute the following command from the CLI:


mvn archetype:generate -Dfilter=com.airhacks:igniter

You can also clone the sample source code directly from: https://github.com/AdamBien/followme.fx.

followme screenshot

See you at Java EE Workshops at MUC Airport or on demand and in a location very near you: airhacks.io!


Special Events: Java 8 with Java EE 7: "More Power with Less Code", 13th October, 2014 and Java EE 7: "Testing and Code Quality", 14th October, 2014

A book about rethinking Java EE Patterns

Friday Aug 15, 2014

Special Business Logic Treatment Considered Harmful in Java EE

Prior Java EE 5 (2006, see the whole history in: http://realworldpatterns.com) your application code had to realize J2EE interfaces and was forced to implement several infrastructural methods. The amount of plumbing was significant and the business logic was hard to understand.

With the introduction of annotations in JDK 1.5 and the introduction of Dependency Injection paired with Convention over Configuration in Java EE 5 your application code is only dependent on annotations which are comparable to the Marker Interface pattern. Java EE 6 went even further, so you can implement large portions of business logic without being even dependent on any Java EE annotations.

Also the main goal of the outdated http://www.corej2eepatterns.com was the separation of "clean" business logic and the "polluted" J2EE infrastructure. Now the majority of the J2EE patterns solves no more existing problems, mostly problems being already solved in the recent Java EE releases.

With Java EE 5+ any attempt to separate your business logic from Java EE infrastructure will result in empty delegates, parallel and identical object hierarchies, increased complexity and harder maintainability.

Stop plumbing, focus on business logic and added value to your customers :-)

See you at Java EE Workshops at MUC Airport or on demand and in a location very near you: airhacks.io!


Special Events: Java 8 with Java EE 7: "More Power with Less Code", 13th October, 2014 and Java EE 7: "Testing and Code Quality", 14th October, 2014

A book about rethinking Java EE Patterns

Wednesday Aug 13, 2014

Every Ping Needs A Floyd - v0.0.1 Released

ping is a Java EE 7 application which provides app server health-checks exposed as REST services.

floyd is the corresponding Java FX client (a single, self-contained jar) which searches for ping services in the network and visualizes the health (CPU, Memory, Ping Time) conveniently.

ping screenshot

The first version is available for download.

After the download execute: java -jar floyd-app.jar with Java 8.

See you at Java EE Workshops at MUC Airport or on demand and in a location very near you: airhacks.io!


Special Events: Java 8 with Java EE 7: "More Power with Less Code", 13th October, 2014 and Java EE 7: "Testing and Code Quality", 14th October, 2014

A book about rethinking Java EE Patterns

Friday Aug 08, 2014

afterburner.fx 1.6.0 released

The 1.6.0 release of the afterburner.fx, a 2.5 class MVP framework for JavaFX is available.

The main feature of this release is asynchronous loading of views and presenters:

  1. Support for lazy initialization and asynchronous view construction
  2. "per-instance" injection of parameters into a view

floyd was built with the new 1.6.0 features. floyd is the front end for ping.

See you at Java EE Workshops at MUC Airport particularly at JavaEE UI day!


Special Events: Java 8 with Java EE 7: "More Power with Less Code", 13th October, 2014 and Java EE 7: "Testing and Code Quality", 14th October, 2014

A book about rethinking Java EE Patterns

Wednesday Aug 06, 2014

The Return Of JSPs In HTML 5?

In it's early days JSPs were misused for the realization of business logic. Any complex code enclosed in scriplets is hard to write, test and so maintain.

However: JSPs are perfectly suitable for delivery of HTML 5 documents:

  1. You have full control over HTML markup. There is no hidden code generation in place.
  2. No magic: JSPs become Servlets. Usually you can even look at the generated code in case something feels strange.
  3. After the initial invocation, JSPs are as performant as Servlets.
  4. JSPs just serve strings, so no components have to be hold in memory -- the memory requirements are low.
  5. IDE support, debugging and performance analytics for JSPs are superb.
  6. JSPs even support lambdas in EL.
  7. JSPs can be perfectly used in the "logic free" mode, just as a powerful templating language.
  8. You can introduce custom tags for the encapsulation of recurring functionality.
  9. CDI managed beans and so whole Java EE components can be easily exposed to JSPs

A simple POJO:


public class Greeting {

    private String title;
    private String content;

    public Greeting(String title, String content) {
        this.title = title;
        this.content = content;
    }
    public String getTitle() {
        return title;
    }
    public String getContent() {
        return content;
    }
}

Could be easily exposed by a CDI presenter / backing bean:

@Model
public class Index {

    public List<Greeting> getGreetings() {
        List<Greeting> greetings = new ArrayList<>();
        greetings.add(new Greeting("short", "hi"));
        greetings.add(new Greeting("casual", "hello"));
        greetings.add(new Greeting("formal", "welcome"));
        return greetings;
    }
}

...and conveniently rendered using a JSP:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<body>
    <h1>Hello JSP</h1>
    <ul>
        <c:forEach var="message" items="${index.greetings}">
    	    <li><c:out value="${message.title}"/> - <c:out value="${message.content}"/></li>
        </c:forEach>
    </ul>
</body>

See you at Java EE Workshops at MUC Airport or on demand and in a location very near you: airhacks.io!


Special Events: Java 8 with Java EE 7: "More Power with Less Code", 13th October, 2014 and Java EE 7: "Testing and Code Quality", 14th October, 2014

A book about rethinking Java EE Patterns

realworldpatterns.com
...the last 150 posts
...the last 10 comments
Links
License