Showing posts with label jee 7. Show all posts
Showing posts with label jee 7. Show all posts

Thursday, 1 June 2017

flexibleJDBCRealm

I have recently changed my security realm settings, and I thought I'd document them here.

I'm still using the flexibleJDBCRealm1 as I've documented in previous blogs2,3.

In the Glassfish administration console, under Configurations -> server-config -> Security -> Realms -> myRealm, the settings are now as follows.
NameValueDescription
datasource.jndijdbc/mydbthe data source to my database
jaas.contextflexibleJdbcRealm
password.digestSHA-512I have upgraded from SHA1 to SHA2, which seems more secure
password.encodingHEX:128See note below
sql.groupsselect groupid from mmv_groups where name in (?)using a database view, makes it easier to change table layout without effecting the securityrealm
sql.passwordselect password from mmv_users where name in (?)same as above

Note

The SHA-512 encoding always creates 128 characters as the hash.

However, in the source code of the flexibleJDBCRealm, this hash is converted from a byte[] into a hexadecimal string by means of a call "new BigInteger(1, aData).toString(16);".

This effectively means that if the byte[] starts with one or more "0"s, these are removed in the BigInteger call leaving you with a hash that is less than 128 characters.

This is why I need to use "HEX:128", instead of just "HEX".

MariaDB/MySQL

The values are easily verifiable in the database.

I can just do a
SELECT SHA2(usertable.password, 512) from usertable where user='mrbear';

It should yield the exact same result as the encryption function of the flexibleJDBCRealm.

References

[1] FlexibleJDBCRealm
http://flexiblejdbcrealm.wamblee.org/site/
[2] Security Realms in Glassfish
http://randomthoughtsonjavaprogramming.blogspot.nl/2016/04/security-realms-in-glassfish.html
[3] Glassfish Security Realms
http://randomthoughtsonjavaprogramming.blogspot.nl/2014/10/glassfish-security-realms.html
[4] Installation instructions
http://flexiblejdbcrealm.wamblee.org/site/documentation/snapshot/installation.html

Thursday, 7 January 2016

Vaadin 7

Vaadin1 is an open source framework for developing web applications2 running in your browser. What is interesting is that it uses Java to do it.

It feels like you're programming like Swing in Java, but the results are transferred to your webbrowser using Vaadin. Vaadin is able to do this with the help of the Google Web Toolkit3.

Vaadin can apparently be run on the Google App Engine, if you like.

Vaadin 7 supports the JSR-286 Portlet specification. Several portals are supported. Vaadin also has some deeper integration with Liferay Portal11, in which I am very interested, as it is the one that my website is running on.

I did find a youtube video12 that introduces Vaadin in combination with JEE and NetBeans.

Upgrading to Vaadin 7

One of the problems I encountered, when using Vaadin 74 is that most of the resources available are still referring to Vaadin 6. It is important to notice the differences.

The points in [4] that have been most relevant to me are:
  • com.vaadin.Application class no longer exists. The main entry point to your application is now a com.vaadin.ui.UI, which replaces Application and its main window.
  • Also com.vaadin.terminal.gwt.server.ApplicationServlet has been replaced with com.vaadin.server.VaadinServlet in web.xml and its parameter "application" with "UI" pointing to your UI class, and the application is ready to go. Of course you can use annotations, if you prefer.

Testing

As it is Java, I should have no problem Stubbing the Vaadin framework and junit-testing my code. This to me is a big bonus.

Persistence

Persistence in Vaadin is possible by using the JPAContainer5.

JEE and CDI

I use the Servlet to inject a lot of things I need, and then provide those injected things to my UI. Works flawlessly6.

JEE and JPA together in Vaadin

I found helpful information on how to create a EjbEntityProvider here at [7]. That I can use as a base class for EJBBeans that I can inject in my Servlet and henceforth use in my UI for the JPAContainer.

A full downloadable example is available at [8].

Debugging

I have not had to debug anything, everything just works. But, for those interested, you can find it at [9].

FAQ

I get a "Failed to load the bootstrap javascript: ./VAADIN/vaadinBootstrap.js?v=7.5.5"
See [10]. Extend the @WebServlet annotation withe more than one urlPattern. See the example above.

References

[1] Vaadin
https://vaadin.com/home
[2] Wikipedia - Vaadin
https://en.wikipedia.org/wiki/Vaadin
[3] Google Web Toolkit
http://www.gwtproject.org/
[4] Vaadin Wiki - Mirating from Vaadin 6 to Vaadin 7
https://vaadin.com/wiki/-/wiki/Main/Migrating+from+Vaadin+6+to+Vaadin+7
[5] Book of Vaadin - Chapter 19 - JPAContainer
https://vaadin.com/book
[6] Vaadin Wiki - JEE6 integration with Vaadin 7
https://vaadin.com/wiki/-/wiki/Main/JEE6+integration+with+Vaadin+7
[7] Using JPA Container 2.0 in a JEE6 server
https://vaadin.com/web/matti/blog/-/blogs/using-jpa-container-2-0-in-a-jee6-server
[8] Vaadin Forum - Unable to follow J6EE wiki - NullPointerException
https://vaadin.com/forum/#!/thread/386542/389263?_19_redirect
[9] Book of Vaadin - Chapter 11.3. Debug Mode and Window
https://vaadin.com/book/-/page/advanced.debug.html
[10] Book of Vaadin - 4.9. Deploying an Application
https://vaadin.com/book/-/page/application.environment.html
[11] Liferay
http://www.liferay.com/
[12] YouTube - Java EE 7 with NetBeans and Vaadin
https://www.youtube.com/watch?v=3TompuzySD8

Thursday, 5 November 2015

J-Fall 2015

“Once you stop learning, you start dying.”
- Albert Einstein

I just got back from J-Fall 20151.

Seeing as the location had been changed from Nijkerk to Ede, I was unable to attend the Early Bird sessions, much to my dismay. I did manage to hitch a ride with a colleague of mine, but in the future, I will try and get a train. The connection seems to be quite good and once more there is a shuttle bus riding between the location (Cinemec) and the trainstation.

What with traffic (congestion) and my colleague sleeping late, I did miss the first keynote (The Experimental Enterprise - Keynote ING), only arriving at the destination at around 09:45.

The list of sessions I witnessed:

Pushing the limits of Continuous Delivery - Keynote Quintor

Provided by Rene Boere and Pascal Snippen

A fascinating view on what Quintor uses to provide Continuous Delivery (CD) using Docker, Apache Mesos, Marathon and Consul combined with HAProxy. The use of container ships to emphasise Docker was inspired and probably is starting to be overused by now. The microservices landscape is large and you can no longer see the forest for the trees, test environments are hard to set up, deployments are complex and timeconsuming.

Automation of Continuous Delivery is the answer.

Microservices for Mortals

Provided by Bert Ertman

This lecture could be construed as a big, huge, warning if you wish to use Microservices. It had a metaphore comparing coding practices with Italian food. The old way of coding compares to Spaghetti. Then SOA (Service Oriented Architecture) was introduced and those layered coding practices compare to Lasagna. Now the new Microservices compare more to Ravioli (tight independent containers of code bundled together) with sauce. The main idea behind microservices seems to be the ability to easy adapt to change. There is no hard definition on what microservices are. Apparently, microservices are small enough to just replace them with a completely new implementation, or just run 10 instances of one easily. They do away with a lot of items we are software developers have gotten used to:
  • synchronous programming models
  • ACID
  • code reuse
  • using abstractions
Instead, because of the characteristics of Microservices, you get:
  • asynchronous programming models
  • any constraints need to be taken care of at the application level
  • code duplication, each micro service is independent of the others, so code reuse between microservices doesn't make sense
  • separate data storages (one data storage per microservice)
  • passing data using websockets or binary protocols or messaging (REST is too much overhead, I don't want to even mention XML. It's all fine for a public API though.)
  • prefer conventions over abstractions (see code reuse)
If you have not been doing Devops, you cannot get started using Microservices without getting into a world of hurt.

Code for failure. Microservices are brittle, the distributed asynchronous models make them so. Design for this! Use fail early, use resilience patterns, use redundancy, etc.

10 Awesome Tips for Enterprise Javascript - Oracle

Provided by Geertjan Wielenga

This lecture provided an excellent overview of the current JavaScript landscape. I especially liked the fact that he mentioned that at the end of the lecture the landscape will probably already have changed. The JavaScript ecosystem is in that much flux.

Nowadays we have multiple devices, all with different screensizes requiring responsive design. One common factor in all these devices, is that all of them possess a browser. And the Single Page Application (SPA) is becoming the internet-enabled "application" of choice. Page navigation is irrelevant when it comes to Single Page Applications, yet for most Java-based Web Frameworks, page navigation is still an important part of their programming model.

Also, resist the hype. Apparently most managers make bad architecture decision based on hype. And you, as a developer, shouldn't want that.

For some applications, Javascript actually doesn't make any sense. The example provided was air traffic controllers. But different architectures can play different roles, even in those applications where Javascript doesn't make any sense. for example:
mobile apps
notifications
web apps
reporting to (upper) management
application itself
what users actually need and use in day-to-day work

NetBeans provided really nice point-and-click programming of the new HTML 5 components. The new HTML 5 components look very snazzy. Apparently, every new HTML 5 component is itself composed of sub-html-components, called the Shadow DOM and can therefore be styled appropriately. CSS has been split up into approximately 50 CSS modules. JavaScript can be used to avoid having to hide HTML using CSS, because hiding certain HTML components still makes the browser get the linked resources contained in those HTML components. Especially on mobiles this can make a huge difference.

In the Java world, the acronym WORA (Write Once Run Anywhere) is very well known. In the JavaScript world its WONTA (Write Once, Never Touch Again). The projects are so small, and the evolution of the Javascript ecosystem is so quick, it makes more sense to re-design and re-write everything from scratch when required.

Oracle has defined a Javascript framework, which is basically a bundling of common javascript libraries, into what is called the "Oracle Javascript Extention Toolkit"2.

“Javascript is the assembly language of the web.”

Then there's, if you really do not want to touch JavaScript with a ten-foot pole, the transpilers:
Dukescript
write Java, but also HTML and CSS. Combine those.
GWT/Vaadin
provides a Java backend similar to the Swing toolkit, and translates your code into HTML,CSS and JavaScript for the frontend.
Dart
separate programming language for the web/mobile/desktop.
Typescript
provides static typing to javascript, a sort of superset of JavaScript following ECMA recommendations that is transpiled to JavaScript
Coffeescript
programming language that translates to javascript

The Java renaissance continues - Keynote Oracle

Provided by Sharat Chander

A motivating speech on the fact that Java is still a success primarily because of the community. And a personal appeal to every person there to connect to at least two in the audience during the conference.

Devops - Are you walking or still talking? - Keynote Capgemini

Provided by Remko Reinders

A lecture on Devops, more importantly, what it takes for an organisation to become a success at Devops and what you can do to help your organisation and yourself to become a success as well.

“Most people will talk the talk. Few will walk the walk. Be amongst those few.”
- Steve Maraboli

“Software is eating up the world.”
- Marc Andreessen, Wall Street Journal

Building Asynchronous and Non-Blocking HTTP Applications with Ratpack

Provided by Hubert Klein Ikkink

My first introduction to Ratpack3, which I had never heard of before. It is a small webserver, that can be programmed using Java 8 and Groovy. It uses Netty for the HTTP IO, has a very small footprint, is very fast and is asynchronous. Does not provide JEE, does not follow the Servlet API and can be started by running a Jar file. Spock is used for testing.

If you want a quick webserver to dish out some REST stuff in a distributed environment, this is it. Check his webblog4 for more information.

Java modularity, life after Java 9 - Luminis

Provided by Sander Mak & Paul Bakker

“Good fences make good neighbours.”
- Proverb

An excellent talk about the upcoming Jigsaw in Java 9. It provides a faster startup and a smaller footprint, essential for small devices. It compared what little information there is about Jigsaw to the existing implementation of OSGI. Modules are allowed to talk to other modules only by the service contract each module provides. Modules are defined in a module-info.java file. The segregation is looked after by the VM itself and cannot be circumvented. Layers are used to prevent different versions of the same module interfering with each other. Versioning isn't really built into the new system. There is a linking tool called jlink and module maker tool called jmod. Jdebs can provide your program with which modules it needs. Identification of a module is done using a newly defined namespace specific for modules.

Classpath scanning for annotations is going to be a problem. It is going to have to be service-oriented in the future.

Especially application servers are going to need a major overhaul, as well as several annotation-crosscutting concerns frameworks as REST and JPA implementations.

See http://bit.ly/java9demo for more information.

References

[1] NLJUG - J-Fall 2015
http://www.nljug.org/jfall/2015/
[2] Oracle JavaScript Extention Toolkit
http://oraclejet.org
[3] Ratpack
https://ratpack.io/
[4] Mr Haki's Webblog
http://mrhaki.blogspot.nl/



Monday, 2 November 2015

J-Fall 2015 Incoming!

The NLJUG[1] is once again organizing J-Fall[2]. Edition 2015 obviously.

It takes place in a new location, as the old location apparently has grown too limiting in number of people allowed. It will be held in CineMec, 150 Laan der Verenigde Naties, Ede on Thursday, the 5th of November 2015. No longer on a Wednesday, that's a change!

Once again I am looking forward to it, to see what I can learn. I shall write up a report on what sessions I visited and found interesting.


References

[1] NLJUG - Nederlandse Java Users Group
http://www.nljug.org
[2] J-Fall 2015
http://www.nljug.org/jfall/2015/

Sunday, 9 November 2014

J-Fall 2014

Well, I have once again been privileged enough to attend the J-Fall 2014 on Wednesday, the 5th of November, in Nijkerk, the Netherlands.

I'll provide a short summary of the Breakout Sessions I followed, and the parts that really struck me as interesting. There's more information on the sessions available at [1].

My chosen schedule:

Keynotes

Bert Ertman, after 10 years at the NLJUG, has decided to step back and become a regular attendee of J-Fall. He is the most visible of the people behind J-Fall, as he has opened J-Fall, to the best of my knowledge, every year. Let us hope we shall see more of him and not less.

The Keynotes were not actually that interesting. The Keynote of Oracle was more related to awards for proven Java-ness, than what Oracle has planned for the future. The keynote of Oracle was provided by James Weaver, who was also giving a Session last year regarding JavaFX and guitar playing.

The Keynote of ING was surprisingly similar to last year, regarding the banks new way of working with software releases (Agile, Scrum, three releases every week, automated testing, DevOps, etc.)

The Keynote of Salves was interesting, in that it had a high geek-techy-factor, with drones flying, and brainwaves to control them, with pattern recognition in cameras. But the complexity of the setup, and the conference location and The Dreaded Demo Effect got to 'em, which is a shame.

I found the best Keynote to be the one provided by Quintor, a consultancy business started in 2005, regarding a simulated Cluster with Hadoop they set up during one of their "Summer Camps" to brute-force a Shortest Path Algorithm. They needed some penguins to find an igloo between ice blocks and rocks. They created "Willem", a server that was running 20 or so virtual environments, chained in a Hadoop cluster with Apache HBase as work memory and Akka Reactive Streams.

The Sessions

Event-sourced architectures with Akka

A great number of projects are always based around the idea of Shared Mutable State. This shared mutable state makes things very hard to scale, so it has traditionally been pushed to the database as far as possible. Stateless code always scales better, because it can be easily run parallel.

It seems to me that event-sourcing is basically based on the database transactionlog that has been in Databases for the past hundreds of years.

The idea is that we store the events that happened, instead of storing only the changes of data. In the latter case we lose a lot of history. In order to keep the side effects out of the way when replaying the event log, these are not re-done.

A simple example is, instead of storing Price and Orders, we store events like PriceChanged or OrderCancelled.

Of course, this presents problems as you have to rerun the event log in order to find out the current situation of the system. This is solved by creating snapshots.

Another problem is the fact that Searching for stuff becomes harder. So it makes sense to have basically two different modules, one module is responsible for changes (and stores events and the likes) and one module is responsible for querying and searching (and searches, for example, over Snapshots).

The abbreviation concerning this is called CQRS, Command Query Responsibility Segregation2. Here the command model is the eventstore (the "journal") and the query model can have several data stores, each containing for example snapshots.

It is possible to have the module that stores events present hooks to the searchmodule to keep the segregated models synchronised.

Some software that is used for the event model and storage of events are:
  • Cassandra
  • Kafka
  • DynamoDB
  • MongoDB
  • HBase
  • HBase
  • MapDB
  • JDBC
We can use Java Serialization, the default, or specific implementations of Java Serialization for example Protobuf, Kryo, Avro.

Akka can be used for all this, it provides a new experimental persistence module called appropriately Akka Persistence, that uses event sourcing.

Code can be found on github at https://github.com/sandermak/akka-eventsourcing. The url provided by Sander was http://bit.ly/akka-es, convenient for if the source moves.

One of the advantages, are that events show the business processes a lot better than normal persisted objects do. With events it is much more clear what is happening.

Conclusion is that event sourcing is very applicable to Domain Driven Design.

A word on versioning, a change in event-structure is going to cause a problem for the history (which uses the old event-structure). There are several solutions for this:
  • don't change your event structure (which, likely isn't possible)
  • use both old and new event-structure at the same time (which, introduces legacy code that needs to be maintained)
  • change ALL your events, also the historical ones (which, from a purity standpoint is debatable)
  • create a snapshot of the historical (old) events, and continue using new events henceforth (losing a bit of history)

I rated this as the best Session of the day!

Reactive programming with Java 8 and Java EE 7

Most of our programming is run sequentially, which, with the current advent of multiple cores, becomes inefficient (they say).

In Java 7 "Futures" were introduced to take care of doing things in parallel using ThreadPools.

A Future is a placeholder for a value that hasn't been set yet, but will (hopefully) be set in the future.

The Java API for Futures is very extensive with a lot of different classes containing a lot of different methods. In the future (my, was that a pun?) there might well come to the front a framework that abstracts away a lot of the nitty-gritty of this highly detailed API. Where the other sessions were light on the amount of code, this one more than made up for them.

Some codepoints:
  • ForkJoinPool.commonPool() => suited to the number of cores the JVM is running on.
  • Callable -> interface, provides a task to perform.
  • ManagedExecutorService -> for externally configurated threadpools for example in an application server like Glassfish. It is a part of JEE 7.
  • CompletableFuture -> takes care of Promise Pipelining. These may trigger actions.
The example provided was regarding Customer data, Contract data of that customer, and Communication data of that customer.

Modelling the flow (probably in a flow model) helps a lot, as you lose a lot of visibility on what the code is actually doing.

You tend to define/plan everything up front, with Futures, and then you start the ball rolling, so to speak, with the last call in the chain.

JAXRS 2.0 has the possibility to perform REST services Asynchronously. This can be done, using:
public void retrieve(@Suspended AsyncResponse response, ...
{
    response.resume...
}

HTTP connections are released during requests, this will lead to much better scalability. (HTTP threads can be re-pooled)

His source is on github at martijnblankestijn/reactive-rest-demo.
One diagram that basically says it all, where green is retrieval of customer information, and red and purple are contract data and communication data respectively of said customer:

Modularity and Domain Driven Design : a killer combination?

The idea of this session was to be serious about the standard software design pattern Separation of Concerns, where you have Loose Coupling and High Cohesion.

The reason why, is that the Cost of A Change should be predictable, and should not result in slowly escalating costs, regarding lost/unattainable deadlines or high maintenance.

The way to do this is with Functional Modularisation, because a functional change should only impact that functional module.

There should be few hard connections between domains, for example no Foreign Keys or the like.
There should be no query between modules, which is a problem when you wish to do some serious Search Queries. A query between modules and across several modules, causes these modules to be tightly coupled.

So, in other words, cross module searches should be postponed as long as possible.

When this isn't possible, you could use CQRS, Command Query Responsibility Segregation.

Elasticsearch can be used to do the searching.

All the modules can be queried individually by the SearchModule, and the SearchModule uses elasticsearch.

Hand-on-Labs: Hands-on with Java 8

This was fairly interesting. They decided on providing a lab on several features in Java 8: the Lambdas (of course), and the new DateTime API.

I've managed to nick their Lab and plan on practicing more of the assignments at home (there wasn't enough time for me at the conference, there were quite many of them).

Microservices: the how and why?

Unfortunately, this was a bit of a miss. I am stuck with no clear idea of what Microservices are exactly, but it seems to follow quite closely in the footsteps of the Session on Modularity.

Here are some book titles mentioned:
  • Domain Driven Design4 - Erik Evens
  • Release It!5 - Michael T. Nygard
  • Antifragile6 - Nassim Nicholas Taleb

Characteristics of Micro services:
  • small (1000 lines of code)
  • do one thing, and do it well (Unix philosophy)
  • independent
  • language agnostic communication
  • highly decoupled

Conway's Law3: organizations which design systems ... are constrained to produce designs which are copies of the communication structures of these organizations.

Basically what this means is that, for example, if you have three teams, one for the UI, one for the Middleware, and one for the database, you end up with a software product that uses a UI, a Middleware and a Database. If the entire team works on ONE microservice, you get the absolute best product. It also means you cannot have a standard team. It is SOA (Service Oriented Architecture) done right.

Missed Sessions

I was planning on visiting Hot migration of JSF to cool SPA with smart hacks, but somehow that fell through.

Unfortunately, at the end of all that it was 17:00 hours, and I was Conference-tired, so I decided to skip Using Docker to Develop, Test and Run Maven projects.

Conclusion

J-Fall always provides an excellent glimpse in what the Software Community (at that current time) feels is most important in sharing with their colleagues.

The main conclusion that I can take away from this J-Fall is that somehow a number of the Sessions was regarding a Separation of Concerns in one way or another (either by an event log, or modules, or micro services, or you-name-it). I heard the term CQRS more than once. Perhaps its importance is felt more and more now that the entire world is getting wired and complexity and unlikely combinations of projects is growing at a rapid rate. (Internet-of-Things anyone?)

References

[1] NLJUG - J-Fall 2014
http://www.nljug.org/jfall/2014/
[2] Martin Fowler - CQRS
http://martinfowler.com/bliki/CQRS.html
[3] Wikipedia - Conway's Law
http://en.wikipedia.org/wiki/Conway%27s_law
[4] Domain Driven Design
Erik Evens
[5] Release It!
Michael T. Nygard
[6] Antifragile
Nassim Nicholas Taleb
ElasticSearch
http://www.elasticsearch.org/

Sunday, 19 October 2014

Glassfish Security Realms

The JDBCRealm

In the Glassfish Administration Console, go to Configurations -> server-config -> Security -> Realms -> and select "New".

We're going to choose com.sun.enterprise.security.ee.auth.realm.jdbc.JDBCRealm.

The jaas.context name of the new realm is "jdbcRealm".

A jdbcRealm needs both a user table and a group table. The group table should store both userids as well as groupids. In other words,
  • the group table doesn't only contain groups, and
  • has a composite primary key, consisting of userid and groupid.

Database Schema

The user table is called "mm_admin" in my case, and the groups table is called "mm_admin_mm_groups".

I have created the "mm_groups" table to store extra information for groups, but that table is ignored by the jdbcRealm.

Some serious disadvantages of the jdbcRealm are:
  • groups are cached, which means if a user changes groups, the Glassfish Server needs to be rebooted.
  • flexibility is about zero, for instance if I have an expiration date attached to my usertable, I'm out of luck.
All this causes me to look elsewhere, namely towards the flexibleJDBCRealm5

The flexibleJDBCRealm

The great advantage of the flexibleJDBCRealm is that you can add SQL queries that are run to retrieve passwords and groups.

Instructions

Well, according to instructions found here6, you have to:
  1. download the flexiblejdbcrealm-deploy-1.2-all.jar
  2. put it into glassfish/domains/domain1/lib directory
  3. change glassfish/domains/domain1/config/login.conf to add
    flexibleJdbcRealm {
    org.wamblee.glassfish.auth.FlexibleJdbcLoginModule required;
    };
  4. reboot the glassfish
  5. In the Glassfish Administration Console, go to Configurations -> server-config -> Security -> Realms -> and select "New"
  6. enter the class name org.wamblee.glassfish.auth.FlexibleJdbcRealm
  7. set the properties, for example like in the image above.

Properties

The properties that can be entered could use a little more explaining compared to what is available at [6].
password.digest
uses MessageDigest(String algorithm). Possible values are "PLAIN", "MD2", "MD5", "SHA-1", "SHA-256", "SHA-384" and SHA-512.
password.encoding
the encoding, I find HEX to be the most useful. Possibile values are "TEXT", "HEX" and "BASE64". A variation of "HEX" is "HEX:<digits>", for example "HEX:40". This padds the beginning of the encoding with zeros to reach the length required. For example MySQL itself always creates passwords using the SHA() function to 40 hex digits also padding the beginning with zeros.
sql.groups
select groupid from mm_admin_mm_groups where name in (?)
sql.password
select passwd from mm_admin where name in (?) and validuntil > now()
jaas.context
flexibleJdbcRealm
datasource.jndi
of course, the connection string to the database
NOTE: he's complaining about setting properties in the realm with a = in them. So I had to go back to an "in (?)" construction for the SQL queries.

Logging

In glassfish/domains/domain1/config/logging.properties, add: org.wamblee.level=FINEST.

Application Configuration

My web.xml would look like thusly:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" 
    xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
             http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">

    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <security-constraint>
        <display-name>Administration</display-name>
        <web-resource-collection>
            <web-resource-name>Administration REST Resources</web-resource-name>
            <description/>
            <url-pattern>/resources/administration/*</url-pattern>
            <url-pattern>/administration/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <description/>
            <role-name>deputy</role-name>
        </auth-constraint>
    </security-constraint>
    <login-config>
        <auth-method>BASIC</auth-method>
        <realm-name>deputyRealm</realm-name>
    </login-config>
    <security-role>
        <description/>
        <role-name>deputy</role-name>
    </security-role>
</web-app>
My glassfish-web.xml looks like:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE glassfish-web-app 
    PUBLIC 
    "-//GlassFish.org//DTD GlassFish Application Server 3.1 Servlet 3.0//EN" 
    "http://glassfish.org/dtds/glassfish-web-app_3_0-1.dtd">

<glassfish-web-app error-url="">
  <security-role-mapping>
    <role-name>deputy</role-name>
    <group-name>deputy</group-name>
  </security-role-mapping>
  <class-loader delegate="true"/>
  <jsp-config>
    <property name="keepgenerated" value="true">
      <description>Keep a copy of the generated servlet class' java code.</description>
    </property>
  </jsp-config>
</glassfish-web-app>
In this file you can create a mapping between security roles and groups.

Declarative Security

An example of declarative security using Annotations:
@DeclareRoles("deputy")
@RolesAllowed("deputy")
@Stateless
@Path("/administration/worldattributes")
public class WorldattributesBean extends AbstractFacade<Worldattribute>
{
This means the role definition in the web.xml can be removed.

In the example above, the security role is applied to the entire Bean, so for each method in the bean, instead of on each method that requires the role.

Programmatic Security

Unfortunately, some fine-grained security can only be done with programmatic means, for example determining if a person who has authenticated themselves owns a certain object that needs mutated upon. In my example, this info in a Rest service can be obtained through a SecurityContext:
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.Context;
...
@POST
@Override
@Consumes(
{
     "application/xml", "application/json"
})
public void create(Worldattribute entity, @Context SecurityContext sc)
{
  itsLog.info("create");
  final String name = sc.getUserPrincipal().getName();

FAQ

I get WEB9102: Web Login Failed: com.sun.enterprise.security.auth.login.common.LoginException: Login failed: No LoginModules configured for flexibleJdbcRealm?
You forgot to add the entry to the login.conf as specified above.

References

[1] Oracle - Security in the Java EE Platform
http://docs.oracle.com/javaee/7/tutorial/doc/security-intro.htm
[2] The Java EE 7 Tutorial
Release 7 for Java EE Platform
[3] Oracle - Using the JDBC Realm for User Authentication
http://docs.oracle.com/javaee/6/tutorial/doc/glxgo.html
[4] Understanding Web Security
http://java.dzone.com/articles/understanding-web-security
[5] FlexibleJDBCRealm
http://flexiblejdbcrealm.wamblee.org/site/
[6] Installation instructions
http://flexiblejdbcrealm.wamblee.org/site/documentation/snapshot/installation.html

Sunday, 13 July 2014

Migrating between JEE versions

I had an issue where I wanted to port my current JEE 6 (Web profile) application (YPPO) to JEE 7 (Full profile).

This concerns a Netbeans project (built using Ant)

I thought I'd just write down which files needed changing.
nbproject/project.properties
-j2ee.platform=1.6-web
+j2ee.platform=1.7
persistence.xml
-<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
+<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
beans.xml
-<beans xmlns="http://java.sun.com/xml/ns/javaee"
+<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">

+ xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd" bean-discovery-mode="annotated">
web.xml
-<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
+<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"></dd>

References

Github - changed from JEE 6 Web (Lite) to JEE 7 (Full).
https://github.com/maartenl/YourPersonalPhotographOrganiser/commit/82d0c00812ec626e21c7b48a6a5523fb0311218e
Github - changed from JEE 6 Web (Lite) to JEE 7 (Full) Part II.
https://github.com/maartenl/YourPersonalPhotographOrganiser/commit/a092896dc00805f640a1dd305e248c39aa3cf70b
Github - bean-discovery-mode required attribute in beans.xml
https://github.com/maartenl/YourPersonalPhotographOrganiser/commit/b979c896711e7ebf30f90534aaffe9ddbe855681

Tuesday, 8 April 2014

Batch Jobs in JEE 7

This little blogpost is to describe my current design for Batch processing in my YPPO9 project. The image comes straight from Spring Batch.

As no doubt you are aware, Batch Processing in Java has been standardized in JEE 72. It is based on already existing Batch implementations, for example, Spring Batch7.

The reason I am interested in it, is that I wanted to initially solve my problem using a JMS queue, but after getting the warning that I'm creating too many messages in one transaction, I decided to give batch processing a try instead. Besides, it felt a little (oh, all right, a lot!) like I was abusing the JMS for Batch processing in the first place.

Definitions:
Job
encapsulates the entire batch process. So, in our case, we have two jobs to define for YPPO. Job "Import new Photographs" and job "Verify existing Photographs".
Step
a domain object that encapsulates an independent, sequential phase of the job. There are two kinds, Chunk-style and Batchlet-style. We can suffice here with the standard, Chunk-style. We only need one step for each job. We are keeping it simple as that is all that is needed.
  • chunk-style step "Import Photograph" for job "Import new Photographs"
  • chunk style step "Verify Photograph" for job "Verify existing Photographs"
JobOperator
operates on jobs, starts them, stops them, retrieves required steps etc.
JobRepository
contains history, jobs running, job that have run, etc.
I shall be focussing on the "Verify existing Photographs" job for the remainder of the blogpost.

Batch Artifacts

The Batch Artifacts are injected as Beans into the job system using CDI. Thusly the artifacts used are Beans identified with @Named annotations.

In the package gallery.jobs.verify above, the classes Listener, Reader, Processor, Writer are Beans annotated with @Named with names verifyPhotographListener, verifyPhotographReader, verifyPhotographProcessor and verifyPhotographWriter respectively. These names will be used later in defining the job.

In my example, I also wished that if an actual error occurred, the item to be processed would be skipped and a log error written to the database, so that it can be checked and corrected afterwards by the user. So, errors on individual items are no excuse for stopping the job.

In the new JEE 7, there's a setting in the empty beans.xml file called "bean-discovery-mode", which is required. If set to "all", it checks all classes for CDI. If set to "annotated", it checks only those classes that have annotations. I've set it to "annotated". However, I've tried setting the @Named annotation on the classes I required, but my classes weren't injected in the Batch jobs. An additional annotation for the scope (@ApplicationScope) is required, before the classes are picked up.

Below is a sequence diagram of a job.

Job Specification Language

JSL or Job Specification Language is the xml format used to define jobs. It is grammatically defined in [5].

In the picture on the left, you can see where in my project structure in NetBeans the Job definition files are located. In this location, they are automatically picked up by the Application Server.

For YPPO you can find the files AddPhotographs.xml and VerifyPhotographs.xml as visible below on my git repository YourPersonalPhotographOrganiser.

A job can currently not be restarted. My jobs are not configured for restarting (restartable="false" as you can see). I'll devote a future blog to it once I figure out how to do that.

In my example, I have a Batch job chunk-size of 4. (item-count="4")

Listeners should be defined in the step, prior to defining other things, like for example a chunk.

Starting a Batch Job

public void verifyPhotographs(Location location)
{
    JobOperator operator = BatchRuntime.getJobOperator();
    Properties jobParameters = new Properties();
    jobParameters.setProperty("location", location.getId() + "");
    operator.start("VerifyPhotographs", jobParameters); // maps to VerifyPhotographs.xml
}

Retrieving Details About Batch Jobs

Notes

It seems NetBeans has no Wizards nor GUIs and Widgets to automatically generate Batch Jobs scaffolding, but it is on the roadmap.

There are lots of tutorials on Batch Jobs in JEE 7, however, a lot of them were written in the first half of 2013 and they have in the mean time changed the definition of Batch Artifacts from Annotations to a simple set of Interfaces your Batch Artifacts need to implement.1 3

[4] gives a good general view of Batch Applications in Java 7. The JEE 7 Tutorial8 is also very good.

References

[1] Batch Applications in Java EE
https://blogs.oracle.com/arungupta/entry/batch_applications_in_java_ee
[2] JSR 352 - Java Batch
https://java.net/projects/jbatch
[3] Batch Applications for Java Processing - SlideShare
http://www.slideshare.net/arungupta1/jbatch-21153200
[4] Java EE 7 Introduction to Batch JSR 352
http://jaxenter.com/java-ee-7-introduction-to-batch-jsr-352-47400.html
[5] Batch Applications for the Java Platform - Version 1.0 Final Release
JSR-352-1.0-Final-Release.pdf
[6] JavaDoc - JEE 7
http://docs.oracle.com/javaee/7/api/
[7] Spring Batch in Action
Arnaud Cogluègnes, Thierry Templier, Gary Gregory, Olivier Bazoud
[8] JEE 7 Tutorial - Batch Processing
http://docs.oracle.com/javaee/7/tutorial/doc/batch-processing.htm
[9] GitHub - YourPersonalPhotographOrganiser (YPPO)
https://github.com/maartenl/YourPersonalPhotographOrganiser

Saturday, 9 November 2013

JFall 2013

I went to JFall 2013, the annual Dutch Java Conference, organised by the NLJUG on Wednesday, the 6th of November 2013 in Nijkerk, the Netherlands.

I found the Keynotes to be singularly exciting, a lot better compared to last year.

Main change was the main sponsor, ING, who have some interesting requirements for their software and who have undergone a change
from the traditional way of developing software to the DevOps way.

My chosen schedule:
  • Shootout! Template engines on the JVM (Jeroen Reijn)
  • Retro Gaming with Lambdas (Stephen Chin)
  • Code-driven introduction to the Java EE 7 Platform (Arun Gupta)
  • Hands-On Labs: Gradle (Mr. Haki)
  • Scratching the Surface with JavaFX (James Weaver)
  • ING Beleggen: how top quality software and state-of-the-art technology leads to continuous delivery (Jos Klompe)

I managed, according to my colleague, to miss out on the talk by Allard Buijze called 'Reactive applications: ready for the future'. But, if all is well, I should be able to view it at Parleys.com.

I hear the talk 'On the integrity of data in Java Applications' (Lucas Jellema) was also really good, that I didn't visit. There's only 24 hours in a day.

Shootout! Template engines on the JVM


The presentation was provided by Jeroen Reijn of Hippo (the Java CMS). He mentioned a few old Template engines, JSP, Freemarker and Velocity. Hippo seems to make use of Freemarker, at least at the moment.

Then he went into some (relatively) new Template engines with included benchmarks:
  • Thymeleaf (web+spring mvc+large memory footprint, a little slow)

    Has Natural Templating, which means that additional namespaces in the XHTML will cause the xhtml pages to render on a normal browser. (It just ignores the additional namespaces).

    Benchmark: 25,000 requests took 30 sec.
    For whom: html designers
  • Mustache (not just web+spring mvc addon)

    Logic-less, so they claim, has no control statements (if, for, while, else, etc). Called Mustache because Expressions are written between double curly brackets ({{), and those look like a mustache.

    Good IDE support.

    Benchmark: 25,000 requests took 12/13 sec.
    For whom: html designers
  • Jade (web)

    A Node.js based template engine. Indentation is part of the syntax, which means there's no need for closing tags. It's minimal, easy to read and small.

    Good IDE support.

    Benchmark: 25,000 requests took 20 sec.
    For whom: java developers
  • Scalate (Scala Template Engine, very slow due to the layout mechanism)

    Scala based, integrates well into Spring, Play, Lift, etc. Supports multiple template languages. The one language Jeroen went into deeper detail about is called SCAML.

    Benchmark: 25,000 requests took 100 sec.
    For whom: Scala enthousiasts

For the java developers that feel the need, the need for speed, stick to JSP and Freemarker.

Retro Gaming with Lambdas


Stephen Chen provided both an overview of lambdas in Java 8 and a practical example in the form of a JavaFX game called 'MaryHadALittleLambda'.

The latter part of which is available on github at https://github.com/steveonjava/MaryHadALittleLambda.

He talked about
  • lambdas
  • extension methods
  • the hamburger operator
  • method references
  • @FunctionalInterface

Code-driven introduction to the Java EE 7 Platform


It was given by the Arun Gupta. I was quite surprised to learn that he's been an employee of JBoss for the past three weeks.

I'm also still not used to the fact that their JBoss Application Server is now called ... Wildfly.

He did a quick code-driven introduction in the following topics:
  • WebSocket (URLs start with 'ws://')
  • JAX-RS (JS339)
  • JSON Client Api
  • Batch
  • JMS

JEE 7 samples are available at his github account at https://github.com/arun-gupta/javaee7-samples.

Hands-On Labs: Gradle


Gradle is sort of like Maven only with a Groovy DSL instead of XML and is more flexible than Maven. Where Maven required selfmade Plugins to get it to do the things you want, Gradle can just be adapted.

From what I hear it is quite easy, even automatic, to convert Maven build scripts into Gradle build scripts.

It seems that NetBeans has builtin support for Gradle, no plugins required. I gotta check that out!

Gradle helps in building a Project. The project consists of tasks. A task consists of actions.

The Lab was one of the easiest and simplest to do. I could have just as easily done that at home.

Scratching the Surface with JavaFX


I enjoyed the presentation of Jim (James) Weaver immensely. It started off with a Dutch Music Guessing Game to break the ice, presumably. After that he showed us the touch events interface in JavaFX. Then proceeded to dazzle us with simple 3D in JavaFX3D.

We should check out iotcommunity.net, and I should mention in JIRA that I want to have shadows from lightnodes.

JavaFX Ensemble application is very nice, as a starting point on what JavaFX makes possible.

Currently, there is some 'unofficial' versions of JavaFX that run on Android and IOS. Expect more news on this.

JavaFX can be lay outed by means of CSS. CSS is a good way to make it more 'finger friendly'. We're talking about touch screens after all.

The 3d parts showed things like shapes (ball, cube, triangle mesh, textures, bump maps), lights (ambient and directional), cameras.

One of the more awesome parts of the presentation was the fact that he wanted to play the guitar, when he was away from home, but without dragging his guitar along. So he programmed touch sensitive guitar strings in 3d on his Microsoft Touchpad. He could play quite well and it was very impressive to see a really good demo of all the touch events he had been talking about.

ING Beleggen: how top quality software and state-of-the-art technology leads to continuous delivery


Jos Klompe and his colleague provided a riveting and energizing talk about what they do for ING, to be specific the portal that customers and employees use to trade stocks and other, more complex, financial instruments.

The most interesting in the story is the complete turnaround from a Bank with a traditional waterfall model over to a dynamic Bank using Agile and Scrum and DevOps teams that is putting IT at the core of its business.

Tuesday, 25 June 2013

Java EE 7 Launch

I have been unable to write about the Webcasts I have followed on the 12th of June regarding the release of Java EE 7. (See Java EE 7 Launch Webcast: Jun 12th)

So here's my attempt.

I'm going to put some points down as a reminder for me on what are the main points of JEE 7 indicated in the Webcast.
  • HTML 5
    • WebSockets
    • Servlet 3.1 NIO
    • JSF 2.2
    • JSON
      • Streaming API - searching and retrieving data from large JSON documents
      • Object Model API - creation and updating of JSON documents
    • REST
  • Developer Productivity
    • More Annotated POJOs
    • Less boilerplate code
    • Cohesive integrated platform
  • Meeting Enterprise Demands
    • Batch Processing
      • Item oriented : chunk (normally used)
      • Task oriented : batchlet
    • Concurrency
    • JMS

References

Your First Cup: An Introduction to the Java EE Platform
Release 7 for Java Platform, Enterprise Edition
Introduction to Java Platform, Enterprise Edition 7
An Oracle White Paper, June 2013

Thursday, 23 May 2013

Java EE 7 Launch Webcast: Jun 12th


Wednesday, June 12 and Thursday, June 13 (depending on time zone)

Event One

Event Two

Content

9:00 a.m. PT

9:00 p.m. PT

Keynote Address

10:30 a.m. PT

10:30 pm PT

On-Demand Breakouts Available

10:30 a.m. PT

10:30 pm PT

Dynamic, Scalable HTML 5 – Chat Session

11:30 a.m. PT

11:30 p.m. PT

Meeting Enterprise Demands – Chat Session

12:30 p.m. PT

12:30 a.m. PT

Increasing Productivity – Chat Session

References

Java EE 7 Platform Completes the JCP Final Approval Ballot
https://blogs.oracle.com/theaquarium/entry/java_ee_7_platform_completes
Java EE 7 Launch Webcast: Jun 12th, Register Now
https://blogs.oracle.com/arungupta/entry/java_ee_7_launch_webcast
Time Zone Converter – Time Difference Calculator
http://www.timeanddate.com/worldclock/converter.html
System Test
http://vshow.on24.com/view/vts/tys/tys.htm?cookie=true