Adam Bien's Weblog

Tuesday Sep 02, 2014

The Perfect JavaEE Microservice

Microservices are a self-contained and easily understandable realization of domain logic, highly independent of each other.

The definition above could be shortened as: "Maximal Cohesion, Minimal Coupling" (MC/MC), which in turn defines a Java EE business component. A Java EE component is an ordinary Java package organized with the MC/MC idea in mind, ideally with predefined internal structure like e.g. BCE / ECB.

According to the above definition, a perfect JavaEE microservice is single ECB component within a WAR deployed on a single server/domain. In such a case you could release and redeploy individual components (aka microservices) independently. Direct method invocations between WARs are not possible, so the WARs are forced to use e.g. JAX-RS to communicate with each other.

Monolithic deployment of multiple components within a single WAR still remains the simplest possible solution for a mainstream project without any additional requirements. Unfortunately, simplest possible solutions are usually not buzzword-compatible :-).

[See also an in-depth discussion in the "Real World Java EE Patterns--Rethinking Best Practices" book (Second Iteration, "Green Book"), page 419 in, chapter "Entity Control Boundary (ECB)—The Lean Way"]

See you at Java EE Workshops at MUC Airport, particularly at the Java EE User Architectures workshop!


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

Sunday Aug 31, 2014

Opinionated JavaFX 8--virtualJUG Session

Opinionated Java FX applications, behind the scenes of afterburner.fx and walk through the floyd at virtualjug.

Thanks http://virtualjug.com for the invitation!

See you at Java EE Workshops at MUC Airport, particularly at the Java EE User Interfaces workshop!


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 30, 2014

My JavaOne 2014 Sessions: JavaFX, Nashorn and Unorthodox Practices

  1. Session ID: UGF8872 Session Title: Free Java Tools for Maven and Java EE Venue / Room: Moscone South - 200 Date and Time: 9/28/14, 11:00 - 11:45
  2. Session ID: CON2265 Session Title: Productive JavaFX 8 Venue / Room: Hilton - Plaza A Date and Time: 9/30/14, 16:00 - 17:00
  3. Session ID: CON2301 Session Title: Unorthodox Enterprise Practices Venue / Room: Parc 55 - Cyril Magnin II/III Date and Time: 10/1/14, 10:00 - 11:00
  4. Session ID: CON2131 Session Title: Java EE 8 Community Update and Panel Venue / Room: Parc 55 - Cyril Magnin II/III Date and Time: 10/2/14, 11:30 - 12:30
  5. Session ID: CON2266 Session Title: Enterprise Nashorn Venue / Room: Parc 55 - Cyril Magnin II/III Date and Time: 10/2/14, 14:30 - 15:30

See you at JavaOne in San Francisco, Munich: http://airhacks.com, or each first Monday of the month at 6 P.M CET live: http://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 29, 2014

New Pattern, Play, Broken EJB Proxies, Network Files, Huge Apps--Or The 6th Airhacks Q & A

  1. What do you think about play framework as compared to JavaEE ? I often heard that JavaEE is heavyweight in development and therefore internet-startups uses other framework stacks like play, rails, meteor etc
  2. What would be the proper approach to read a network file in a J2E environment?
  3. “Open Extended Persistence Context In View” - a new pattern?
  4. ID generation in a cluster.
  5. State computation (daily limits) and scalability vs. consistency.
  6. Is JSF compatible with Bootstrap?
  7. The JSP / HTML 5 drama: The Return Of JSPs in HTML 5
  8. “How are you going to structure your application if application is going to be really huge. Are you still going to keep it in one big war?” blog comment by Thomas
  9. Commercial vs. free tools: gist discussion
  10. Is “Mixing storage/transfer concerns an antipattern”? Rafael Chaves, @abstratt
  11. Broken EJB proxies? Brad Davies, @bradsdavis

See also https://gist.github.com/AdamBien/8735518ee671d7edb778

The questions above are going to be answered during the next "Airhacks Q & A" http://airhacks.io live. You can subscribe to the channel and / or for the next event: http://www.ustream.tv/channel/adambien.

If you miss a question, write a comment on this post, tweet your question with the hashtag "#airhacks" or mention me https://twitter.com/AdamBien.

The best of all: you can ask the questions live, during the show using the chat: http://www.ustream.tv/channel/adambien, twitter (hashtag "#airhacks") or (the best option): using channel ##airhacks on http://freenode.net.

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

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

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