Archive

Archive for the ‘language’ Category

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:

Scalafication of an Equity Quote Application Part 3

July 26th, 2011 Comments off

This is the final part in a series of article about porting an existing Java application to Scala. The application calls the Yahoo! Financial web service and retrieve stock quotes for the user, storing them in a local repository. The original Java project was described in the part one.

In the part two of this series, we looked at the unit test, and in particular the behaviour driven development (BDD) styles in the ScalaTest framework.

We will look at the Scala implementation of this business application. The easiest task is to simply convert the exceptions. Here are the Exceptions.scala file:

 

package uk.co.xenonique.stockquoteapp_scala

class ConnectionException( msg: String, root: Exception ) 
extends RuntimeException( msg, root ) {
   def this( msg: String ) = this( msg, null )
}

class DataRetrievalException( msg: String, root: Exception ) 
extends RuntimeException( msg, root ) {
   def this( msg: String ) = this( msg, null )
}

class UnknownStockSymbolException( msg: String, root: Exception ) 
extends RuntimeException( msg, root ) {
   def this( msg: String ) = this( msg, null )
}

 

We have more than one public class in a single source file. It is sort of allow Scala to look like a dynamic scripting language like Python or Ruby.

Next, we port the quote repository over to Scala. We remove the semi-colons, reverse the declarations of the variable types on the way. We take advantage of Scala support for Option types, we retrieve the stock quote by symbol name. The Scala library has two types of collections: immutable and mutable. By default, immutable collections are those that imported into the compiler as a predefinition. The QuoteRepositoryKeyValueStore imports a mutable Map collection for storing symbol associated with stock quotes. 

Here is the QuoteRepository.scala file:

 

package uk.co.xenonique.stockquoteapp_scala

import scala.collection.mutable.Map

trait QuoteRepository {
  def isEmpty(): Boolean
  def size(): Int
  def clear(): Unit
  def store( quote: StockQuote  ): Unit
  def get( symbol: String ): Option[StockQuote] 
  def contains( symbol: String ): Boolean
  def getSymbols(): List[String]
}

class QuoteRepositoryKeyValueStore extends QuoteRepository {

  private var store: Map[String, StockQuote] = Map()

  def clear(): Unit = { store.clear() }

  def contains(symbol: String): Boolean = store.contains(symbol)

  def get(symbol: String ): Option[StockQuote] = store.get(symbol)

  def isEmpty(): Boolean = store.isEmpty
	
  def size(): Int = store.size

  def store(quote: StockQuote ): Unit = {
    store.put(quote.symbol, quote)
  }

  def getSymbols(): List[String] = {
    // We use a tuple to iterate through the map, which return mutable list
    // then we use "toList" to convert to an immutable list.
    ( for ( (key,value ) <- store ) yield (key)  ).toList
  }

}

 

In above implementation class, we can write, in Scala, methods such as size() as one-liner methods.

We can convert the Java stock quotes to a case class and get the benefits of an implicit equalsTo(), hashCode() and toString() methods; and even get a handy copy() method too. Note: That we override the definition of the toString() class specifically for better formatting and, of course, debugging, but we did not need to do this for a case class.

Here is the StockQuote.scala file:

 

package uk.co.xenonique.stockquoteapp_scala

import java.math.RoundingMode
import java.math.BigDecimal

case class StockQuote( symbol: String, askPrice: BigDecimal, bidPrice: BigDecimal ) {

  // Auxiliary (convenience) constructor
  def this( symbol: String, askPriceStr: String, bidPriceStr: String ) =
    this ( symbol, new BigDecimal(askPriceStr).setScale(2, RoundingMode.DOWN ), new BigDecimal(bidPriceStr).setScale(2, RoundingMode.DOWN ) )

  // Auxiliary (copy) constructor
  def this( ref: StockQuote ) = this ( ref.symbol, ref.askPrice, ref.bidPrice )

  def meanPrice: BigDecimal = bidPrice.add( askPrice.subtract(bidPrice).divide( StockQuote.TWO ).setScale(2, RoundingMode.DOWN ) )

  override def toString(): String = {
    return "StockQuote [ symbol=" + symbol +", askPrice=" + askPrice +
      ", bidPrice=" + bidPrice + ", meanPrice="+meanPrice+"]";
  }
}

object StockQuote {
  def TWO = new BigDecimal("2.0")
}

 

The real hard part of the quote retriever service is get information from the Internet, by calling the web service. Luckily calling the Yahoo! Finance service is a simple REST GET request in comparison to other more complicated SOAP or REST web services.

Here is the QuoteRetriever.scala file:

 

package uk.co.xenonique.stockquoteapp_scala

import java.lang.NumberFormatException
import java.io._
import java.net._

trait QuoteRetriever {
  def getStockQuote( symbol: String ): StockQuote
}

object QuoteRetrieverYahooImpl {
   val TOKEN_SYMBOL="@SYMBOL@"
   val DEFAULT_URL_FRAGMENT="http://finance.yahoo.com/d/quotes.csv?s="+TOKEN_SYMBOL+"&f=sb2b3"

}

class QuoteRetrieverYahooImpl( var urlFragment: String = QuoteRetrieverYahooImpl.DEFAULT_URL_FRAGMENT ) 
extends QuoteRetriever {
  
  def getStockQuote( symbol: String ): StockQuote = {

    val queryUrl: String = urlFragment.replace(QuoteRetrieverYahooImpl .TOKEN_SYMBOL, symbol)

    try {
      val url: URL = new URL( queryUrl )
      val connection: HttpURLConnection  = url.openConnection().asInstanceOf[HttpURLConnection]
      connection.setRequestMethod("GET")
      connection.connect()

      val is: InputStream = connection.getInputStream()
      val reader: BufferedReader = new BufferedReader( new InputStreamReader(is) )

      try {
        val line = reader.readLine()
        if ( line != null ) {
          val tokens = line.split(",").toList
          if ( tokens.length < 3 ) {
            throw new DataRetrievalException(
              "Data service at URL=["+queryUrl+"] does not supply enough fields (3 != "+tokens.length+")")
          }
          var stockSymbol = tokens(0)
          if ( stockSymbol.length() > 0 &&
              stockSymbol.charAt(0) == '"' && stockSymbol.charAt(stockSymbol.length()-1) == '"') {
            stockSymbol = stockSymbol.substring(1, stockSymbol.length()-1 )
          }
          val askPrice = tokens(1)
          if ( "N/A".equals(askPrice)) {
            throw new UnknownStockSymbolException(
              "Unknown stock quote symbol ["+stockSymbol+"] price not available")
          }
          val bidPrice = tokens(2)
          if ( "N/A".equals(bidPrice)) {
            throw new UnknownStockSymbolException(
              "Unknown stock quote symbol ["+stockSymbol+"] price not available")
          }

          try {
            return new StockQuote(stockSymbol, askPrice, bidPrice)
          }
          catch {
            case e:NumberFormatException =>
              throw new DataRetrievalException(
                "Unable to read numerical data from quote service URL=["+queryUrl+"]", e)
          }
        }
        else {
          throw new DataRetrievalException(
            "Data unavailable from quote service URL=["+queryUrl+"]")
        }
      }
      finally  {
        if ( reader != null) {
          try {
            reader.close()
          }
          catch  {
            case e: IOException => null
          }
        }
        if ( is != null) {
          try {
            is.close()
          } 
          catch {
            case e: IOException => null
          }
        }
      }
    }
    catch {
      case e: MalformedURLException  =>
        throw new ConnectionException("unable to connect to the remote quote service URL=["+queryUrl+"]", e)

      case e: IOException =>
        throw new ConnectionException("I/O failure reading service URL=["+queryUrl+"]", e)
    }
  }
}

 

Effectively, we could have left the QuoteRetriever as a simple Java interface, because we gained nothing. If however we wanted to define a default implementation in a Scala trait we could do so, where it would be not possible with the current version of Java 6 / 7.

We make use of the companion object QuoteRetrieverYahooImpl to define Scala constants. Essentially this would be same as declaring a Java variable as public final static String.

Inside the QuoteRetrieverYahooImpl class, let us look at the implementation method getStockQuote(). We chucked away Java standard library StringTokenizer and replaced it with the nicer Scala equivalent. We split a String into Array[String] of fragments using the split method, and then convert the array into a list collection by calling toList. Since Scala 2.8, these methods toList(), toSet() and toArray() are ubiquitous across the Scala collections.

There is probably a more object functional way of building the temporary variables using functions and closures, however for intermediate Java developer this is easier to follow. The rest of the code is just boiler plate to tackle the exception handling of the Java I/O library. See the last part of this article for an improvement.

Last, but not least is the main application class in the StockQuoteApp.scala file.

 

package uk.co.xenonique.stockquoteapp_scala

import java.lang.System

class StockQuoteApp( retriever: QuoteRetriever, repo: QuoteRepository ) {
  

  def this() = this( new QuoteRetrieverYahooImpl(), new QuoteRepositoryKeyValueStore() )

  def doInteractive(): Unit = {

    println("=======================================================")
    println("   Welcome Peter Pilgrim's Stock Quote Application")
    println("=======================================================")

    var quit = false
    while ( !quit) {
      println("Type in a stock symbol or `:repo' to list the repository or `:quit' to quit")
      println("or `:clear' to clear the repository")
      var line = readLine("$ ")
      if ( line != "" ) {
        line = line.trim()
        if ( line.startsWith(":r") || line.startsWith(":p")) {
          val symbols  = repo.getSymbols()
          printf("%10s  %9s %9s %9s\n", "SYMBOL", "MEAN", "ASK", "BID")
          printf("%10s  %9s %9s %9s\n", "--------", "------", "-----", "-----")
          for ( symbol <- symbols ) {
            val quote = repo.get(symbol).get
            printf("%10s: %9.2f %9.2f %9.2f\n", quote.symbol, quote.meanPrice, quote.askPrice, quote.bidPrice )
          }
        }
        else if ( line.startsWith(":c")) {
          repo.clear()
          println("Repository cleared.")
        }
        else if ( line.startsWith(":q")) {
          quit = true
        }
        else {
          if ( line.length() > 0 ) {
            try {
              val quote = findAndUpdateStockQuote(line)
              printf("%s: %7.2f\n", quote.symbol, quote.meanPrice)
            }
            catch {
              case e:ConnectionException =>
                System.err.println("CONNECTION ERROR : "+e.getMessage())

              case e: UnknownStockSymbolException =>
                System.err.println("STOCK SYMBOL NOT FOUND : "+e.getMessage())
            }
          }
        }
      }
    }

    // Prints name and age to the console
    println("Goodbye.")
  }


  def  findAndUpdateStockQuote(symbol: String): StockQuote = {
    val quote = retriever.getStockQuote(symbol)
    repo.store(quote)
    quote
  }

}

object StockQuoteApp {
  val CONNECTION_PROPERTIES_FILENAME: String = "connection.properties"

  def main( args: Array[String] ): Unit = {
    println("Hello world. This is the Scala application!")
    new StockQuoteApp().doInteractive
  }
}

 

It should be fairly self-explanatory that this program is interactive one. It reads a symbol at the command line and invokes the quote retriever to find the stock quote for the symbol.

There is one other improvement to QuoteRetrieverYahooImpl we could make use of. Scala supports function objects; functions calling other functions and returning a different (or the same input) function. Scala methods on class or object types can have more than one parameter list in order to support currying of parameters. Scala language has the feature of partial functions that enable this facility.

Here is a class called TryResource, which closes an InputStream resource.

 

package uk.co.xenonique.stockquoteapp_scala

import java.io.InputStream
import java.io.FileInputStream
import java.io.InputStreamReader
import java.io.BufferedReader
import java.io.IOException
import java.lang.System

// Needs to be generic
class TryResource[T <: InputStream]( inputStream: T ) {

  private val is: T = inputStream

  def execute( body: ( InputStream => Unit ) ): Unit = {
    try {
      body(is)
    }
    finally {
      if ( is != null ) {
        try {
          is.close()
        }
        catch {
          case e:IOException => System.err.println(e)
        }
      }
    }
  }
}

object TryResource {

  def tryResource[T <: InputStream]( inputStream: T )( body: ( InputStream => Unit ) ) {
    val construct = new TryResource( inputStream)
    construct.execute( body )
  }

  def demo1() {
    val construct = new TryResource( new FileInputStream("pom.xml") )
    construct.execute( (is: InputStream ) => {
      val reader = new BufferedReader( new InputStreamReader(is))
      var count = 1
      var line: String = null
      do {
          line = reader.readLine()
          if ( line != null ) {
            printf("demo1 %5d %s\n", count, line)
            count = count + 1
          }
      }
      while ( line != null  )
    } )
    println("==== Done it ====")
  }

  def demo2() {
    tryResource ( new FileInputStream("pom.xml") ) ( ( is: InputStream ) =>  {
      val reader = new BufferedReader( new InputStreamReader(is))
      var count = 1
      var line: String = null
      do {
          line = reader.readLine()
          if ( line != null ) {
            printf("demo2 %5d %s\n", count, line)
            count = count + 1
          }
      }
      while ( line != null  )
    } )
    println("==== Done it ====")
  }

  def main( args: Array[String]): Unit = {
    demo2()
  }
}

 

The method tryResource takes two parameter lists. The first parameter list is a argument list of one, the input stream resource. The second parameter list is also a argument of one, except it is a so-called called-by-name type, by which the function call is delayed, evaluated after inside the method. In other words, we call tryResource()() by passing a block of code that operates on the InputStream and the library function will automatically close the resource for us, regardless of whether block of code completes with normal or abnormal termination. Java 7 now has a similar acquire-release mechanism as a language feature, whereas in Scala, we implemented this a library feature. Scala is scalable language after all.

It would be straight forward now to use tryResource in the QuoteRetrieverYahooImpl directly. This is an exercise for you, the reader. Hint: You should have a good read about Scala’s structured types!

Good Luck!

Scalafication of a Java Equity Quote Application Part 1

July 1st, 2011 1 comment

Here follows in these series of three article is a description of Scala application that ported from Java. I would prefer to call this work a “Scalafication”.

Many people are thinking about Scala Adoption as it gets important interest from the wider community. Did you know that Professor Martin Odersky won the Java Top Ambassador award at the JAX Conference 2011? I think as you might do that Java the programming language is now very mature and that it is getting long in the tooth. However, Java is still very important for open source libraries, because the vast majority of the framework and library landscape, out there, has been very built with Java the programming language. Therefore interoperability is going to be important, and whenever they get around to my favourite [fictional] JSR 555, which will standardise the interoperability between Java and Beyond Java, the holy grail of meta-object protocol, virtual classes, static and dynamic languages and the JVM byte code executor will be a momentous occasion in the history of the Java platform. However, I digress and pat myself down due my excitement.

(Please start your favour MP3 player now on the track: Holst – The Planets – “Jupiter”. You are going need some inspiration.)

Overall Project Summary

The task for this Java project was to retrieve stock quotes from Yahoo Financial Quotes services, store these quotes in a repository, and all prospective users to interrogate the repository for a quotes. If the quote does exist in the repository then the application should go the Yahoo web service and pull down the quote. If it is newer store it in the cache and then return the result to the user.

Project Requirement

The Java application stored the latest quote on a data store (so that, say, a banking risk manager department could compare quotes to some trade that may have been made by the user through some other system). The application displayed the equity stock quote (the average of bid and ask prices) to the user.

The Java application was a prototype. The client envisioned Spring MVC and Hibernate as the web framework solution, which of course meant a relational database. The prototype was a single-user, and build with Apache Maven.

User Stories

For the original Java prototype, there were two user stories:

S1 “A trader wants to see the stock quote for a given ticker symbol so that she can buy and sell the relevant financial instrument at a good market price”.

S1-Acceptance Criteria

A1-1 “Type in a Yahoo ticker symbol and within one second see the current price.  The current price should be approximately equal to that available from a Google search”

A1-2 “Type in an invalid ticker symbol and within one second see an error message”

S2 “A risk analyst wants to view a repository of ticker symbols together with the latest price in each case as last viewed by the stock system’s user so that I can compare these to prices traded by the user on other systems.”

S2-Acceptance Criteria

A2-1 “From an empty data store, use the stock system to view ORCL and then RHT noting their current value.  Then query the data store to ensure those values have been recorded.”

A2-2 “Wait till the Oracle price has changed (a quarter of an hour during NY trading hours 2:30PM to 9:05PM UK time should be sufficient) and then re-query ORCL noting the new price.  Then re-query the data store to ensure that the value had been updated for ORCL and the RHT value is unchanged”.

Original Java Interfaces

In order to port the prototype easy I started the Java interface and the unit tests.

Here is a design-by-contract interface for a quote repository

package uk.co.xenonique.stockquoteapp;

import java.util.List;

/**
 * A contract for a stock quote repository
 * @author Peter
 */
public interface QuoteRepository {

	public boolean isEmpty();
	public int size();
	public void clear();
	public void store( StockQuote quote );
	public StockQuote get( String symbol );
	public boolean contains( String symbol );
	public List<String> getSymbols();
}

Here, with QuoteRepository, the contract is to store and retrieve a stock quote by a symbol. You can check if the repository is empty or not, how many quotes it stores and clear it out. You can enquire also if stock quote is part of the repository by symbols, and finally you can a list collection of stock exchange symbols. By inspection, this interface, looks to be an associative collection, a map type.

Here is an implementation that uses a repository key value storage. Notice that I chose the ConcurrentHashMap to store the key value. Strictly, speaking it could have been a HashMap too, since the prototype was a single-user. Where have you seen a single-user system in existance if ever?

package uk.co.xenonique.stockquoteapp;

import java.util.*;
import java.util.concurrent.*;;

/**
 * A key value store representation of the stock quote repository
 * @author Peter
 */
public class QuoteRepositoryKeyValueStore implements QuoteRepository {

	private Map<String, StockQuote> store = new ConcurrentHashMap<String, StockQuote>();
	
	@Override
	public void clear() {
		store.clear();
	}

	@Override
	public boolean contains(String symbol) {
		return store.containsKey(symbol);
	}

	@Override
	public StockQuote get(String symbol) {
		return store.get(symbol);
	}

	@Override
	public boolean isEmpty() {
		return store.isEmpty();
	}

	@Override
	public int size() {
		return store.size();
	}

	@Override
	public void store(StockQuote quote) {
		store.put(quote.getSymbol(), quote);
	}
	
	@Override
	public List<String> getSymbols() {
		List<String> symbols = new ArrayList<String>();
		symbols.addAll( store.keySet() );
		Collections.sort(symbols);
		return symbols;
	}

}

Here is interface for a quote retriever

package uk.co.xenonique.stockquoteapp;

public interface QuoteRetriever {
	public StockQuote getStockQuote( String symbol );
}

This is a contract to retrieve a stock quote from a system and return it the user.
Here is an implementation of it that talks to the Yahoo web service.

/**
 * 
 */
package uk.co.xenonique.stockquoteapp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.StringTokenizer;

/**
 * Yahoo web site stock retriever
 * @author Peter
 */
public class QuoteRetrieverYahooImpl implements QuoteRetriever {

	public final static String TOKEN_SYMBOL="@SYMBOL@";
//	private final static String URL_FRAGMENT="http://finance.yahoo.com/d/quotes.csv?s=@SYMBOL@&f=sb2b3jk";
	private final static String DEFAULT_URL_FRAGMENT="http://finance.yahoo.com/d/quotes.csv?s="+TOKEN_SYMBOL+"&f=sb2b3";
	
	private String urlFragment = DEFAULT_URL_FRAGMENT; 

	@Override
	public StockQuote getStockQuote(String symbol) {
		String queryUrl = urlFragment.replace(TOKEN_SYMBOL, symbol);
		try {
			URL url = new URL( queryUrl );
			HttpURLConnection connection = (HttpURLConnection)url.openConnection();
			connection.setRequestMethod("GET");
			connection.connect();

			InputStream is = connection.getInputStream();
			BufferedReader reader = new BufferedReader( new InputStreamReader(is) );
			
			try {
				String line = reader.readLine();
				if (  line != null ) {
//					System.out.println("*DEBUG* : line="+line);
					String stockSymbol;
					String askPrice;
					String bidPrice;
					StringTokenizer stk = new StringTokenizer(line, ",");
					int countTokens = stk.countTokens();
					if ( countTokens < 3 ) {
						throw new DataRetrievalException("Data service at URL=["+queryUrl+"] does not supply enough fields (3 != "+countTokens+")");
					}
					stockSymbol = stk.nextToken();
					if ( stockSymbol.length() > 0 &&
							stockSymbol.charAt(0) == '"' && stockSymbol.charAt(stockSymbol.length()-1) == '"') {
						stockSymbol = stockSymbol.substring(1, stockSymbol.length()-1 );
					}
					askPrice = stk.nextToken();
					if ( "N/A".equals(askPrice)) {
						throw new UnknownStockSymbolException("Unknown stock quote symbol ["+stockSymbol+"] price not available");
					}
					bidPrice = stk.nextToken();
					if ( "N/A".equals(bidPrice)) {
						throw new UnknownStockSymbolException("Unknown stock quote symbol ["+stockSymbol+"] price not available");
					}
					
					return new StockQuote(stockSymbol, askPrice, bidPrice);
				}
				else {
					throw new DataRetrievalException("Data unavailable from quote service URL=["+queryUrl+"]");
				}
			} 
			finally  {
				if ( reader != null) {
					try {
						reader.close();
					} catch (Exception e) {
					}
				}
				if ( is != null) {
					try {
						is.close();
					} catch (Exception e) {
					}
				}
			}
		} 
		catch (MalformedURLException e) {
			throw new ConnectionException("unable to connect to the remote quote service URL=["+queryUrl+"]", e);
		}
		catch (IOException e) {
			throw new ConnectionException("I/O failure reading service URL=["+queryUrl+"]", e);
		}
	}

	public String getUrlFragment() {
		return urlFragment;
	}

	public void setUrlFragment(String urlFragment) {
		this.urlFragment = urlFragment;
	}
}

This is all very straight forward Java Networking that you all should know and love by now.

Here is the equity stock quote data class

package uk.co.xenonique.stockquoteapp;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class StockQuote {
	private final String symbol;
	private final BigDecimal askPrice;
	private final BigDecimal bidPrice;
	private final BigDecimal meanPrice;

	private final static BigDecimal TWO= new BigDecimal("2.0");
	
	public StockQuote(String symbol, String askPrice, String bidPrice) {
		this( symbol, new BigDecimal(askPrice), new BigDecimal(bidPrice));
	}

	public StockQuote(String symbol, BigDecimal askPrice, BigDecimal bidPrice) {
		this.symbol = symbol;
		this.askPrice = askPrice.setScale(2);
		this.bidPrice = bidPrice.setScale(2);
		this.meanPrice = calcMeanPrice(askPrice, bidPrice);
	}

	/**
	 * Copy constructor 
	 * @param ref the reference
	 */
	public StockQuote(StockQuote ref) {
		this.symbol = ref.symbol;
		this.askPrice = ref.askPrice.setScale(2);
		this.bidPrice = ref.bidPrice.setScale(2);
		this.meanPrice = bidPrice.add( askPrice.subtract(bidPrice).divide( TWO ) );
	}

	private BigDecimal calcMeanPrice(BigDecimal askPrice, BigDecimal bidPrice) {
		return bidPrice.add( askPrice.subtract(bidPrice).divide( TWO ) ).setScale(2, RoundingMode.DOWN );
	}

	public String getSymbol() {
		return symbol;
	}

	public BigDecimal getAskPrice() {
		return askPrice;
	}

	public BigDecimal getBidPrice() {
		return bidPrice;
	}
	
	public BigDecimal getMeanPrice() {
		return meanPrice;
	}
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((askPrice == null) ? 0 : askPrice.hashCode());
		result = prime * result
				+ ((bidPrice == null) ? 0 : bidPrice.hashCode());
		result = prime * result + ((symbol == null) ? 0 : symbol.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		StockQuote other = (StockQuote) obj;
		if (askPrice == null) {
			if (other.askPrice != null)
				return false;
		} else if (!askPrice.equals(other.askPrice))
			return false;
		if (bidPrice == null) {
			if (other.bidPrice != null)
				return false;
		} else if (!bidPrice.equals(other.bidPrice))
			return false;
		if (symbol == null) {
			if (other.symbol != null)
				return false;
		} else if (!symbol.equals(other.symbol))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "StockQuote [ symbol=" + symbol +", askPrice=" + askPrice + 
		", bidPrice=" + bidPrice + ", meanPrice="+meanPrice+"]";
	}
}

I need you to notice that it is an immutable object class. It is a stock quote that aggregates the symbol, ask and bid prices together. It borrows from C++ with a copy constructor, it has the hashCode() and equals() and a toString().

Finally, lets look at a unit test that ties it all together

package uk.co.xenonique.stockquoteapp;

import org.junit.*;
import static org.junit.Assert.*;

public class QuoteRetrieverYahooTest 
{
    @BeforeClass 
    public static void loadProxySettings()
    {
        StockQuoteApp.applyConnectionPropertiesFile();
    }

    @Test
    public void shouldRetrieveStockQuote()
    {
        QuoteRetriever retriever = new QuoteRetrieverYahooImpl();
        StockQuote quote = retriever.getStockQuote("ORCL");
        assertNotNull(quote);
        assertEquals("ORCL", quote.getSymbol());
        assertNotNull( quote.getAskPrice());
        assertNotNull( quote.getBidPrice());
        assertNotNull( quote.getMeanPrice());		
    }

    @Test(expected=UnknownStockSymbolException.class)
    public void shouldRaiseErrorWithUnknownStockSymbol()
    {
        QuoteRetriever retriever = new QuoteRetrieverYahooImpl();
        retriever.getStockQuote("UNKNOWN");
    }

    @Test(expected=ConnectionException.class)
    public void shouldRaiseConnectionFailure()
    {
            QuoteRetrieverYahooImpl retriever = new QuoteRetrieverYahooImpl();
        retriever.setUrlFragment("http://foo.finance.yahoo.com/"+QuoteRetrieverYahooImpl.TOKEN_SYMBOL);
        retriever.getStockQuote("MFST");
    }
}

There is another unit test to verify the operation of the key value repository.

package uk.co.xenonique.stockquoteapp;

import java.util.List;

import org.junit.*;
import static org.junit.Assert.*;

public class QuoteRepositoryKeyValueTest {
	
	@Test
	public void shouldInitialiseWell() {
		QuoteRepository store = new QuoteRepositoryKeyValueStore();
		assertTrue(store.isEmpty());
		assertEquals(0,store.size());
	}

	@Test
	public void shouldStoreAndRetrieve() {
		QuoteRepository store = new QuoteRepositoryKeyValueStore();
		StockQuote expected1 = new StockQuote("PILGRIM", "123.45", "123.12" );
		// Exercise the copy constructor in order to verify the store is not just using object references!
		store.store(new StockQuote(expected1));
		assertFalse(store.isEmpty());
		assertEquals(1,store.size());
		
		assertEquals( expected1, store.get("PILGRIM"));
		// Put an updated stock quote in the repository with same symbol for good measure
		StockQuote expected2 = new StockQuote("PILGRIM", "555.55", "555.12" );
		store.store(expected2);		
		assertFalse(store.isEmpty());
		assertEquals(1,store.size());
		
		// The quote inside the store is not equal to the old stock quote 
		assertNotSame( expected1, store.get("PILGRIM"));
		// The quote inside the store is equal to the new stock quote 
		assertEquals( expected2, store.get("PILGRIM"));
	}
	
	@Test
	public void shouldStoreAndRetrieveMultipleQuotes() {
		QuoteRepository store = new QuoteRepositoryKeyValueStore();
		assertTrue(store.isEmpty());
		assertEquals(0,store.size());
		
		StockQuote quotes[] = new StockQuote[] {
				new StockQuote( "LYG", "4.020", "4.015" ),
				new StockQuote( "RBS.L", "39.58", "39.48" ),
				new StockQuote( "HSBC.L", "646.65", "646.62" ),
				new StockQuote( "ORCL", "27.75", "27.74" ),
		};
		
		for (StockQuote quote: quotes) {
			store.store(quote);
		}
		
		assertEquals( quotes.length, store.size());
		assertFalse(store.isEmpty());

		for (StockQuote quote: quotes) {
			assertTrue( store.contains(quote.getSymbol()));
			assertEquals( quote, store.get(quote.getSymbol()));
		}
		
		List<String> symbols = store.getSymbols();
		assertEquals( quotes.length, symbols.size());
		for (StockQuote quote: quotes) {
			assertTrue( symbols.contains(quote.getSymbol()));
		}
		
		store.clear();		
		assertTrue(store.isEmpty());
		assertEquals(0,store.size());		
	}
}

These were the essential parts of the Stock Quote application written in Java. I have left some notable bits and bobs, such the exceptions, and also the main program. You can treat it as an exercise-for-the-reader to tie it all together. I will publish the Java main program later on.

The static method call StockQuoteApp.applyConnectionPropertiesFile() is a method, that initialised the Java system properties with a configuration that allowed the application to work behind a company Internet proxy. The properties file looks like this:

# File: ``Connection.properties''
# ==========================================
# Uncomment and set the proxy gateway for your environment
#
# Uncomment this line to use a Internet Proxy
http.proxySet=true
# Define the proxy hostmachine e.g. gateway.declan.server1
http.proxyHost=webcacge.proxyhost.mydomain.com
# Define the port number of the proxy e.g. 8080
http.proxyPort=8080
# Define the login name 
http.proxyUser=PILG1472
# Define the password
http.proxyPassword=PILGPASS
# Define the non proxy hosts
http.nonProxyHosts=otcdev57,otcdev1287,otcdev1244
# End

Next time. I will describe how I Scalafied these classes.

Scala Adoption Seems To Be Going Well

June 23rd, 2011 4 comments

 

So I was at the Scala Exchange at Skills Matter last week. It was a really great mini-conference that happened in the middle of personal awkward time, a somewhat busy and confusing place in my space-time, my corner of the universe. Thanks for the invitation by Skills Matter as London’s only Java Champion, one of seven in the entire United Kingdom and Northern Ireland territory, I was there for the full two days.

Martin Odersksy opened the conference with a key note. He was just in on route from the Scala Days conference in Stanford University. California. Professor Odersky presented and talked about the new changes in Scala 2.9, especially in the parallel collections and the new Dynamic trait and of course the DelayedInit trait. He talked in depth about the parallel collection methods, the new abilities of the REPL, which allow users to use Bash Control-R syntax to search through the command history. Odersky also explained about the Scala executor. For instance you type “scala –jar my.jar” and your main program in Scala will be run, which behaves just like java. He discussed the formation of TypeSafe and the challenges in the concurrency fields, where EPFL received a multi-million dollar grant from Microsoft and the joint-research with Stanford into Scala DSL for popular parallel computing.

A lot of these points in the key note were way over the heads of most of us in the audience, however it was interesting to see that there is progressive research and targeted use of Scala in to hardest of all computing problems: how software can efficiently utilise the on-going exponential growth of microprocessor cores from now and into the future.

There were other luminaries, some very good speakers like James Strachan, who actually asked the audience, who at this time, right now, right here, actually develop Scala programs professionally? I observed rough 50% of the audience raise their hands. The Scala Exchange was sold out to about 120 audience members. So this was uplifting to witness this result. How good or how proficient the audience, which were Scala professional users  is another question. James Strachan gave an excellent talk on Scalate and the templating frameworks around Scala. It was well worth a look.

My time was limited and still is. I would like to make a shout-out to Renato of the Belgium Java User Group. (Hopefully with my present situation behind me, I will be able to make to Devoxx later this year, I mean, I would love to visit Antwerp again)

 

DSCF2630

Martin Odersky

 

DSCF2640

Martin Odersky

 

DSCF2645

Jason Zaugg

 

DSCF2671

James Strachan

 

 

Thanks All

Scala Adoption: Learn A New Language People!

June 1st, 2011 Comments off

Yay! The Scala Adoption (Episode 353) session from JavaPosse Round Up 2011 has been released. You can listen to the JavaPosse podcast episodes online at The Lounge or try this German website directly Podcast.de.

The session was proposed by Diane Marsh and myself.  There is not much more I can say to add to the session on Scala adoption except for that in I can report in London in recent days. I hear of some of investment banks are showing a passing interest in the language. Utlimately they want a better solution to concurrency and  Unfortunately, this progress is far little and too late for me in my current situation. It would appear that in many institutions the guerrilla style, that of grass roots evolution or revolution, which many Groovy developer successfully chose to get Groovy adopted several years ago, is not happening the same way with Scala. The decision makers and management are yet to be convinced that Scala is the next programming language forward to take the Java platform. It may be that I, admittedly, am not moving in the right cliqué or that this esoteric information is not flowing outside the institutions themselves.

Regardless of whether banking will or will not adopt Scala is irrelevant. It is frankly true that some form of functional literate programming is going to come down the wire and in the very near future. It is not a question of “if” but of “when”. As Diane Marsh eloquently expressed her frustration at the very beginning of the session in Crested Butte, Colorado

Java is an old language. It’s been changed over the years, but seriously this has been really long time for a language to be dominant and kind of tongue and cheek. I will say like to say, “Man Up! Learn a new language people!” It is not that hard to learn a new language and we all should be doing it anyway. It’s good for our brains to actually think in different ways. It doesn’t have be just like Java, and there are reasons why it shouldn’t be.  If it were to be Java, we should just stick with Java. I’am kind of exhausted about the argument that it is just too difficult.”

 

Born this way.

Listen!

A Week In Scala: ACCU 2011

April 14th, 2011 2 comments

It is Wednesday 13th April 2011 and I am here at the ACCU 2011 Conference again in Oxford, England. It is great to back. The last time I was in Oxford for ACCU 2008, I gave a talk on JavaFX 1.1. This morning, I presented An Introduction to Scala: The Object Functional Programming Language. The responses have been very good so far:

@devpg: Listing to ‘Introduction to Scala’ at #accu2011 reminds me to use it in a project

@rachelcdavies: @peter_pilgrim enjoyed your talk. I’m new to Scala and this was just right for me. #accu2011

@TimPizey: Installing Scala after lightening introduction by Peter Pilgrim at #ACCU2011

@matty_jwilliam: @peter_pilgrim great talk today. Tonight has been all scala (and beer) #accu2011

@gasproni: @matty_jwilliams: @peter_pilgrim great talk today. Tonight has been all scala (and beer) #accu2011

@TimPizey: Day 1: java > 1.4 is a mess and is going to get worse, move to Scala or other JVM language as soon as you can. #ACCU2011

@russel_winder: All the JDK8 stuff is already in Groovy and Scala. #accu2011 #groovy

@ewan_milne: #accu2011 Intro to Scala – here’s the Fibonacci algorithm!

@lisacrispin: RT @peter_pilgrim As promised My latest SlideShare upload : #ACCU2011 Introduction to Scala: An Object Functional Lang… http://slidesha.re/hufsPG

The attendance was fairly good. There was no pressure then: Rachel Davies (agile coach), Kevlin Henney (consultant and top speaker) and Ewan Milne (ACCU Chair) were in attendance. The competition was Scott Meyers (C++0×10) and Jutta Eckstein (Agile software development). My Scala talk did not do too badly with this quality of simultaneously talks and their respective speakers.

I was pleased with the face-to-face feedback as well. Kevlin Henney was impressed by the description of the Scala type reference engine. Ewan liked it too. Delegates Michael from England and Khalid from Pakistan/Norway enjoyed the overall presentation for being just enough technical detail to be inspired to try Scala.

Here is my entire slide deck as promised on Slide Share:

You can download my PDF slides directly from XeNoNiQUe. I attempted to share with SlideShare web site however the conversion process they used washed all the nice beautiful colours on my slide deck. Boo!

Enjoy Winking smile

(I welcome feedback of any sort. If you want this talk for your business, especially in London then hook me up)

This is My Week of Scala. You get out of the task exactly the proportion of result that you put into the plan. Next episode I will have more aggressive discussion on Beyond Java and stab at the history of how we got here.

Listen!

Post addendum 1

Dinner was great. I joined fellow ACCU 2011 speakers, Schalk Cronje, Steven “Doc” List and Lisa Crispin for a short stroll to the nearby Plough pub, which is about 10 minutes walk from the Barcelo Hotel. The ACCU brings a different crowd. I was the first time I met Steven “The Doc” and Lisa. Steven ( Thoughtworks) had this great idea for Source Mastery Quest for gaining true experience and skills through crowd sourcing and peer recommendation and certification. Lisa talked about her experience in software development in Austin, Texas in the early 1980’s where everybody wrote the same code in the exactly the same style. Being an Agile tester she reminisced the old way was what we should be doing now in software development.  Shalke (McAfee) I had met before at ACCU 2008 and other conferences, he tends not to do so much C++ development now these days. I think it is great to networking with new people, swap business cards and share ideas. The best ideas are those sometimes we have in those corridor moments, or conversation over a beer or glass of wine.

Post addendum 2

I managed not to sleep again. Woke up at 2:30AM because my iPhone buzzed. Oh yes. I had put in to a schedule “Richard Bair at the Silicon Valley JavaFX User Group”.  Eight hours behind in time zone. I did watch the UStream.TV feed of the talk. JavaFX 2.0 is coming along nicely, the binding API worked very well. I can see this was true through the live coding demonstration on Richard’s MacBook Pro, and I have a good feeling about the new JavaFX Bean property models. The layout API is where action is needed next, because in the early access I have found it less understandable in comparison to the JavaFX Script 1.x releases. I am quite sure the FX SDK team are working hard on it as I type. Shout out to Stephen Chin and Jonathan Giles.

ACCU 2011 Introduction to Scala Talk

March 28th, 2011 Comments off

Hey All

I will giving a presentation at ACCU 2011 Conference in Oxford on 13th April: Introduction to Scala. The conference takes place in Oxford at the Barceló Hotel on the outskirts of the town. Registration is still open last time I check, so if you want to go then do it now.

I examined the full schedule and I see my talk is first one on Wednesday morning at 11am in Cherwell.

I plan to give a fair robust overview of programming in Scala. It will cover Beyond Java the landscape that we all face, some the ideas on the adoption, where the JVM platform is going. It will be technical and the syntax and concepts of Scala will definitely covered. There will be guide to the functional side of the Scala. Above all I will be stressing the Yoda line: “with great powers, comes great responsibility”.

The ACCU has a long history with C/C++ in the past and the over decades this has been distilled with object orientation, agile development, patterns, and generally best practice for programmers. I was originally a member of ACCU for its C/C++ years and years ago. I moved on as we all do. I moved to Java in 1998 and left C++ behind.

It is good to represent the Java platform again in Oxford and I am looking forward to it.

PS: James Gosling has joined Google: Bang Goes The Drum!

Deeply Worried Q1 – Q2

March 16th, 2011 2 comments

I have just had massive blow out. I seem to be fighting and arguing all the time now with close people near me. I feel ratty even talking to acquaintances. A turning point has been reach, and I honestly do not what on earth to do next about it.

It would appear that investment banks are extremely confused on what their long strategy is to do with Java and even Beyond Java:

  1. The sheer unpredictably of interviewer requirements, unpredictably of technical, social, team make up, and process whether it is agile or non-agile
  2. All interviewers are different because all client are different; this is understood and they all have different personalities; however common rapport is increasingly hard to achieve in the mix there
  3. Difficulty of getting to the conclusion of a potential engagement; the perfect match is proving harder to achieve 
  4. Lack of foresight in clients in that they really want. It seems that they only interested ever in a fix for the pain right here right now – they are unwilling to look at changing the application architecture; infrastructure; underlying algorithms behind the scene
  5. Expect wizards to turn up and perform a spell of magic – and clear all ills. We still do not if there is a special technical skill that is out there (a silver bullet) if there is such a thing.
  6. The state of the job market software engineering in financial services / investment bank in City of London is unknown. Is it good or bad? Everyone seems to have a conflicting view.

With case (5) I could have said several years ago. “Ah! The missing skillset of knowledge is Java Servlets or Struts or JSF or EJB or even Spring Framework”, then I could have done something about it. In 2011 the answer is “Well, Hellfire, save matches, fuck a duck and see what hatches!” and my own little addendum to Steven Tyler’s [American Idol Judge] surprised vocal curse-rhyme is, “Hail Jesus and Mary! Spread your legs, buttocks and latches. Give me good sex, herpes and whatever catches”. In other words if there is a magic inspired Java technology X that one needs to get an engagement in 2011, then it is news to me.

The deep worry of (5) is, I believe that it is further evidence of Java ecosystem fragmentation and disparate wealth and spread of technologies. On the one hand I would be over joyed if the clients now let start looking Beyond Java on the JVM, but they are unanimously sticking with Java the programming language, sticking purely to it, becoming the late majority and progressing to a laggard category.

These dogs [bitches] are holding back the innovation and early adopter categories (including me, myself and I; and also add you, yourself and you). We know that the backward compatibility guarantees is the constraint on the Java programming language. You and I can see that this rubber band stretching between laggards and early adopters has to break at some time soon as the client themselves are demand more of the applications that run on the Java software platform. We can no longer be held to ransom for application strongly tied up to legacy WebSphere application server 4/5, WebLogic Server 8 or steadfast only runs on a JDK 1.4.2. The clients must know that they have to upgrade their application, give up these legacy environments, reinvest for future ROI, refactor for sustainable architecture, in order to ultimately be competitive in their technology model, which is by now proportional to the performance their business model.

In case (4) I see a lot of job specifications for things like Java performance and multiple thread programing / concurrency expertise.

The candidate must have extensive Java knowledge and must be experienced in writing streamlined (memory and CPU efficient) code. Additionally, they must have a very good understanding of Java multi-threading and Java performance tuning.

This suggests to my mind, client are facing a lot of issues about pain now, fire-fighting and fixing the problem short-term. It just does not suggest fixing performance in a long-term strategic way through innovation and changing the architecture or searching for a better algorithm or collapsing layers appears to be non-thought here. Not up for discussing. Nada.

It seem all to soon to be like a Hollywood action movie scene: Just load the fucker and fix it so the actor can keeping shooting bullets from my rifle, whilst not thinking of day when rifles are replaced with ray-guns. (One can therefore forget talking to prospective client about Scala adoption or looking at radically different solution á la Clojure)

With case (2) this is human interaction sociological issue, the quality of interviewers seems to less than desirable IMHO. If the other side of the fence has different fixed ideas about software development rather you appear to do, then we are sunk in a face-to-face. And low and below if the organisation has dysfunctional view of Agility, then the wheels will come off …

With case (5) asking the candidate or the contract for wider flexibility suggest that the client has a lack of clarity in the first place. It is this idea of, in a British way, or wanting to dot the I-s and crossed the T-s, ticking all the boxes from A to K, in order to get SIGN OFF from the manager’s manager that is a deeply flawed and ultimately troubling. Yes one can say the job market behaves in the Keynesian model of economy, it is a seller’s markets now, but who the fuck is a ultimate master of Java, C# and C++, Perl, Python, Swing, Spring Framework, ASP, Hibernate, Core Java, JPA,Scripting Languages, Web and programming language and framework simultaneously and not already working for the software deity G.0.D? I would like to know who these mythical people are and meet them today; and I suspect so would you.

With case (6) it is hard to get the real truth of the information of engagements these days, when one is involved fighting in a war. The war is the talent search game and recruitment of good programmers. The amount of misinformation is as dangerous as finding right information. The trouble is discerning if your information is valid and good, the signal-to-noise ratio is not good today.

I am deeply worried about the future prospects. Currently my own money and budget have limits, but there are not infinite. I can postulate, blog and express my enthusiast about a Beyond Java (on the JVM platform) universe as much as humanly possible, I can talk a good game (á la Paul Gascoigne) on Java technology and the platform, as I have done it before. I am human and have limits though, and I am beginning wonder genuinely what those are at the moment …

My tech lead rant is over … Stupid, silly and uninspired … unsure what value there is there … software pride weak … we don’t reach … we don’t join arms … ah we as software developers take it up the ass as per usual …

Categories: alternative, banks, beyond, future, Java, jvm, language, London Tags:

Moving Beyond Java on the JVM: To Be Or Not To Be

December 21st, 2010 Comments off

Recently, I have been thinking about Java and Moving Beyond Java. I ruminated aloud in a couple of Audioboos and so here are a summarised listable version of these thoughts and ideas.

Java

  • The Mother Language – Lingua franca of the Java Virtual Machine platform
  • Java SE 7
  • Java SE 8
  • Work related. Programming language is risk-averse, it changes slowly and carefully. Oracle steward ensure that it is safe. Business owners and web site owners will be able hire or contract.
  • A de-facto programming language for new learners, students of computer science
  • Die-hard stalwarts can stick with Java the programming language, because eventually some of the benefits of the other languages could make it into Java ecosystem as frameworks and libraries
  • Performance-related Java programming: There is a native-like programming approach for writing Java applications like they do C++ / Speed performance

Beyond Java on the JVM

  • Neil Ford, Ted Newark and Myself are examples of external luminaries (the forces) that are telling you why you should be thinking about moving beyond Java
  • Continued learning
  • Reduction of Boilerplate (Almost all)
  • Declarative programming (JavaFX Script)
  • Ease-of-Development
  • Dynamic typing (Groovy)
  • Scripting language approach
  • Closures (Almost all)
  • Control abstractions (Scala)
  • Improved concurrency models parallel algorithms, actor, CSP and software transactional memory
  • Better simple abstract data types (case classes and objects in Scala)
  • Better language support for immutable object (@Immutable in Groovy)
  • Better annotations (Groovy has loads)
  • Some languages support an object functional approach (Scala, Groovy, Fantom)
  • Other object functional languages may support Higher order functions (Scala, Clojure)

General behaviour, psychology within the movement of herds "staying up to date and getting good".The decision is yours in 2011