Sunday, January 25, 2015

CDI events in Swing application to decouple UI and event handling

After having the pleasure building my code around CDI for couple of years, it feels very natural to use it to structure my code according to well-known patterns. CDI is a dependency injection mechanism designed to be used within Java EE application servers, and this could be perceived as a disadvantage. However, I want to show that it can be used and has great potential also in a Java SE application.

What is great about CDI is that it is much more than an injection mechanism. On top of this it provides also an elegant and powerful event passing mechanism. This feature can be nicely combined with Swing to build a GUI application based on MVC pattern.

It is really possible to efficiently combine CDI and Swing framework to build a Java GUI application rapidly and with a clear structure. Stay tuned to find out how...

First of all, the reference implementation of CDI called Weld, is distributed also as a separate library. You may add it to your project and start using it. The only shift from the standard way of running the application is that you need to start a Weld container, which is as simple as this one liner:


import org.jboss.weld.environment.se.StartMain;
public static void main(String[] args) {    StartMain.main(args);
}


To add Weld into your maven application, just add this dependency: org.jboss.weld.se:weld-se:2.2.9.Final

To execute your application code, you should put it in a method which observes ContainerInitialized event:

public void start(@Observes ContainerInitialized startEvent) {
   // code which would be usually in the main() method
}

In the method above, you may initialize your application, build and display the GUI and wait for Swing events.

And here starts the interesting part. I will use CDI event mechanism to implement binding between Swing components and the model using observer pattern. The idea is to trigger custom events whenever a data update should occur and not modify data directly. The controller observes triggered events and executes actions based on the event data. The actions then manipulate the datamodel and send notifications to the view about data updates. See following diagram:



The MVC cycle starts in Swing action listeners, which compose an action object and emit it as a CDI event. The action listener is not bound to any controller code - the controller is bound to event using the CDI mechanism. This completely decouples GUI code from business logic. Following snippet responds to button click event and emits an action to add a value to a counter:

@ApplicationScoped
class MainFrame extends javax.swing.JFrame {
  @Inject Event<ChangeValueAction> changeValueAction;
...
  void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
    changeValueAction.fire(ChangeValueAction.plus(getValue()));
  }
...
}

Here we need to remember that observers of CDI events would be created as new objects for any event triggered, together with all dependencies. I used @ApplicationScoped for MainFrame to ensure that all the code operates on the very same instance of it.

One thing to mention here: in order for CDI to work, instance of MainFrame must be created by CDI, and not using its constructor directly. This is achieved by injecting it to already existing bean - e.g. the one, which observes ContainerInitialized event emitted at start-up.

CDI mechanism dispatches the event to any observer method, which listens for this type of event. We create a controller Application and put the code into an observer method, like this:

public class Application {

...
  public void updateValueWhenChangeValueAction(@Observes final ChangeValueAction action) { 
   ... // controller action
  }
...
}

Finally, the controller updates the model and triggers update of the view if necessary. If we take it further, we may trigger an update event from the controller, which would be observed by the view, in this case the MainFrame component. Or even build a model, which automatically triggers CDI events on update. Thus, controller and view would be completely decoupled and only respond to events - GUI events flowing in the direction from View to Controller, and data-update events flowing from Controller/Model to View.

In summary, CDI event mechanism is very convenient for building an MVC Swing application with View decoupled from business logic. This can be accomplished by running your application inside the Weld CDI container (1 line of code), triggering actions from Swing listeners (2 lines of code) and observing the actions (single method on any CDI-enabled class). The actions take a form of a data bean, which itself is not too many lines of code altogether.


A complete example can be found on github: https://github.com/OndrejM/JavaDecoupledUI-CDI



Additional resources:

Saturday, November 15, 2014

Impressions from Geecon in Prague - Day 2

The day 2 started earlier than the day before. A bit too early for me. While hurrying to catch the beginning of the first presentation, however, a stranger with a big suitcase passed by me in an even greater hurry, a bit confused about which way to take. I grinned to myself as I recollected the familiar face from the speakers' section of Geecon web page. Anyway, speakers are only human too...

Although latest and greatest themes in Java world these days are reactive programming, alternative languages, HTML5 and microservices, I decided to stay close to the ground at first. I chose jBMP presentation to get an update on how thinggus are moving in the old Java enterprise waters.
jBMP looks like a vivid yet mature project and it is promisingly evolving under the RedHat umbrella. In fact, the team have a strategy to focus on knowledge, business goals, their visibility and continuous improvement. Does that ring a bell? To me, that sounds quite close to what agile principles adhere to.

OK,  enough business, we all want some fun too, right? And the next presentation certainly was about how to make fun and even conquer the world with home-made devices. Guys, thank you for bringing the real 3D printer there! It was really a great introduction for a beginner to see how the thing looks like and how it works.
3Dprinter
The real 600€ 3D printer on the scene.
A wooden skeleton with a machinery visible from outside.
Two things to highlight here: a fully functional 3D printer is as cheap as 600€, and "What may fail will fail" - at least until you learn how to use it properly.
Some toolset around 3D printers:
  • 3D editors like blender, tinkercad
  • a slicer (Cura, Repetier-Host) providing more or less a functionality of missing 3D printing dialog
  • and not to forget a taft spray - very handy "tool" to improve performance of a printer when the bed is not heated, no kidding
The iBeacon did not get me yet though. These days it looks like there are many gadgets out there with great potential, but still seeking to find useful applications. iBeacon seems to fall into this category, sorry.

To let the fun continue, I switched then to the latest and greatest trends. Microservices, here I come! The idea to cut a huge system into small and focused microservices is easy to grasp. Knowing when such architecture really helps and how to design it properly is still dark waters for me. Speakers from a company based in Ostrava came to present their approach and experiences. Well, big European mobile operators under the pressure of the market tend to provide constant flow of change requests. To meet their requirements, microservices architecture seems to be a perfect match . Such systems can be maintained in distributed manner, components redeployed separately in different time-frames, failures don't pull the whole system down. Obvious drawback - transactions are hard to manage across multiple services. But as Neal pointed out, maintaining transactions can be really slow and inefficient. Designing operations as idempotent might come to the rescue - how many times have you checked an already locked door just to be sure? Certainly many times and it didn't cost much.

Later I found out why, oh my, why that app server eats so much RAM after I redeploy my applications and that there is Plumbr to aid in searching for mem leaks. Yes, classloading is really tricky even in memory consumption.
Simple rule noted down: always unregister classes you publish to anything on the app server's classpath. For the rest, almighty restart might be cheaper than the time spent on seeking leaks.

Dukescript then steered my course even deeper into the juicy modern stuff. Another attempt to bring Java everywhere, even if compiled to Javascript. Is it still Java then? Well, it seems it passes the duck test: the source code is Java, it executes in JVM, all the tooling of Java works with it. But.
The GUI is based on omnipresent HTML5, meaning that no JavaFX nor Swing components are available. Also, under the hood, the runtime obviously varies according to what different platforms have to offer - JVM where available, otherwise Dalvik on Android, RoboVM on iOS, BackToBrowser Javascript VM in modern browsers. Yes, I wrote Javascript VM. Java can really be executed even in a browser without any plugin, just plain Javascript. I have seen it working so it must be true! It still takes some time to download 2MB of scripts, but wait, this is still an unoptimized proof of concept, which already works well! It is another hit nailing Javascript to become an assembler of the web.

No more time to mention Erlang, Go, Rust, Scala, Kotlin nor Java 8. Luckily Bruce Eckel had a wonderful closing speech about all of them. Even more, he mentioned the driving forces that lead people to design new languages. Better support for parallelism, readability, even purity in design are among them. But purism proved not to be very helpful and mostly did not work. Software transactional memory has not grown to be really usable concept as well. On the other hand, inherent support of parallelism becomes a valuable selling point of modern languages, like Erlang. Even Java 8 has now support for parallel streams. Though, Java 8 stays way too boring. Maybe "Thinking in Kotlin" will be the next book by Bruce Eckel? Anyway, after all that hassle, Python stays Bruce's favourite language - no wonder, more than 20% women in the active community are and will stay another great selling point. Applause to Mr. Eckel for his insights and thank you for reading!

Tuesday, November 4, 2014

Impressions from Geecon in Prague - Day 1

Eventually, a famous Java conference came to Prague. After planning to travel to Krakow some time, it was suddenly to be here at my finger tips. As a fresh freelancer, not yet fixed to any long-term project, I decided to invest the money to inhale the atmosphere of a big conference and enjoy presence of all the people interested in Java and all the tech stack around it. So here I was to see and listen to Neal Ford - the one from ThoughtWorks, so adored for their Radar. I came alone, as freelancers often tend to, expecting to meet some familiar faces from my previous jobs. What followed was much beyond my expectations, as so many of them started suddenly popping up. Great feeling to meet so many pleasant people after 2 years spent away from Prague.

"So this is the water!" - I told to myself while Neal was talking about continuous delivery, acceptance tests and all the supportive things aiding in software development, wiring together the effort of developers, testers, operations and project managers. Warm feeling rose even higher when the very book I'm currently reading appeared on one of Neal's slides. He hit the nail again, when he stated that meta-work is more fun than real work. And it is often not productive at all, when the fun is not guided well. Damn, that is so true. Even though claiming to seek improvement in my daily work, the biggest power to drive me into my pet projects is the desire to do fun stuff to complement boring daily work. Boy, that's a relief that I'm not the only one having problems with lack of fun! But then, banks are not ACID? Again, not ACID?? Then, how the hell can I be sure to get my salary on my account at the end of the day? Wait, banks are running auditing jobs after working hours to put everything in order. ACID is slow and inefficient in real world. Eventual consistency is enough in most cases. But remember to schedule the auditing jobs, guys, just in case. Immutable database - an oxymoron, sure? No, Datomic is here to keep track of all the past changes. The SQL is dead, long live NoSQL! :) Jokes aside, now I seriously started thinking that some NoSQL solutions have really something to offer. Read NoSQL distilled if you want to know more...

Some more insights from Day 1:

"Customers want consistency. But when they find out what would they lose to get it, they tend to sacrifice consistency without a doubt." (see also CAP theorem)
   - Neal Ford

"Architecture of software projects tends to resemble structure of the organization" (Conway's Law)
"Design enough, early enough"
"Don't document things evident from the code"
"Keep a decision log to remember reasons for past decisions"
    - Janne Sinivirta

"Many companies want to be agile, but do not realize what definitely is NOT agile"
   - Katarzyna Mrowca

Afterwards, some home-baked cookies from Czech speakers - perfcake is an interesting tool to monitor throughput, memory consumption and other performance characteristics. It comes with some nice additional features like CSV reports and warm-up detection. Finally, I was looking forward to assertThat(I). understandUnitTesting(). On top of that, I've learned how NOT to write unit tests, which may be even more helpful. I've also found out that TestNG is good, because "it is much better". Maybe true, maybe not, I would suggest to the speaker to add more reasoning to be more convincing.

However, what certainly is true, is that I enjoyed the day and even more interesting sessions were to come the day after. I took a donut on my way home and headed to the train station filled with joyful emotions.

Tuesday, July 2, 2013

Deproxy a lazily loaded JPA reference (using standard Java and JPA API)

When tried to tune our near-production application, we came to problem when a single entity reference (not a collection) is loaded lazily. We used inheritance with this entity and hibernate JPA provider (as probably any other provider) inserts a proxy object into referencing entity instead of reference to real object loaded from database (as it is not yet loaded).

We came to a problem because we were casting super class to subclasses using instanceof. The problem is that proxy class is already a subclass and cannot be cast to a sibling class. It is a proxy only to super class instance, but it's not possible to access methods of superclasses directly. The proxy never gets converted to real subclass. The problem is specified here, here and here. All described solutions depend on hibernate non-standard API to retrieve deproxied instance.

However, after lots of thinking...

... I found a solution to deproxy a class using standard Java and JPA API. Tested with hibernate, but does not require hibernate as a dependency and should work with all JPA providers.

Only one requirement - its necessary to modify parent class (Address) and add a simple helper method.

General idea: add helper method to parent class which returns itself. when method called on proxy, it will forward the call to real instance and return this real instance.

Implementation is a little bit more complex, as hibernate recognizes that proxied class returns itself and still returns proxy instead of real instance. Workaround is to wrap returned instance into a simple wrapper class, which has different class type than the real instance.

In code:

class Address {
   public AddressWrapper getWrappedSelf() {
       return new EntityWrapper(this);
   }
...
}

class AddressWrapped {
    private Address wrappedAddress;
...
}

To cast Address proxy to real subclass, use following:

Address address = dao.getSomeAddress(...);
Address deproxiedAddress = address.getWrappedSelf().getWrappedAddress();
if (deproxiedAddress instanceof WorkAddress) {
WorkAddress workAddress = (WorkAddress)deproxiedAddress;
}

Tuesday, March 12, 2013

Properties and config in persistence.xml

List of elements in persistence.xml

<!-- turn off 2nd level caching (optional), values: NONE, ALL, DISABLE_SELECTIVE, ENABLE_SELECTIVE,  -->
        <shared-cache-mode>NONE</shared-cache-mode>
<!-- desired provider (optional), if not present, default provider will be used -->
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<!-- optional declaration of used datasource, if not specified, connection properties must be specified, otherwise will use specified datasrouce in container -->
<jta-data-source>jdbc/cbn</jta-data-source>

List of standard properties

Driver: <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
URL: <property name="javax.persistence.jdbc.url" 
       value="jdbc:derby://localhost:1527/chapter02DB;create=true"/>
User: <property name="javax.persistence.jdbc.user" value="APP"/>
Password: <property name="javax.persistence.jdbc.password" value="APP"/>

Hibernate properties

Debug SQL:  <property name="hibernate.show_sql" value="true"/>
Schema generation (optional):
            <!-- create the database schema automatically, values: create-drop, update -->
            <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
Dialect:   <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />

EclipseLink properties

Schema generation (optional):
      <!-- create the database schema automatically, values: create-tables, drop-and-create-tables -->
      <property name="eclipselink.ddl-generation" value="create-tables"/>

Resources

  • http://antoniogoncalves.org/2009/07/05/jpa-2-0-standard-properties-in-persistence-xml/
  • Netbeans persistence.xml editor

Wednesday, September 5, 2012

Transparently transfer data from server script to client javascript

When developing a web application, sometimes I ran into need to pass information from server to a JavaScript component at the moment when the page is built. I believe that general solution is to use a <script> element in the HTML page, which initializes the component with data, which is generated by server-side script (PHP, Groovy, Python, etc.). However, when writing reusable JavaScript components, this is not a maintainable solution.

The problem is that the component may be used multiple times (or even not at all), but every time the component is included in the HTML page, the same initialization script is executed. It would work if every component was identified by a unique ID, however, this does not seem to be a good practice.

As I always try to improve what appears cumbersome, in my projects I'm using a declarative approach within HTML body. This approach reverses the responsibility of initializing JavaScript component from the generated page to an external js file. Therefore, the only <script> element placed within the HTML page is a link to external js file, which calls an initializer function after document is loaded.

Final solution may look like this:

<div class="my-javascript-button">
    <div class="config" style="display: none;">
        <div class="title">Go to www.google.com</div>
        <a class="url" href="http://www.google.com"/>
    </div>
</div>

or

<div class="my-javascript-button">
    <div class="config" style="display:none;">
        <!-- JSON object: -->
  { "title" : "Go to www.google.com",
          "url" : "http://www.google.com"
        }
     </div>
</div>


To read about best way how to code it, jump directly to Golden Mean Solution.

Description of the Problem:

  • Data in server script, which generates page dynamically (PHP, Ruby, Python,...)
  • HTML page generated by the script
  • Javascript included into HTML page (JavaScript is static, not generated)
Therefore configuration from server script can be passed to the HTML page (rendered in the page), but not to static JavaScript script.
We want to create encapsulated HTML+ JavaScript components, which can be inserted once or multiple times into generated HTML page and can be passed a configuration object from server side script to configure their behavior.

Simple solution using JSON (still cumbersome) 

Requirements

  • requires JSON and random generation support in server script
  • requires piece of javascript code in HTML page
Both requirements make the solution a bit cumbersome, but understanding this solution will help understand the idea.

Description

  1. For each piece of HTML code (which places the component into generated page), generate a random textual identifier
    • def randomId = getRandomId('my-javascript-button-')
  2. Mark that piece of HTML with randomId, either by attribute id, or as css class, or other attribute:
    • <div class="my-javascript-button ${randomId}">
          ... rest of html goes here
      </div>
  3. In the external JavaScript file for the component, create an initializer function for this configuration type, which takes two parameters: randomId to identify the target html element, and an object holding the configuration:
    • function initializeMyJavascriptButton(id, config) {
      }
  4. Call the initializer function from the page, passing in randomId and script object encoded to JSON:
    • example in grails GSP:
      initializeMyJavascriptButton("${randomId}" ,  ${config as JSON} );

Results

  • JavaScript code, which can be efficiently passed configuration
  • HTML element and its configuration are visually separated in HTML source code as HTML and JavaScript blocks - they are coupled by generated random identifier

Declarative Solution using invisible DOM structure

The simple JSON solution works, but is not easily maintainable nor readable. Generated identifiers - do we really need this? Cannot we just mark all components with a common class? Where is the configuration of the component, in a different HTML block? Why not put it directly at the place where the component is declared, as its attributes, or at least in nested block? Also, generating JavaScript code is not a neat idea, is there a way to put all code into a separate file, or even a library?

After all, the basic question: Why do we need JavaScript just to declare a component together with its attributes, when HTML is rich enough to do it?

Imagine this declaration:

<div class="my-javascript-button" title="Go to www.google.com" 
      url="http://www.google.com">
</div>

See what I mean?

Although above code is not a valid XHTML code, we can get really close to something like it while not breaking XHTML rules. In fact, we can use a nested invisible element, which would be accessible in DOM tree from JavaScript, but will not affect how the page is rendered.

Requirements

  • custom technique in server script to generate HTML elements to reflect data on server
  • custom technique to read values from html elements in the page
Both these custom techniques can be extracted into a server-side and JavaScript API, which could be reused.

Description

  1. For each piece of HTML code (which places the component into generated page), create a nested div element with special class "config", which is given css style "display: none;" :
    • div with class "config" will be invisible in the document and will not have any impact on how the page is generated:
      <div class="my-javascript-button">
          <div class="config" style="display: none;">

          </div>
      </div>
  2. Inside div with class "config", you may put any DOM elements, identify them using class attribute, and then assign a value to them, either as one of valid attributes, or as a body of the element:
    <div class="my-javascript-button">
        <div class="config" style="display: none;">
            <div class="title">My title</div>
            <a class="url" href="http://my.url"/>
            <ul class="listOfTargets" >
                <li>target1</li>
                <li>target2</li>
            </ul>

        </div>
    </div>
  3. If you need to store nested objects, you may also nest elements, or even nest list of elements. You may in fact create any HTML structure, which will somehow store desired values. You may make it more readable using appropriate HTML elements (ul for lists, a for urls), or always use div elements, as more appropriate
  4. In external JavaScript file, define an initializer, which can be executed to initialize configuration for all target elements in the html page. This initializer will find all the target elements, and for each of them it will find "config" element and read values from DOM subtree of this element
  5. The initializer function will be executed once after html page is loaded, (e.g. using jQuery's $(document).ready() ). Best is to execute the initializer within the external JavaScript file and ensure that it is executed only once (you may use a global variable, or mark all config elements on first execution, so that config is read only once)

Results


  • configuration is always stored within the target html element, regardless if the browser supports javascript (although this is rather irrelevant, as the configuration has no use without javascript)
  • configuration is declarative, therefore it can be parsed with any alternative technique or even with external HTML analyzer (e.g. in unit tests)
  • coupling between the html element and its configuration is visible using DOM inspector right within the html element
  • no standard way of writing and reading configuration to and from html elements
  • may be slower than direct conversion of server data to JSON
As this solution is pretty nice and readable, it may be sufficient or even desired in some cases. However, it brings some cons compared to the Simple JSON solution: it is easier to read the code, but takes longer to write it, and also reading the configuration by JavaScript may be slower than parsing JSON.

Therefore, as always, there is a golden mean that would solve everything. Or is there?



Golden Mean Solution - declarative approach with JSON


The idea here is to standardize the way how data is stored within the nested config element used in the Declarative solution. Instead of writing config using DOM elements, we would use JSON, which can be easily read by JavaScript.

Requirements

  • As in Simple JSON solution, requires JSON support in server script, but does not rely on random numbers and does not require putting any JavaScript to initialize a component
  • As in the Declarative solution, requires some custom code. However, this time, no special technique is necessary on server side, and on client side, only a function to retrieve configuration block within a component declaration is necessary (couple of lines of reusable JavaScript code)

Description

This solution is similar to the Declarative solution. In fact, it is also declarative, but uses one simple trick together with JSON:

Instead of encoding data to a HTML structure, we may encode the configuration into JSON and put it as a body of the config element. like this:

<div class="my-javascript-button">
    <div class="config" style="display: none;">

        ${it as JSON}     </div>
</div>

JSON should be compliant with XHTML and should not break its structure. If we're not sure, it is better to put the JSON code into a CDATA block.