Archive

Archive for the ‘programming’ Category

GlassFish 4 Promoted Build, Gradle and Embedded Application Server

January 31st, 2013 Comments off

Very recently, perhaps towards end of last year, the GlassFish open source team released GlassFish 4.0 beta 72 as a promoted build. Arun Gupta posted an article on the Maven coordinates for the GlassFish 4 .0 beta 72 on his blog. This release was significant because the team published the artifacts into a maven repository.

This year, 2013, I am the author of a up and coming Java EE 7 User Guide and so it is important that I investigate the latest GlassFish, especially since it is the reference implementation of the specification. I want to actually research and investigate how far the latest Java Servlets 3.1, Web Sockets and JAX-RS specifications behave in the server.

Here is a Gradle build script that I wrote last night to execute an GlassFish Embedded application:

apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'eclipse'
apply plugin: 'idea'

group = 'com.javaeehandbook.book1'
archivesBaseName = 'ch06-servlets-basic'
version = '1.0'

repositories {
 mavenCentral()
 maven {
   url 'https://maven.java.net/content/groups/promoted'
 }
 maven {
   url 'http://repository.jboss.org/nexus/content/groups/public'
 }
}

dependencies {
 compile 'org.glassfish.main.extras:glassfish-embedded-all:4.0-b72'
 compile 'javax:javaee-api:7.0-b72'
 testCompile 'junit:junit:4.10'
}

// Override Gradle defaults - a force an exploded JAR view
sourceSets {
 main {
   output.resourcesDir = 'build/classes/main'
   output.classesDir = 'build/classes/main'
 }
 test {
   output.resourcesDir = 'build/classes/test'
   output.classesDir = 'build/classes/test'
 }
}

task(run, dependsOn: 'classes', type: JavaExec) {
 description = 'Runs the main application'
 main = 'je7hb.common.webcontainer.embedded.glassfish.EmbeddedRunner'
 classpath = sourceSets.main.runtimeClasspath
}

The key to the build script is the order of the dependencies. I found that the glassfish-embedded-all had to be first dependency on the list, otherwise there would be ValidationException from the Hibernate Validator (bean validator) jar not being found. The exception message was "javax.validation.ValidationException: Unable to load Bean Validation provider".

The Gradle build also references the GlassFish Java repositories, which is the second key point.

Here is the EmbeddedRunner, the Java application code:

package je7hb.common.webcontainer.embedded.glassfish;

import org.glassfish.embeddable.*;
import java.io.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;

public class EmbeddedRunner {

 private int port;
 private AtomicBoolean initialized = new AtomicBoolean();
 private GlassFish glassfish;

 public EmbeddedRunner(int port) {
   this.port = port;
 }

 public EmbeddedRunner init() throws Exception{
   if ( initialized.get() ) {
     throw new RuntimeException("runner was already initialized");
   }
   BootstrapProperties bootstrapProperties = new BootstrapProperties();
   GlassFishRuntime glassfishRuntime = GlassFishRuntime.bootstrap(bootstrapProperties);

   GlassFishProperties glassfishProperties = new GlassFishProperties();
   glassfishProperties.setPort("http-listener", port);
   String [] paths = System.getProperty("java.class.path").split(File.pathSeparator);
   for (int j=0; j<paths.length; ++j) {
     System.out.printf("classpath[%d] = %s\n", j, paths[j]);
   }
   glassfish = glassfishRuntime.newGlassFish(glassfishProperties);
   initialized.set(true);
   return this;
 }

  private void check() {
    if ( !initialized.get() ) {
      throw new RuntimeException("runner was not initialised");
    }
  }

  public EmbeddedRunner start() throws Exception{
    check();
    glassfish.start();
    return this;
  }

  public EmbeddedRunner stop() throws Exception{
    check();
    glassfish.stop();
    return this;
  }

  public static void main(String args[]) throws Exception {
    EmbeddedRunner runner = new EmbeddedRunner(8080).init().start();
    Thread.sleep(1000);
    runner.stop();
  }
}

The class executes the embedded GlassFish as the beginnings of a containerless build, which is a term that James Ward and others have coined. This class starts GlassFish, waits one second, and then shuts it down again. The code works with Gradle, by invoking at the command line gradle run or through an IDE. I used the command gradle idea to generate IDEA project files.

Here is sample output from IntelliJ IDEA 12:

/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/bin/java -Didea.launcher.port=7537 "-Didea.launcher.bin.path=/Applications/IntelliJ IDEA 11.app/bin" -Dfile.encoding=UTF-8 -classpath "/Users/Developer/Documents/IdeaProjects/javaee7-handbook/ch06/servlets-basic/out/production/servlets-basic:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/lib/ant-javafx.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/lib/dt.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/lib/javafx-doclet.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/lib/javafx-mx.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/lib/jconsole.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/lib/sa-jdi.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/lib/tools.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/deploy.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/htmlconverter.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/javaws.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/jce.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/jfr.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/jfxrt.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/JObjC.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/jsse.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/management-agent.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/plugin.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/resources.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/rt.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/ext/dnsns.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/ext/localedata.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/ext/sunec.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/ext/sunjce_provider.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/ext/sunpkcs11.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/ext/zipfs.jar:/Users/Developer/.gradle/caches/artifacts-15/filestore/org.glassfish.main.extras/glassfish-embedded-all/4.0-b72/jar/942b982d5c005806a08843d2a1f411f278c04077/glassfish-embedded-all-4.0-b72.jar:/Users/Developer/.gradle/caches/artifacts-15/filestore/javax/javaee-api/7.0-b72/jar/56d50eaa8d21c2f70394f607efc1aa27c360141d/javaee-api-7.0-b72.jar:/Users/Developer/.gradle/caches/artifacts-15/filestore/javax.activation/activation/1.1/jar/e6cb541461c2834bdea3eb920f1884d1eb508b50/activation-1.1.jar:/Users/Developer/.gradle/caches/artifacts-15/filestore/com.sun.mail/javax.mail/1.4.6-rc1/jar/5c5de8592e570afb595a8be727b484d438b49d69/javax.mail-1.4.6-rc1.jar:/Applications/IntelliJ IDEA 11.app/lib/idea_rt.jar" com.intellij.rt.execution.application.AppMain je7hb.common.webcontainer.embedded.glassfish.EmbeddedRunner
classpath[0] = /Users/Developer/Documents/IdeaProjects/javaee7-handbook/ch06/servlets-basic/out/production/servlets-basic
classpath[1] = /Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/lib/ant-javafx.jar
classpath[26] = /Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/ext/zipfs.jar
classpath[27] = /Users/Developer/.gradle/caches/artifacts-15/filestore/org.glassfish.main.extras/glassfish-embedded-all/4.0-b72/jar/942b982d5c005806a08843d2a1f411f278c04077/glassfish-embedded-all-4.0-b72.jar
classpath[28] = /Users/Developer/.gradle/caches/artifacts-15/filestore/javax/javaee-api/7.0-b72/jar/56d50eaa8d21c2f70394f607efc1aa27c360141d/javaee-api-7.0-b72.jar
classpath[29] = /Users/Developer/.gradle/caches/artifacts-15/filestore/javax.activation/activation/1.1/jar/e6cb541461c2834bdea3eb920f1884d1eb508b50/activation-1.1.jar
classpath[30] = /Users/Developer/.gradle/caches/artifacts-15/filestore/com.sun.mail/javax.mail/1.4.6-rc1/jar/5c5de8592e570afb595a8be727b484d438b49d69/javax.mail-1.4.6-rc1.jar
classpath[31] = /Applications/IntelliJ IDEA 11.app/lib/idea_rt.jar
Found populator: org.glassfish.kernel.embedded.EmbeddedDomainXml
Jan 31, 2013 10:05:12 AM org.glassfish.security.services.impl.authorization.AuthorizationServiceImpl initialize
INFO: Authorization Service has successfully initialized.
Jan 31, 2013 10:05:12 AM org.hibernate.validator.internal.util.Version <clinit>
INFO: HV000001: Hibernate Validator 5.0.0.Alpha1
Jan 31, 2013 10:05:13 AM com.sun.enterprise.config.modularity.StartupConfigBeanOverrider postConstruct
INFO: Starting the config overriding procedure
Jan 31, 2013 10:05:13 AM com.sun.enterprise.config.modularity.StartupConfigBeanOverrider postConstruct
INFO: Finished the config overriding procedure
Jan 31, 2013 10:05:13 AM com.sun.enterprise.v3.services.impl.GrizzlyProxy start
INFO: Grizzly Framework 2.3 started in: 18ms - bound to [/0.0.0.0:8,080]
Jan 31, 2013 10:05:13 AM com.sun.enterprise.v3.services.impl.GrizzlyProxy start
INFO: Grizzly Framework 2.3 started in: 3ms - bound to [/0.0.0.0:8,081]
Jan 31, 2013 10:05:13 AM com.sun.enterprise.v3.admin.adapter.AdminEndpointDecider setGuiContextRoot
INFO: Admin Console Adapter: context root: /admin
Jan 31, 2013 10:05:13 AM com.sun.enterprise.v3.admin.adapter.AdminEndpointDecider setGuiContextRoot
INFO: Admin Console Adapter: context root: /admin
Jan 31, 2013 10:05:13 AM com.sun.enterprise.v3.admin.adapter.AdminEndpointDecider setGuiContextRoot
INFO: Admin Console Adapter: context root: /admin
Jan 31, 2013 10:05:13 AM com.sun.enterprise.v3.server.AppServerStartup$StartupActivator awaitCompletion
INFO: Undefined Product Name - define product and version info in config/branding 0.0.0 (0) startup time : Embedded (1,204ms), startup services(856ms), total(2,060ms)
Jan 31, 2013 10:05:13 AM org.glassfish.admin.mbeanserver.JMXStartupService$JMXConnectorsStarterThread run
INFO: JMXStartupService has disabled JMXConnector system
Jan 31, 2013 10:05:13 AM com.sun.enterprise.connectors.jms.util.JmsRaUtil getInstalledMqVersion
WARNING: RAR7000 : Check for a new version of MQ installation failed : /var/folders/kr/vj5fd5s91g76_t348ndnbtxr0000gn/T/gfembed883899172293116872tmp/lib/install/applications/jmsra/../imqjmsra.rar (No such file or directory):/var/folders/kr/vj5fd5s91g76_t348ndnbtxr0000gn/T/gfembed883899172293116872tmp/lib/install/applications/jmsra/imqjmsra.rar
Jan 31, 2013 10:05:14 AM org.glassfish.admin.mbeanserver.JMXStartupService shutdown
INFO: JMXStartupService and JMXConnectors have been shut down.
JdbcRuntimeExtension, getAllSystemRAResourcesAndPools = [GlassFishConfigBean.org.glassfish.jdbc.config.JdbcResource, GlassFishConfigBean.org.glassfish.jdbc.config.JdbcResource, GlassFishConfigBean.org.glassfish.jdbc.config.JdbcConnectionPool, GlassFishConfigBean.org.glassfish.jdbc.config.JdbcConnectionPool]
Jan 31, 2013 10:05:15 AM com.sun.enterprise.v3.server.AppServerStartup stop
INFO: Shutdown procedure finished

Process finished with exit code 0

You should be seeing something the above output in the IDE if you are doing it right. It would appear we will have to be on our guard until JDK 9 in order to avoid class path loading issues. My book on the user guide to Java EE 7 is scheduled for the Summer of 2013.

Happy Testing.

+PP+

Categories: Author, Book, Glassfish, JavaEE, javaee7, programming Tags:

Agile Software Developer Terminology for New Programmers

December 21st, 2012 2 comments

This is a post for new developers, young, inexperienced or old and retraining into information technology.

Recently, I had a discussion with many engineers at one of those many London user group nights about how there is so much new stuff that we have to explain to people new to programming. One person had to coach a graduate developer on writing unit tests. Another person had to explain the reasons why dependency injection is better than dependency lookup.  I can recall similarly stuff, being able to gently and concise explain why we should have unit tests in the code, and why we need them.

Here is my current matrix of terms:

Term Description
YAGNI You Are Not Going To Need It – The issue hare is that far more code is written than necessary to solve or deliver application functionality. 

Classic symptom: Added unused finder methods to session beans in Java EE

DRY Don’t Repeat Yourself – writing code that has lot of duplication across methods, classes, packages and package object. 

Classic symptoms: Copy & Paste coding in unit tests and repeated metadata in entity and the front end

KISS Keep It Simple Silly [or Stupid] – a mantra to describe writing only code to solve the function problem instead of writing a less complicated codeAlso see Occam’s Razor.

 

Classic symptom: Too many abstract layers in a software application

WET Write Every Time – the antithesis to DRY, where code is deliberately written that repeats lots and lots of time in different classes, packages, and functions. 

Symptoms: Deciding to do things your way and instead of collaborating with the other developers and finding some common ground.Classic antidote: DRY, Unit Tests and Code Refactoring.

WETTT Write Everything Ten Thousand Times – the hyperbole colloquial version of WET
R3 Rules of Three – This is not the proprietary operating system of the same name, or the classic 1980′s arcade game, or either the description of a maxed out pimp-my-ride Volkswagen Golf; but the idea that when ever you have three duplicated parts of code in a method, function or classes then it is time to refactor the duplication in to single method. See Rule of Three computer programming. 

Related to DRY and WET

 

Class Symptom: Ignoring the code repeats because of time pressures, or the Scrum master says no, don’t do it in this sprint.

DBC Design By Contract – the idea of building a service from a contract first. In Java you write the interface as simply as possible and then secondly worry about the implementation class.

 

Interfaces are easier to refactor around and because you can plug different implementations into the interface you get higher cohesion and lower coupling.

 

Classic Example: JDBC specification since version 1.0. There are tons of implementations for different relational databases including MySQL, Postgres, H2, Derby etc.  Every Java programmer knows how to code against JDBC because that they don’t have to fight with an different implementation, which vary, because the DBC implied it will do the right thing most of the time.

 

Also related to standardisation of application programming interfaces.

BDUF or BUDF Big Up-Front Design – a problem with many large corporate institutions that sometimes require a 100 – 1000 page document full of business requirement before any software construction gets the green lightSome poor architect or business analyst will have spent weeks investigating and chatting to the business about the requirement, only for the development team to say the document is practically worthless.

 

Antidote: Get the technical lead and some key developers talking with the business and the analysts and the customer. Ideation sessions everybody!Symptom: Waterfall methodology and aspects of the investment banking IT culture

 

Antidote: Unknown, lots of people how tried to bring “Agile” with both a big A and small A to many of these institutions with some success and failure

Pink Book Describes the book with a Pink Cover called Extreme Programming Installed by Ron Jeffries, Ann Andersen, and Chet Hendrickson. I do not recommend this for new starters unless for reference, since the Pink Book is now rather old, 2000, there are other more recent Agile development books and courses that help new Java developers.
YOLO You Only Load It Once [If Ever] – this is related to fact that you want to have a single source of truth in an application system. This is problem of mis-architecture, where someone has not thought the functional requirement through enough.

 

Classic Example: Shopping Cart Service EJB – you only ever want one implementation of the pay-point in an application, albeit you will have many pay-point providers (credit and debit card third parties and PayPal)

 

The If-Ever part is YOLO and YAGNI added together. You are not sure of the another part of the system loads the data, so you decide to keep the component. (You probably want to put a logging client on the YOLOIF thing so that you can effectively decide to chuck the component if nobody has used the function in 12 or 18 months time.)

 

Digression: If you have find data that is constantly being uploaded to serve a web request then perhaps it really needs caching and not YOLO.

Spike A quick exploration of coding in Sprint in SCRUM methodology, which is also time-boxed inside a single sprint, usually. In a Spike you are probably are looking an new API, like a cloud service or user interface API like JavaFX or similar and basically you explore if the function can implemented relatively well in the new API.In short, you are trying to build some confidence in a new area before committing yourself and other resources to it. Spikes are usually contained and protected from the flow of the critical path and restricted to a time length. See SMART goals. Once your team has gained confidence and knowledge in the new “thing” then reasonable estimates can be made.

 

Classic Examples: Adopting a build system – moving from Apache Ant to Maven; moving from Subversion to Git; Adopting a new open source library

TDD Test Driven Development – often conflicted as not being fully explained as a change of discipline and mind.”You are only ever doing one of these four things: writing unit tests, writing production code, refactoring unit tests, and refactoring production code; and never doing more than one at these previous at the same time.”
TFD Test First Development – builds on the ideas of TDD and then extends the discipline to writing unit test code before any production code.”Once you have a brand new unit test written completely, then you make sure that new unit test(s) actually fail in order to switch over to writing production code ensures the the new test passes.  After you have done that, you refactor the tests. Run all tests for all the green bars. Refactor the production code and runs the tests for all the green bar.Repeat: Go back to the start; write a new unit to that will check validate operation of the next function for the application. Repeat with the same formula as above.”

 

Velocity This is often misunderstood as a very basic measurement on the Return-on-Investment for SCRUM/XP software development and it has nothing at all to do with financial services, budgets and/or reporting. The creators of SCRUM/XP now disuade velocity as a ROI indicator at all.

 

Velocity is the number of story points completed per team per iteration. To the SCRUM/XP  experienced: Velocity is equal to the aggregated units of work completed over aggregated time intervals, which implies you measure each progress of tasks in two or more sprints.

Story Point For each user story in the sprint or task, predict  how hard it is to implement by using unit of reference. 

Story points are usually written in Fibonacci numbers: 0, 1, 1, 3, 5, 8, 13, 21, 34, 55, 89, 144Every agile team in the world has a definition of a user story unit point.Teams decide on the backlog items in order to come up with predictions and these joint predictions every member of team go to decide what should applied to the next sprint.

DTSTTCPW Do The Simplest Thing That Could Possibly Work – Related to Spike and KISS in many ways. If you are pressed for time and some trading systems developers in investment bank are then this is your working life. 

DTSTTCPW certainly invites team collaboration and effective sound-boarding from other developers and members of the team, otherwise you are asking for trouble.

VoC Voice of the Customer – This is a term from SCRUM methodology, but I am about 20% unsure about this one; I believe 80% of the time to mean a proxy, a placeholder, for the real customer, the person who understands the business requirement and will of the customer. Because the true user is unavailable for some reason due to authority, culture or organisation, or even geo-location. 

Some people have amusing called this abbreviation, the Voice of Reason, especially when they do not enjoy working with the customer directly.

Unit Test In Java programming, a Unit Test is a Java JUnit framework test class or TestNG framework test class that specifically verified and validates a single function of work in an application 

A unit test requires a target, which can be a Java Class, a Service Bean, Managed Bean or something implements the said functionality.

 

Unit test are often seen as low-level fast and efficient tests.

Functional Test A functional test is a larger test, which can also be a unit test, designed to test packages of classes or sub part of the overall application infrastructure. Functional test validates if the application meets one of the customer’s external requirements on performance, results and efficiency.

 

Symptom: a functional test is not necessarily a unit test, and not all functional tests are acceptance tests.

Acceptance Test An acceptance test is the same as a functional test in name only. Acceptance tests are those where the customer wants to see the validation pass in order they sign of the implementation. 

Symptom: If the customer is disastisfied with the application at demonstration time, then at least the one of the acceptance test is broken. Add one in the next sprint.

SOLID A set of five principles:Single Responsibility, Open-Closed, Liskov Substitution, Interface Segregation and Dependency Inversion.
Single Responsibility Principle An object class, a service bean, web service, a function or procedure should have only one single responsibilitySymptom: It is hard to write unit test for complex object, because it doing WETTT
Open Closed Principle Open for extension and closed for modificationIt means you can subclass the object, but the object is encapsulated by not allowing an outside object to gainfully change the internals. 

Symptom: leakage in object implementation, hard code dependency, and not working with Java interfaces (or interface like constructs i.e. Scala traits and mix-ins)

Liskov Substitution Principle Idea of swap-ability and is expressed as a Design By Contract (DBC).I can swap in another object X which is an implementation of T if that objects is a type of T and the overall application works.This is the basis of mocking objects, mocking implementation frameworks; testing in general; proxy remote objects, persistence capable objects; application server and lifecycle monitoring situations; plug-and-play and restartable applications. I could go on, but I won’t.
Interface Segregation Principle A service interface that does only single specific functional thing is better than a service interface that does several different things. 

Symptom: Failure to adhere to the KISS principle. In days gone, the non standard C++ String libraries where everybody threw in the kitchen sink of methods for any operation that one would want to write that manipulated a C/C++ String (char*)

Dependency Inversion Principle Idea of not hard-wiring a direct relationship to a dependent into object.In Java EE world, you would use a dependency injection container such as CDI to inject different managed beans into a service bean. 

Dependency inversion also should mean in my humble opinion given up on managing the life-cycle of service components and beans. The lifecycle is managed by the application container, the cloud provider or whatever it is you are using.

 

In another school of thought: every application is managed these days, whether it is the operating system, a virtual machine or web container or mobile platform (iOS and Android). This is the way forward.

Design Patterns A classic book on Design Patterns by Erich Gamma et Al. 

Ask your local technical leader to lend you his or her copy of the book; and if they don’t have a copy then that really sucks. Tell them to give you a personal training budget and buy the book yourself!

Glad to be of service to all my readers.

Merry Xmas and Happy New Year 2013!

+PP+

PS: I, once, had a notebook and file with a lot more of these terms with or without explanations. If I find anymore abbreviations and terms that I will add to this blog entry.

Where There is Still Hope

December 4th, 2012 Comments off

On Monday evening, 3rd December, 2012, I went along to the British Computer Society London in the Strand for a lecture from non other than Professor Sir Tony Hoare. It is not everyday you get meet a personality who has been so well deserved lauded in the computer science, in its history and its modernity and  brief time of existence. Tony Hoare was the inventor of the famous Quicksort computer algorithm in 1960 (at the age of 26). I remember a first encounter with the QuickSort algorithm in Herbert C. Schildt’s Programming in C book.

Professor Hoare was in town to give a Peter Landin lecture on Laws of Concurrent Design. The talk was essentially about mathematical calculus of computer programs; how they could be expressed in terms of mathematical functions, and set of basic axioms with rules, then could be composed together to proof notations about concurrency and sequential operations.

Professor Sir Tony Hoare at BCS London, December 2012

Oh gosh, it has been awful long time, since I personally looked at additional mathematics course book. Yet I understood this level of discourse in the talk. I found that I could understand the Exchange Axiom to my surprise. Although, I think Professor Hoare had simplified the actual formulas for the benefit of his talk and the level of the audience.

For the ordinary punter, dealing with this abstract mathematical terms is clearly out of the level of usefulness, however these are the theories that allows computer scientists to build programs such as compilers, static analysers and the tools that language writers use to build new programming languages in order to give us the world of devices and applications that we all use today. Without these pioneers in the computer programming arena, we would be, I think, far far behind. Indeed, we are standing, everyday, on the shoulders of giants and reaching for the stars.

I thoroughly enjoyed the Professor Hoare talk, and the fact that this guy is older than me and still working (at Microsoft Research in Cambridge, England) is inspiration enough to say to hell with silo management and bad attempts to be hip with the agile practices. Say hello to diversity in corporation, the future is for real. Here is a real star: a living legend.

+PP+

PS: I also got meet up with some fellow ACCU members who also turned up for the lecture.

NightHacking Tour with Stephen Chin

November 20th, 2012 Comments off

On Monday 19th November 2012, in the evening, I interviewed for the final episode of the Nighthacking tour by Stephen Chin, who is an Oracle Evangelist for Java, Chairperson of the JavaOne Program committee, and also a Java Champion a.k.a @steveonjava.

We talked about ScalaFX the open source Domain Specific Language and Scala library framework for JavaFX 2.x. I showed off my version of the JavaOne 2011 demo in Scala. It is called VideoCubeDemo.scala. We actually started to fix a bug in the demo. We checked into version control a quick fix that helped and pushed that to Mercurial.

I also talked about my upcoming reference book for JavaEE 7, which will be published by Packt. I demonstrated some of the example Context Dependency & Injection code that will feature in the book. I showed off JBoss WeldDeltaSpike and Arquillian framework. We discussed some of the other upcoming features of Java EE7 like JAX RS and WebSockets; and also how CDI could be used outside the container in a JavaFX application.

Many thanks to SkillsMatter for hosting us, in particular Wendy Devolder and Nick Devolder; and extra special medal goes to Ami Partridge for being very helpful, staying late into the evening to help us get this live stream out to the public with wired ethernet cables, router boxes, WI-FI and tea.



Video streaming by Ustream

Hosted by Skills Matter, the company behind the Scala Exchange and Grails Exchange.


SkillsMatter 2012

 

+PP+

A Groovy Script to Keep The Internet Cafe’s WIFI Alive

October 26th, 2012 Comments off

Have you ever been to an Internet Cafe and connected to the free WIFI? Have you found that after five minutes of activity the connection has been dropped and you have go through the License and Terms of Agreement again and again and again? Annoying isn’t.

Well after expiring this at Charlotte Airport in the USA recently, I re-concocted the script that I wrote for the half-dozenth time. This time I going to blog it and save it for all time.
Here is a simple Groovy script to keep the Internet alive.

// Hang-up to Internet Connection Groovy Script
// Useful for Internet Cafe that drop WIFI connectivity through
// perceived lack of activity e.g. Starbucks / Hotels
// Peter Pilgrim
// 28 September 2012

def maxTimeout = 30000
def minTimeout = 15000

def domainList = [
    'gmail.com', 'google.co.uk', 'google.com', 'bbc.co.uk', 'cnn.com', 'java.oracle.com',
    'facebook.com', 'twitter.com', 'oracle.com', 'zen.co.uk', 'java.net', 'www.scala-lang.org',
    'plus.google.com', 'guardian.co.uk', 'linkedin.com', 'www.typesafe.com', 'www.yahoo.com',
    'www.ibm.com', 'www.apache.org', 'www.adobe.com', 'www.microsoft.com', 'www.stackoverflow.com',
    'www.apple.com', 'groovy.codehaus.org', 'java.oracle.com', 'www.telegraph.co.uk', 'www.jroller.com',
    'www.dell.com', 'www.samsung.com', 'www.amazon.co.uk', 'docs.oracle.com', 'www.infoq.com',
    'www.devoxx.com', 'www.qconlondon.com', 'www.smashingmagazine.com', 'en.wikipedia.com' ]

def count = 1
while (true) {
    int idx = (int)( Math.random() * domainList.size )    
    println "[$count]  nslookup ${domainList[idx]}"
    def process = "nslookup ${domainList[idx]}".execute()
    println "Found text ${process.text}"
    
    def sleepTime = (int)( minTimeout + Math.random() * ( maxTimeout  - minTimeout))
    Thread.sleep( sleepTime );
    
    ++count
}

// done

The script can be improved with a much larger set of domain names, perhaps I could machine generate the domain names from the Chrome Browser history, or something like this. That is about all I would do, except to parameterise the command line arguments. On Mac or Linux I just hit the terminal and type with auto completion of course groovy ~/hangon-to-internet.groovy

Now, the only thing to write is a similar script to keep the WIFI connection to the both mobile phone and tablet alive. Answers on a post card please.

+PP+

Categories: Groovy, language, programming, tool Tags:

Custom Ordering Scala TreeMap

July 12th, 2012 1 comment

How do you get custom ordering in a Scala TreeMap?

Well this puzzled me for a while. The answer lies in the world of implicits and receiver type converters.

In a nut shell, a scala.collection.immutable.TreeMap is a SortedMap. If you look at the documentation for TreeMap, you will see it takes an Ordering[T] as an implicit argument.

Normally when you declare a TreeMap, say inline, it will use the default Ordering object like so:-

scala> val dtm = TreeMap( "a" -> 1, "bc" -> 2, "def" -> 3 )
dtm: scala.collection.immutable.TreeMap1 = Map(a -> 1, bc -> 2, def -> 3)

If you want to change the ordering of the keys, for example, instead of the ascending order by String content, into, say, a descending order of strings length then you need an Ordering type.

scala> object VarNameOrdering extends Ordering[String] {
         def compare(a:String, b:String) = b.length compare a.length
       }
defined module VarNameOrdering

Now you can use the second argument list in an explicit fashion like this:

scala> val tm1 = TreeMap( "a" -> 1, "bc" -> 2, "def" -> 3 )( VarNameOrdering )
tm: scala.collection.immutable.TreeMap1 = Map(def -> 3, bc -> 2, a -> 1)

We pass the object to the TreeMap, which is rather similiar to a Java Collection Comparator object without the boilerplate instantiation. The keys of the TreeMap are now ordered by String lengths. We add more elements and the map will stay ordered.

 val tm2 = tm1 + ( "food" -> 4 )
cala.collection.immutable.TreeMap1 = Map(food -> 4, def -> 3, bc -> 2, a -> 1)

However, a word of caution, one needs to be careful and remember that maps are usually implemented as hashes.

scala> val tm3 = tm2 + ( "z" -> 5 )
tm3: scala.collection.immutable.TreeMap1 = Map(food -> 4, def -> 3, bc -> 2, z -> 5)

Surprised? You should be.

Another way to sort a map is just to get access to the keys and sort.

scala> dtm.keys.toList.sortWith ( _.length > _.length )
res3: List1 = List(salad, def, bc, a)

scala> dtm.keys.toList.sortWith ( _.length > _.length ).map( k => ( dtm.get(k).get ))
res4: List[Int] = List(10, 3, 2, 1)

scala> dtm.keys.toList.sortWith ( _.length > _.length ).map( k => ( k, dtm.get(k).get ))
res5: List[(java.lang.String, Int)] = List((salad,10), (def,3), (bc,2), (a,1))

This may well be a better solution, as you have not lost a key in flight! Considering how data is going to be stored is a major decision that needs to be taken early. You can always decide how to write projection of that data much later.

Finally, it is interesting to see the parallels between Java and Scala

scala> dtm.keys
res6: Iterable1 = Set(a, bc, def, salad)

scala> dtm.keys.toList
res7: List1 = List(a, bc, def, salad)

PS: I can safely say I have used Scala professionally today in financial enterprise.

Categories: Development, language, programming, Scala Tags:

QCon London 2012 Philip Wadler Answers “What is a Monad?”

March 9th, 2012 Comments off

Today, I am at the final day of the QCon London 2012 conference in partuculary in the Scala and Functional Languages track.

Philip Wadler gave an excellent presentation on functional programming and his belief about lambda calculas, mathematical formal logic and an advanced computer science. At the end of his talk, there was a lot of people who stayed behind for question answers. Of course, one of the audience members asked the proverbial question: “What is a Monad?”

Here is Professor Wadler, University of Edinburgh, best distinguished answer to this question?

e a

Stayed tuned for a full report on QCon London 2012 ;-)

ScalaFX, Scala Build Tool and JavaFX 2.0 Libraries

November 8th, 2011 Comments off

Hard Reference

In my last blog entry, ScalaFX A Walkthrough, I talked about setting up ScalaFX 2.0 in IntelliJ 10.5 with the Scala Build Tool (SBT) in the screencast. I left out some salient points.

The JavaFX 2.0 SDK has one important hardcoded reference in it, which makes it hard to use in a Maven or Ivy repository. The reference is in a class called NativeLibLoader and it attempts to initialise the native library with a fixed path. The actually call is something like this:

      AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
          NativeLibLoader.loadLibrary("mat");
          return null;
        }
      });

 

The NativeLibLoader class JavaFX 2.0 expects to find native libraries in the “/../bin” of the class path that references jfxrt.jar.

In order, to get a around the problem you need to manually copy all of JavaFX 2.0 native libraries (*.DLL files) to SBT folders as well.

First, create the directory:

cd scalafx
mkdir lib_managed\jars\com.oracle\bin

 
Note: SBT uses Apache Ivy underneath the hood, hence the peculiar non-Maven group name “com.oracle” as the pathname.

Then, copy the native libraries over:

copy “%JAVAFX_HOME%”\rt\bin\*.dll   lib_managed\jars\com.oracle\bin

 

After this fix for the missing native library, you can build the ScalaFX library successfully using SBT:

 sbt
> compile
> test
> run
> exit

 

Finally, in order to generate a JAR file, you then execute sbt thus:

sbt package
sbt clean compile test package

 

Look in the folder "target" for "scalafx-1.0.jar.

Here are some of the SBT fragments that I added to my version the build.sbt file that will help you get configured:

// Upgraded the latest Scala version from 2.9.0.1 to 2.9.1
scalaVersion := "2.9.1"

// Harded code my local repository, because the following breaks Windows file resolution
// resolvers += "Local Maven Repository" at "file://"+Path.userHome.absolutePath+"/.m2/repository"
resolvers += "Local Maven Repository" at "file:///Users/Peter/.m2/repository"

// UPGRADE to JAVAFX 2.0 Final Candidate Status (FCS)
libraryDependencies ++= Seq(
    "com.oracle" % "javafx-runtime" % "2.0"
)

// Everyone should using Java 1.6 by now shouldn't they?
javacOptions ++= Seq("-source", "1.6", "-target", "1.6")

// Reduce the JVM heap space for my laptop!
javaOptions += "-Xmx384M"

// Change the JAVA home to something on your system, if required
// javaHome := Some(file("/Library/Java/JavaVirtualMachines/1.6.0_24-b07-330.jdk/Contents/Home"))
javaHome := Some(file("/Program Files/Java/jdk1.6.0_29" ))

 
In order to install the JAR into a local Maven Repository, you need to add the following stanza to the build.sbt file. Again, this is not portable as it directly reflects my machine and my user space.

// Set publish Maven for local repository
publishMavenStyle := true
// Set up the Maven repository
publishTo := Some(Resolver.file("file",  new File( "/Users/Peter/.m2/repository" )) )

 
Now, you can run the SBT command “publish” like so:

> sbt publish 
[info]  published scalafx to C:/Users/Peter/.m2/repository/org/scalafx/scalafx/1.0/scalafx-1.0.pom
[info]  published scalafx to C:/Users/Peter/.m2/repository/org/scalafx/scalafx/1.0/scalafx-1.0.jar
[info]  published scalafx to C:/Users/Peter/.m2/repository/org/scalafx/scalafx/1.0/scalafx-1.0-sources.jar

 
As you can see this is the equivalent of invoking mvn install:install-file almost.

If you want to install to a local Apache Ivy then use the SBT command “publish-local” instead.

> sbt publish-local
[info]  published scalafx to C:\Users\peter\.ivy2/local/org.scalafx/scalafx/1.0/poms/scalafx.pom
[info]  published scalafx to C:\Users\peter\.ivy2/local/org.scalafx/scalafx/1.0/jars/scalafx.jar
[info]  published scalafx to C:\Users\peter\.ivy2/local/org.scalafx/scalafx/1.0/srcs/scalafx-sources.jar
[info]  published ivy to C:\Users\peter\.ivy2/local/org.scalafx/scalafx/1.0/ivys/ivy.xml

 

Please let me know, if you have any more problems. Thanks.
 

IntelliJ and SBT

There was a definite bug in SBT Plug-in for IntelliJ IDEA that prevents the command line input working more than once. I explained this in the video screencast. However, It has been fixed recently, so make sure you update this plug-in to get the fix.

 

Proposal

This copying of manuals DLL is a real pain for Maven / Ivy / SBT developers, because we have do this every single project. I believe Oracle could standardise on the actualise “platform” name (e.g. “Win”, “Mac”, “Solaris”, “Linux”) for the actual loading or come up with a way of making the mechanism indirect. Let me make myself abundantly clear:

// This SBT stanza will not work!!! It is just for illustration
libraryDependencies ++= Seq(
  "com.oracle" % "javafx" % "2.0" % "provided" ,
  ( 
  "com.oracle" % "javafx-windows" % "2.0" % "provided" |
  "com.oracle" % "javafx-macosx" % "2.0" % "provided" |
  "com.oracle" % "javafx-solaris" % "2.0" % "provided" |
  "com.oracle" % "javafx-linux" % "2.0" % "provided" )
}

Therefore Linux native libraries (*.so file) would in a known repository folder and of course you create a POM or IVY file and these entries:

~/.m2/repository/com/oracle/javafx-linux

We know that genuine differences exists in OS and CPU architecture and even chip hardware and therefore we should be sensitive to native changes e.g. Windows 32 versus 64 bit and AMD/Intel then may be schema could like this:

libraryDependencies ++= Seq(
  "com.oracle" % "javafx" % "2.0" % "provided" ,
  "com.oracle" % "javafx-${PLATFORM}[-${VERSION}][-${ARCHITECTURE}][-${CHIPSET}]" % "2.0" % "provided" 
}
// PLATFORM is "windows" and VERSION is "" or "7" or "8"
// and ARCHITECTURE is "" or "32bit" or "64bit"
// and also CHIPSET is "" or "Intel" or "AMD"

I would be very interested in your thoughts on this scheme above. Thank you in advance.

Categories: Development, Java, JavaFX, programming, Scala Tags:

Install JavaFX Runtime Into Local Maven Repository

October 17th, 2011 9 comments

In order to get JavaFX 2.0 to work with a Maven Repository, requires some fudge factor. Because one cannot simply redistribute JavaFX Library, you have to install the libraries manually into a local Maven repository.

This is my MSDOS command script to do it:

REM Installing Oracle JavaFX 2.0 Runtime into a Local Maven Repository
REM Based on the information from JFXtras 2.0 Project
REM http://code.google.com/p/jfxtras/wiki/ContributorGettingStarted
REM Peter Pilgrim 12th September 2011 in Crete

REM set JAVA_HOME=C:\Program Files\Java\jdk1.6.0_27
REM set javafx.home=C:\Program Files\Oracle\JavaFX 2.0 SDK
REM set JAVAFX_HOME=C:\Program Files\Oracle\JavaFX 2.0 SDK
REM set javafx.home=%JAVAFX_HOME%
REM set USERPROFILE=C:\Users\Peter

REM Install the JavaFX Java Library
call mvn install:install-file -Dfile="%javafx.home%\rt\lib\jfxrt.jar" -DgroupId=com.oracle -DartifactId=javafx-runtime -Dversion=2.0 -Dpackaging=jar



pushd "%javafx.home%\rt\bin"
del /f /q %USERPROFILE%\Documents\javafx-dll-temp-bin.jar
"%JAVA_HOME%\bin\jar" -cf  %USERPROFILE%\Documents\javafx-dll-temp-bin.jar *.dll
popd 

REM Install Native libraries
call mvn install:install-file -Dfile=%USERPROFILE%\Documents\javafx-dll-temp-bin.jar -DgroupId=com.oracle -DartifactId=javafx-runtime -Dversion=2.0 -Dpackaging=jar -Dclassifier=windows

REM Copy the binaries to the Maven Local Repository
copy "%javafx.home%\rt\bin"  %USERPROFILE%\.m2\repository\com\oracle\javafx-runtime\bin

REM End.

Once you have the local repository set up, once include a Maven dependency into a project like this:

    <dependencies>
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>javafx-runtime</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

Thus the group is com.oracle, the artifact id javafx-runtime, and the version is 2.0.

There you go.

Progressive JavaFX Custom Components

October 16th, 2011 Comments off

I have completed all three of my Progressive JavaFX 2.0 talks in California, at JavaOne 2011, Silicon Valley Code Camp at Foothills College and Silicon Valley JavaFX User Group at Oracle Conference Center.

You get the slides deck from here as a PDF document.

The source code is a Maven assembly distribution, a ZIP file, which I concocted on the last day of California. The code is available here.

The slide deck is below (from Slide Share):

 

 

 

As ever if you have any comments in general, modifications, and just essentially interesting things to say, then please do not hesitate to contact me here directly. You can add to the blog entry comment and also do the social networking Twitter, Google+ thing.

Let’s us keep pushing things forward.

Best.

-PP-
  14th October 2011

Categories: Design, Java, JavaFX, JavaOne, Presentation, programming, UI Tags: