Deployment on Heroku


Screen Shot 2014-12-05 at 12.50.10 PM I recently pushed my AngularJS/Spring Boot/Rest application to Heroku.

buildscript {
    repositories {
        maven { url "" }
    dependencies {

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'
mainClassName = "rest.controller.Application"

jar {
    baseName = 'Angular-Boot-Rest'
    version =  '0.1.0'

repositories {
    maven { url "" }

tasks.withType(Copy) {
        eachFile { println it.file }

dependencies {

task wrapper(type: Wrapper) {
    gradleVersion = '1.11'
task stage(dependsOn: ["build"]){}

I added a new task stage and mainClassName.

It allots a free port on which Tomcat binds. If one specified one’s own port then the application does not bind to it within 60 seconds which is the time limit allowed.

Heroku needs this file too.


web: java $JAVA_OPTS -jar target/Angular-Boot-Rest.jar

This is the screenshot. Note the URL which is allotted too.

Screen Shot 2014-12-05 at 1.02.05 PM

Web application stack



I really need to keep up with these new stacks.

Python vs Java Streams and lambda

I ported the first facebook Qualification Round Solution to Java 8.

The main idea is to count the frequency of each letter, then assign the value 26 to the most frequent letter, 25 to the next, etc. If two letters are tied for most frequent, it doesn’t matter which of them gets which value, since the sum will be the same. The python code below explains the solution pretty well.

I haven’t thoroughly checked for bugs but this is almost as beautiful as Python. Java is more verbose though.
I haven’t tested it thoroughly though.

import java.util.Map;
import java.util.TreeMap;

public class WordCount {
	public int x = 26;

	public static void main(String... argv){
		WordCount wc = new WordCount();

	private void count() {

		String s  = "__mainn__".replaceAll("[^a-z\\s]", "");


        final Map<Character, Integer> count = s.chars().
                collect(TreeMap::new, (m, c) -> m.merge((char) c, 1, Integer::sum), Map::putAll);
        	sorted((l, r) -> r.getValue().compareTo(l.getValue())).
        		forEach(e -> count.merge(e.getKey(), x--, Math::multiplyExact));
                //Stop when x == 0.Not tested
        System.out.println(count.entrySet().stream().mapToDouble(e -> e.getValue()).sum());
	//Treating these numbers as double to sum them. Doesn't seem to matter.	
{a=25, i=24, m=23, n=52}


I tried to use lambdas to swap elements in the char[] array. Does this mean that I am trying to change the stream while it is streaming ? This code is from but this question is unrelated to those concepts.

If that is a problem then a new stream will do. How should this be done ? I am not looking for a Comparator. I would like to work with this code as it is without using any API but lambdas.

I am printing using lambdas in this code now.

public class DutchNationalFlag {

    private static final int N = 10;

    private static char[] flags = new char[]{'R','B','B','R','R','B','B','R','R','B'};

    public static void main( String... argv){

        new String(flags).chars().mapToObj(i -> (char)i).forEach(System.out::println);

        int m = 0,  k = 0;
        while (m != N)  {
            if (flags[m] == 'B') { }
            else {
                k = k+1;
            m = m+1;
        new String(flags).chars().mapToObj(i -> (char)i).forEach(System.out::println);

    private static void swap(char[] flags, int k, int m) {

        char temp = flags[k];
        flags[k] = flags[m];
        flags[m] =  temp;



Possible Solution 1:

This doesn’t do exactly what the original code does. It doesn’t swap and doesn’t advance k which is the boundary between ‘B’ and ‘R’.But it produces the result.

    Stream<Character> stream1 = 
    IntStream.range(0, flags.length).mapToObj(i -> (char)flags[i]);

    Stream<Character> stream2 = 
    IntStream.range(0, flags.length).mapToObj(i -> (char)flags[i]);

    Stream.concat(stream2.filter(x-> (x == 'B')), stream1.filter( y->(y == 'R')  )).forEach(System.out::println);

Conway’s Game of Life

This is just a simple demonstration of lambdas to implement the Cell but the code may not be complete.


import java.util.ArrayList;
import java.util.List;

import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.runner.RunWith;



public class Game {

    Mockery context = new JUnit4Mockery();
    public void mocksurvive() {
        // set up
    	context = new Mockery() {  
    	Cell cell = context.mock(Cell.class);
    	final List<Cell> cells = new ArrayList<Cell>();
		cells.add(new Cell(1,1));
		cells.add(new Cell(8,2));
		cells.add(new Cell(2,2));

        // expectations
        context.checking(new Expectations() {
         final boolean result = cell.survive(cells);



import java.util.List;

public class Cell implements Comparable<Cell>{
	public Cell(int x, int y) {
		this.x = x;
		this.y = y;

	int x,y;

	public Object getX() {
		return x;

	public Object getY() {
		return y;

	public boolean neighbour(Cell neighbour) {
		return Math.abs(x - neighbour.x) <= 1 && 
			   Math.abs(y - neighbour.y) <= 1 &&
			   !(this.compareTo(neighbour) == 0);

	public long countNeighbours(List<Cell> cells) {
		return c -> neighbour(c)).count();

	public boolean survive(List<Cell> cells) {
		long count = countNeighbours(cells);
		if( c -> (this.compareTo(c) == 0) )){
			return count == 2 || count == 3;
		return count == 3;

	public int compareTo(Cell o) {
		if( x == o.x && y == o.y)
			return 0;
			return -1;

Succinctness of Lambdas

I think this is impressive. Compare it with the earlier way of iterating over the data. I am streaming a list of‘s, accessing some data from each and creating an ArrayList of GCType objects in one line of code.

public class GarbageCollectionProbe implements Probe{
	Logger l = Logger.getLogger("collection.gc");

	public  List<GCType> getMemoryPool() {
			List<GCType> pools =
					ManagementFactory.getGarbageCollectorMXBeans().stream().map(p-> new GCType(p.getName(),
					.collect(Collectors.toCollection(() -> new ArrayList<GCType>()));> l.debug(p));
			return pools;


Optional and Lambda

This is a piece of code that I converted using Lambdas. It is using JMX but that is irrevelant.

I wanted to use this method initially. This is the JDK source.

     * Returns an {@code Optional} describing the specified value, if non-null,
     * otherwise returns an empty {@code Optional}.
     * @param <T> the class of the value
     * @param value the possibly-null value to describe
     * @return an {@code Optional} with a present value if the specified value
     * is non-null, otherwise an empty {@code Optional}
    public static <T> Optional<T> ofNullable(T value) {
        return value == null ? empty() : of(value);

But once I used Lambda code I realized the API returns Optional<MemoryPoolMXBean>

	   Optional<MemoryPoolMXBean> mpx = Optional.empty();

//			   for (MemoryPoolMXBean pool : memoryBeans) {
//		       		l.debug(pool.getName());
//		               if (pool.getName().equals(METASPACE)) {
//		            	   mpx =  Optional.ofNullable(pool);
//		               }
//		       }
			   mpx =
			    .filter(p ->
			        return p.getName().equals(METASPACE);

I don’t want to delve too deep into this as it doesn’t break the code that calls this.

Display JVM heap details using rJava and R

I finished the first full flow that pulls data from the JVM using JMX and dynamically updates a graph in a browser. I use rJava as the layer between R and Java. I code many lines of java, of course, using jdk 8.

realtimeyoungdata <- function(){
  realtimeyoungdataobserver <- .jnew("com/rxjava/jmx/YoungGenPeriodicObserver")
  occupancy <- .jcall(realtimeyoungdataobserver ,"Lcom/rxjava/jmx/YoungGenOccupancy;","getOccupancy")
  used <- occupancy$getUsed()
  max <- occupancy$getMax()
  print(paste("User[", used,"] Max [", max,"]"))
  result <- c(used, max) 

Interface default methods

I am coding feverishly to complete a web interface to the JVM internals like memory, threads etc. This is my first set of default methods in an interface.

I have not read the JLS comparison between this and other inheritance mechanisms but this serves a purpose.

package com.memory.probe;

import java.util.AbstractQueue;
import java.util.concurrent.ArrayBlockingQueue;


import org.apache.log4j.Logger;

public interface Probe {
	Logger l = Logger.getLogger("generation.gc");
	AbstractQueue<Long> abq = new ArrayBlockingQueue<Long>(100);

	default void connectJMXRemote(int port){
	      JMXServiceURL url;
	  	try {
	  		url = new JMXServiceURL(
	  		            "service:jmx:rmi:///jndi/rmi://localhost:" + port + "/jmxrmi");
	  		JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
	  		l.debug("Remote JMX connection is successful");
	  	} catch (IOException e) {

	default String getTrace(Throwable t){
		return getStackTrace(t);
    static String getStackTrace(Throwable t){
    	StringWriter sw = new StringWriter();
    	PrintWriter pw = new PrintWriter(sw);
    	return sw.toString();


Real-time graph showing heap generations

I am able to dynamically update a graph in real-time with test data using the code shown in the previous post. The graph is refreshed without refreshing the entire browser. Even though the particular JavaScript graph library will be replaced with another better one, at this time the tests are successful.
Now I will be able to use JMX to get the YoungGen data from the heap and show actual data as the GC collects the garbage.

All the code will be pushed to Github.

Screen Shot 2014-06-23 at 11.10.36 AM