Sparkling Services

WebServices and REST services have come a long way in Java. Nowadays, it’s very easy to create a webservice. Basically, it’s adding an annotation to a method. All you need is a servlet container, such as Tomcat. But then, configuring and running a servlet container isn’t really simple. Chances are you think it’s simple, but that’s because most Java programmers have been using application servers for years. They already carry everything they need in their toolbox. But from a newbie’s point of view, things look a little different.

Spark is a nice alternative making it really easy to write a REST service:

import static spark.Spark.*;

public class HelloWorld {
    public static void main(String[] args) {
        get("/hello", (req, res) -> "Hello World");
    }
}

That’s all you need to implement a web server that serves a single REST service. Start the program, open your browser and enter the URL to test your REST service:

http://localhost:4567/hello

Notice that this is a main method. You don’t have to deploy a war file. Instead, Spark follows the idea popularized by Spring Boot: it embeds Jetty in a jar file. When I tested the code, Spark took virtually no time to start. That’s the nice thing about embedding Jetty: it has a really small footprint. I started to use an embedded Jetty for my web applications years ago. It’s a really fast alternative if you don’t need a full-blown application server.
Continue reading

Non-Object-Oriented Java

Hardly ever have I seen code reuse in business-related code. That’s a puzzling observation, given that Java programmers are expected to write object-oriented programs for many reasons, code reuse being an important reason. My puzzlement even grew when I started to analyze my former company’s SAP programs. They aren’t object oriented. Quite the contrary, the coding conventions discourage using ABAP objects. Does this make the ABAP code any worse?

I don’t think so. The average ABAP program is focused on business code. Plus, ABAP programmers usually prefer customizing over programming. SAP delivers a framework covering most of the technical issues, so there’s no point in creating your own class hierarchy of business classes. It’s better to take the data structures and objects SAP gives you and to customize them. More often than not, the result violates requirements concerning cognitive ergonomics, usability and performance, but that’s not today’s topic. SAP’s ABAP framework allows for efficient programming, and it’s perfectly possible to write huge programs without resorting to object orientation. Dropping OO is even a sensible choice.
Continue reading

OmniFaces CombinedResourceHandler Gives Your Application a Boost

OmniFaces 2.1 is soon to be released. Time to present a useful OmniFaces component which has been improved in version 2.1: the CombinedResourceHandler.

The CombinedResourceHandler reduces page load times significantly by combining the countless resource files of a JSF page into one or two larger files, which can be loaded and processed much more efficiently. Since version 2.1, these files can optionally be cached on the server side, giving the application another boost. Server side caching reduces the time needed to display the BootsFaces showcase by a second. If that doesn’t sound much: believe me, your customers will notice the difference. It’s a difference if the page takes one or two seconds to display.
Continue reading

Type Erasure Revisited

You can’t beat type erasure, they say. Information about generic Java data types is lost during compilation, and there’s no way to get it back. While that’s absolutely true, Mahmoud Ben Hassine and I found a tiny loophole which allowed us to improve Mahmoud’s jPopulator framework tremendously. Under certain circumstances, it’s possible to find about the type which is supposed to be erased. So jPopulator is able to populate not only simple beans, but also complex generic data types.

Mahmoud agreed to write an article about the ups and downs of our investigation. You’ll see it wasn’t exactly easy-going. Along the way, you’ll learn about the loophole allowing us to beat type erasure.
Continue reading

How Static or Dynamic Typing Affects Your Coding Style

Erik Osheim has written an excellent article comparing dynamic and static typing. More precisely, he compares Python to Scala. What makes his article interesting, is that he focuses on the consequences of the type systems. The article you’re currently reading is a (not so) short summary of Eriks article, plus a few thoughts of mine.
Continue reading

Should You Avoid or Embrace “Static”?

More often than not, the keyword static confuses Java programmers. As a consequence, Ken Fogel asks his students never to use static in Java unless explicitely told to do so. While that’s a good hint for starters, it’s only part of the story.

Funny thing is, I recommend to use static as often as possible. There’s a twist: Never use static variables, but always use static methods.
Continue reading

Creating Annotations is Fun! Too Much Fun?

Once again Lukas Eder has written an article I mostly agree with – but not completely. Lukas claims Annotations have become an antipattern.

The nice thing about annotations is you can define your own annotation. It’s easy, and it’s extraordinary popular among framework designers. So we see annotations in the bean validation API, in JPA, in CDI, in JSF, in EJBs, WebServices and Rest and much more.

Annotations – a programming language of their own

While I absolutely love these annotations, there’s a problem: they are starting to become a programming language of their own. What do you think about something like this?

@NotNull
@Size(min=6,max=10)
@Pattern("[a-zA-Z]+")
@Inject @UserID
@Column(name="userID")
private String userID;

@Valid
@ManagedProperty("#{customer.account}")
@OneToOne
private Account account;

Continue reading

Newsflash: Java to Scala Converter

JavaToScala.com may help you to learn Scala. It takes an arbitrary Java class and converts it to Scala.

Naturally, this approach emphasizes the similarities between the two languages. The few examples I tried were converted into solid Scala classes, but nothing out of the ordinary. The converter won’t introduce a case class or a trait if it seems fit. However, emphasizing the similarities is not a bad thing: many Java programmers are scared away from Scala after seeing advanced code.

The core of the converter is another project available on GitHub: Scalagen is a Maven plugin converting Java source code to Scala. The project home page states that the converter isn’t perfect, but may introduce errors for certain Java constructs, so I take it the same applies for JavaToScala.com. But still, it’s an interesting way to get familiar with Scala.

BootsFaces 0.6.6, Easter Edition

Fork me on GitHubStop looking for our Easter egg: you’ve found it. The BootsFaces team celebrate Easter with a new version of their responsive JSF framework. By now, BootsFaces is available on Maven Central, and in a couple of days it’ll arrive on the jCenter repository.

Basically, BootsFaces 0.6.6 is a bug fix release. There are also a number of minor improvements, such as adding the style attribute to a number of components that ignored in in the previous version.
Continue reading

What’s New in PrimeFaces 5.2?

The next version of PrimeFaces is planned to be released on April 6, 2015. Continuing what already has become a tradition, BeyondJava.net gives you a round-up of what’s new and noteworthy in in PrimeFaces 5.2.

The list isn’t complete, by the way. Among other things the PrimeFaces team have improved the screen reader support and closed more than 200 issues.
Continue reading

How to Embed a Servlet or an HTML Page in a JSF 2.x View

As trivial as the task may sound, hardly anybody seems to embed a servlet or an HTML page in a JSF view. That’s the impression my team and I got after a lengthy Google investigation. Finally we found OmniFaces, better known as the Swiss Army Knife of JSF.

OmniFaces is one of those JSF libraries that are different: It’s not about visual widgets (not in the first place, at least), but it’s full of other useful stuff. There’s the FullAjaxExceptionHandler BeyondJava.net reported about in an earlier article. There are several useful converters that make using comboboxes (or SelectOneMenus in JSF speak) much simpler. There’s the useful CombinedResourceHandler I’m going to cover soon. And there’s the component of the day: <o:resourceInclude />.
Continue reading

AngularFaces 2.1.4 published

Fork me on GitHubToday I’ve published AngularFaces 2.1.4 on MavenCentral. It should also arrive on JCenter within the next few days. The new version fixes a couple of annoying bugs, so I recommend to update soon.

New, improved documentation

There’s also news from the documentation page of AngularFaces. Currently, it’s moving from www.angularFaces.com to https://www.angularFaces.net. The new documentation page is an AngularFaces application featuring BootsFaces 0.6.5, PrimeFaces 5.1 and Omnifaces 2.1. Among other things, running on a web server makes it possible to show interactive live demos instead of static screenshots.

Continue reading

Scala.js

When I heard about Scala.js a couple of years ago, I thought to myself: “Well, that’s an interesting project, but sure it’s bound to fail”. Only it didn’t. The other day I’ve stumbled over an impressive technology demo. You can write a ray tracer in object-oriented and functional Scala, compile it to Javascript an run it in the browser. Ray tracers are power-hungry, so the good performance shows that Scala.js generates surprisingly good code. I didn’t run benchmarks, but judging from what I’ve seen I believe Scala.js is “good enough” on a modern browser. Native Javascript may be faster, but in many cases you won’t notice the difference.
Continue reading

Getting Started with BootsFaces: Responsive Design

BootsFaces is a JSF framework adding Bootstrap to JSF pages. One of the more attractive traits of Bootstrap is its built-in responsive design. Probably you already know the idea: screen elements are resized to fit on smaller screens. If everything else fails, Bootstrap starts to stack screen elements over each other if they can’t be displayed side-by-side. Usually, that doesn’t look as good as the original design aimed at larger screen estates, but the bottom line is that the application can be used even on small phones. Maybe you have to scroll a lot on a small device, but that’s a small price to pay. Without Bootstrap you’d have to scroll both horizontally and vertically, which is clearly worse.

Let’s write a simple BootsFaces application showing how easy it is to add responsive design to JSF applications. I’ve prepared a repository on GitHub, so you can check out the source codes used in this article. Today’s project is the subfolder ResponsiveDesign of this repository.
Continue reading

Newsflash: Google to Support AngularJS 1.x Longer, Dropping AtScript

According to Jaxenter, the AngularJS team reacted to the harsh reaction of the Javascript community on Google’s AngularJS 2.0 plans.

As a consequence, they decided to support AngularJS 1.x longer, giving companies who’ve already invested in AngularJS applications more time to migrate to AngularJS 2.0. Plus, they decided to drop AtScript. Instead, the team decided to merge AtScript with Microsoft’s TypeScript. That’s a pity because AtScript seemed to be an interesting language, but at the same time it’s good news since alternative browser languages start to cannibalize each other’s market share.

Read the full story at Jaxenter.

By the way, the original AngularJS 2.0 plans BeyondJava.net reported about have changed considerably in the meantime. The AngularJS team listened to the feedback of the community and adapted their former, much more radical ideas in order to align better with existing editors, existing tools and older browsers. Read the current state of the discussion at the AngularJS design documents folder.

BootsFaces 0.6.5 Published on Maven Central

After a while, our team is finally proud to publish the new v0.6.5 release.
This time we added more examples, a couple of handy components and exciting features. Here’s a short summary of the highlights:

  • Font Awesome Support ( #23 , #39 , #53 )
  • compatibility to both Oracle Mojarra and Apache MyFaces
  • improved AngularFaces Integration
  • Primefaces integration
  • Omnifaces integration
  • and better documentation.

Continue reading

Newsflash: Hope for Groovy

Pivotal’s recent announcement to drop both Groovy and Grails shook the Groovy community. The entire Java community, actually. Can we afford to invest in an open source project run by a company? Companies are sold and bought all the time, and the new owner may drop the previous owner’s pet projects without warning. That’s the story of Groovy and Grails.

I can’t help but wonder what that means to other projects. What if management decides to cut costs by releasing a project to freedom? You get the point: this move cost a lot of trust in frameworks run by a company. Any company, actually.

Among other things, the affair shows that open source isn’t a free lunch. Why don’t you support a project you’re fond of? It’s easy: tweet about it, or report a bug. You may even complain about the lousy documentation. That’s not a big deal, but it helps the developers a lot. They learn their documentation is read, and start to improve it.

At least in the case of Groovy, there’s hope. Guillaume Laforge, the public face of Groovy, has found a new job at a company that uses Groovy for their products. He won’t be able to work on Groovy full-time, but still, Guillaumes statement on reddit sounds encouraging:

Of course Groovy lives on! And I’ll still be wearing my Groovy hat on, even if only part time during my day job at Restlet. The project will indeed continue to be developed, with new features, performance improvements, more Java 8 related features, etc. We’re also going to announce in the coming days that the project is joining a foundation, to make the project more resilient!

That’s the second good news, provided it comes true. The Groovy project isn’t going to be homeless, but will be run by a foundation, which hopefully gives it an opportunity to flourish as lively as it did in the past.

Dig deeper

Guillaume Laforge joins Restlet
Let’s make APIs Grooyer
Discussion on reddit on the topic
InfoQ on the future of Groovy
Pivotal’s announcement to drop Groovy and Grails

Hibernate Cheat Sheet

Recently I wanted to write a small state-of-the-art Hibernate application. To my surprise, I didn’t find information about Hibernate 4 and the XML-free documentation easily. It’s all there, but it’s buried under tons of old-school tutorials and Spring tutorials. So here’s my small collection of what I’ve found out.

I’ll describe both the standard JPA and pure Hibernate approach. That’s because I didn’t find out how to configure JPA without XML yet.
Continue reading

AngularFaces 2.1 Blurs the Difference Between JSF and HTML

I always considered JSF to be to verbose, to ceremoniously. AngularFaces allows you to write JSF pages that almost look like HTML pages.

What it looks like

JSF 2.2 introduced the new HTML5 style of writing JSF pages. Basically, that’s ordinary HTML decorated by a few JSF attributes. AngularFaces picks up this idea and takes it to another level. For example, look at this snippet from my Tetris demo that demonstrates both BootsFaces and AngularFaces 2.1 at the same time:

  <body style="width:1000px" 
        ng-controller="AngularTetrisController" 
        ng-app="AngularTetris" 
        addLabels="false">
    <container>
      <form>
        <tabView>
          <tab title="Settings">
            <b:panelGrid colSpans="3,9">
              <selectBooleanCheckbox value="{{settingsBean.preview}}" 
                                     caption="preview (not implemented yet)" />
              <selectBooleanCheckbox value="{{settingsBean.ignoreGravity}}" 
                                     caption="gravity"/>
              <inputText value="{{settingsBean.numberOfColumns}}" 
                         label="columns (width)"/>
              <inputText value="{{settingsBean.numberOfRows}}" 
                         label="rows (height)"/>
            </b:panelGrid>
            <b:commandButton value="apply changes" ng-show="showApplyButton" />
            <messages showSummary="true" showDetail="true" globalOnly="true"  />
          </tab>
        </tabView>
      </form>
    </container>
  </body>

The embedded preview doesn’t work perfectly because of the scrollbar. Visit http://angularfaces.net/tetris for a better experience.


Continue reading

Final Version of AngularFaces 2.1 Published

Fork me on GitHubAngularFaces 2.1 is more than a bug fix release. It contains a couple of features I deliberately postponed in order to get a thoroughly tested version 2.0 out in times. The list below counts no less than 15 improvements. One of the improvements has nothing to the with code: I put AngularFaces 2.1 under an Apache V2 licence, which is much more liberal than the GPL licence of the previous version.

Examples and code snippets

Pictures say more than words, so let’s start with a couple of screenshots and code snippets. Click the tabs to see the source codes.

ng-table is a great client-side datatable component written in AngularJS. Thus, it’s a natural fit to AngularFaces.

<table ng-table="tableParams" class="table ng-table-responsive">
  <tr ng-repeat="car in $data">
    <td data-title="'Brand'" sortable="'brand'">{{car.brand}}</td>
    <td data-title="'Type'" sortable="'type'">{{car.type}}</td>
    <td data-title="'Year'" sortable="'year'">{{car.year}}</td>
    <td data-title="'Color'" sortable="'color'">{{car.color}}</td>
    <td data-title="'Mileage'" sortable="'mileage'">{{car.mileage}}</td>
    <td data-title="'Price'" sortable="'price'">{{car.price}}</td>
    <td data-title="'Fuel'" sortable="'fuel'">{{car.fuel}}</td>
    <td data-title="'Select'">
      <button class="carFilterButton" jsf:action="#{selectionBean.showDetails()}"
        ng-click="selectionBean.carAsJSon=afToJson(car);">show me!</button>
    </td>
  </tr>
</table>
<input jsf:value="{{selectionBean.carAsJSon}}" style="display:none" addLabel="false"/>
<prime:messages globalOnly="false" />
var app = angular.module('CarShop', ["angularfaces", 'ngTable', 'ngTableExport']).
controller('CarShopController', function($scope, $filter, ngTableParams) {
  // This initializes the Angular Model with the values of the JSF bean attributes
  initJSFScope($scope);
  $scope.activeSelections=0;
  
  $scope.select = function(car) {
    console.log(car);
    $scope.selectionBean.carAsJSon=car;
    return true;
  }
  
  $scope.showIfSet = function(ngmodel) {
    if (typeof(ngmodel)=='undefined') {
      return "hidden";
    }
    if (null==ngmodel || ngmodel=="") {
      return "hidden";
    }
    $scope.activeSelections++;
    return "";
  }
  
  $scope.filterBoxStyle=function(){
    var width=400+100*$scope.activeSelections;
    return "" + width + "px";
  }
  
    $scope.tableParams = new ngTableParams({
        page: 1,                  // show first page
        count: 10,                // count per page
        sorting: { brand: 'asc' } // initial sorting
    }, {
        total: $scope.carPool.selectedCars.length, // length of data
        getData: function($defer, params) {
          params.settings().counts=[5, 10, 'all']; // todo: that's a hack!
          var rows = $scope.carPool.selectedCars;
          if (params.filter()) rows=$filter('filter')(rows, params.filter());
          if (params.sorting()) rows = $filter('orderBy')(rows, params.orderBy());
          var page = params.page();
          var pageLength = params.count();
          if (pageLength=='all') 
          $defer.resolve(rows);
          else
            $defer.resolve(rows.slice((page - 1) * pageLength, page * pageLength));
        }
    });

})

Many business applications consist of long forms. AngularFaces simplifies writing such forms by adding labels and messages (including internationalization) automatically. If possible, it validates the form on the client, thus reducing the server load.

     <prime:panel header="If you want to buy this car..."
        ng-show="{{doShowDetails()}}" styleClass="{{showDetailsClass()}}">
        <prime:panelGrid columns="3" style="border: 0px;">
          <prime:inputText value="#{carBean.brand}" />
          <prime:inputText value="#{carBean.type}" />
          <prime:inputText value="#{carBean.price}" />
          <prime:inputText value="#{carBean.mileage}" />
          <prime:inputText value="#{carBean.color}" />
          <prime:inputText value="#{carBean.year}" />
          <prime:inputText value="#{carBean.fuel}" />
        </prime:panelGrid>
      </prime:panel>
      <prime:panel
        header="... we need some informations about where to deliver it:"
        ng-show="{{doShowDetails()}}" styleClass="{{showDetailsClass()}}">
        <prime:panelGrid columns="3" style="border: 0px;">
          <prime:inputText value="{{customerBean.lastName}}" />
          <prime:inputText value="{{customerBean.firstName}}" />
          <prime:inputText value="{{customerBean.dateOfBirth}}" />
          <prime:inputText value="{{customerBean.emailAddress}}" />
          <prime:inputText
            value="{{customerBean.iAgreeToTheTermsAndConditions}}" />
        </prime:panelGrid>
      </prime:panel>
      <prime:panel
        header="Please confirm you are a human by answering this simple question:"
        ng-show="{{doShowDetails()}}" styleClass="{{showDetailsClass()}}">
        <prime:panelGrid columns="3" style="border: 0px;">
          <prime:outputLabel for="captchaField"
            value="{{customerBean.captchaQuestion}}" />
          <prime:inputText required="false" id="captchaField"
            value="{{customerBean.captcha}}"
            ng:captcha="{{customerBean.expectedCaptcha}}" />
        </prime:panelGrid>
      </prime:panel>
      <prime:commandButton 
        action="#{customerBean.buy(carBean)}"
        value="Buy this car! (Non-AJAX)" ajax="false"
        styleClass="carFilterButton {{showDetailsClass()}}" ng-disabled="myForm.$invalid"
        style="{{myForm.$invalid?'color:#888':''}}" />
var app = angular.module('CarShop', ["angularfaces"]).
controller('CarShopController', function($scope, $filter) {
  // This initializes the Angular Model with the values of the JSF bean attributes
  initJSFScope($scope);
  $scope.doShowDetails = function() {
    if (typeof($scope.customerBean)=="undefined"||
      typeof($scope.customerBean.showDetails)=="undefined") {
      return false;
    }
    return $scope.customerBean.showDetails;
  }
  $scope.showDetailsClass = function() {
    if ($scope.doShowDetails()) 
      return "";
    else
      return "hidden";
  }
  $scope.showFinishedTransactionClass = function() {
    if ($scope.doShowDetails()) 
      return "hidden";
    else
      return "";
  }
  
  $scope.buttonEnabledStyle = function() {
    if ($scope.myForm.$invalid) 
      return "color:#888";
    else
      return "";
  }

});

app.directive('captcha', function() {
  return {
    require : 'ngModel',
    link : function(scope, elm, attrs, ctrl) {
      ctrl.$parsers.unshift(function(viewValue) {
        if (typeof(viewValue)=="undefined" || viewValue==null) {
          ctrl.$setValidity('captcha', false);
          return viewValue;
        }
        if (viewValue!=attrs["captcha"]) {
          ctrl.$setValidity('captcha', false);
          return viewValue;
        } else {
          ctrl.$setValidity('captcha', true);
          return viewValue;
        }
      });
    }
  };
});

The JSF view below shows how to exchange arbitrary data between client and server using the new <ngsync /> tag.

The form contains seven input fields, so the XHTML code repeats itself. I omitted most of the repetitions. The XHTML code uses the new HTML5 style of JSF 2.2:

    <ngsync value="{{staticOptionBean.brands}}"   direction="serverToClient" once="true" />
    <ngsync value="{{staticOptionBean.colors}}"   direction="serverToClient" once="true" />
    <ngsync value="{{dynamicOptionBean.types}}"   direction="serverToClient" cacheable="true" />
...
    
    <!-- ngsync doesn't transport the entire bean recursively, so we have to list each attributes we want to send -->
    <!-- will be fixed in a future AngularFaces version -->
    <ngsync value="{{filterBean.type}}"     direction="serverToClient" cacheable="true" />
    <ngsync value="{{filterBean.brand}}"    direction="serverToClient" cacheable="true"/>
    <ngsync value="{{filterBean.counter}}"  direction="serverToClient" cacheable="true" />
    <!-- end of ngsync workaround -->
    
    <ngsync value="{{filterBean}}" direction="clientToServer" id="filterSyncID" />
    <ngsync value="{{settingsBean}}" direction="clientToServer" id="settingsID" />
    
    <div class="carFilterBox"> 
      <div style="font-weight:bold;font-size:125%">What kind of car are you looking for?
      </div> 
      <div>
        <table style="border-spacing:10px">
          <tr>
            <td width="150px">Brand</td>
            <td width="110px">Type</td>
            <td width="100px">Price</td>
          </tr>
          <tr>
            <td>
              <select id="filterbrand" ng-model="filterBean.brand" ng-options="brand for brand in staticOptionBean.brands track by brand"
                                    ng-change="filterBean.type=''">
                     <option value="">-- choose brand --</option>
              </select>
            </td>
            ...
          </tr>
          ...
           <tr>
            <td>
              <select ng-model="filterBean.yearText" ng-options="year for year in staticOptionBean.years track by year">
                     <option value="">-- choose year --</option>
                 </select>
            </td>
            <td>
              <button ng-show="activateAJAXButton()" class="carFilterButton" jsf:action="index.jsf">update counter
                <f:ajax render="angular" execute="filterSyncID settingsID"></f:ajax>
              </button>
            </td>
            <td >
              <button id="listCarsID" class="carFilterButton" jsf:outcome="table.jsf" >{{filterBean.counter}} cars</button>
            </td>
          </tr>
        </table>
      </div>
    </div>
var app = angular.module('CarShop', [ "angularfaces" ]).controller(
    'CarShopController', function($scope) {
      // This initializes the Angular Model with the values of the JSF
      // bean attributes
      initJSFScope($scope);
      
      $scope.activateAJAXButton = function() {
        if ($scope.settingsBean.updateImmediately)
          return false;
        else
          return true;
      };
      
      $scope.sendFilterToServer = function(newValue, oldValue) {
        if ($scope.settingsBean.updateImmediately) {
          if (newValue != oldValue) {
            try {
              $scope.afSendNGSyncToServer();
            } catch (e) {
              console.log("Ein Fehler ist aufgetreten: " + e);
            }
          }
        }
      };

      $scope.$watch('filterBean.brand', $scope.sendFilterToServer);
      $scope.$watch('filterBean.type', $scope.sendFilterToServer);
      $scope.$watch('filterBean.price', $scope.sendFilterToServer);
      $scope.$watch('filterBean.mileage', $scope.sendFilterToServer);
      $scope.$watch('filterBean.fuel', $scope.sendFilterToServer);
      $scope.$watch('filterBean.color', $scope.sendFilterToServer);
      $scope.$watch('filterBean.yearText', $scope.sendFilterToServer);
    })

Continue reading