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 "http://repo.spring.io/libs-release" }
        mavenLocal()
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.1.8.RELEASE")
    }
}

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 {
    mavenLocal()
    mavenCentral()
    maven { url "http://repo.spring.io/libs-release" }
}



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

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    testCompile("junit:junit")
}

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.

Procfile

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

resthub
RestHUB

jhipster
JHipster

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;
import java.util.stream.IntStream;

public class WordCount {
	
	public int x = 26;

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

	private void count() {

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

		System.out.println(s);
		

        final Map<Character, Integer> count = s.chars().
        		map(Character::toLowerCase).
                collect(TreeMap::new, (m, c) -> m.merge((char) c, 1, Integer::sum), Map::putAll);
        
             
        count.entrySet().stream().
        	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.	
	}
}
mainn
a-1
i-1
m-1
n-2
{a=25, i=24, m=23, n=52}
124.0

Streams

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 http://www.cs.uofs.edu/~mccloske/courses/cmps144/invariants_lec.html 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 {
                swap(flags,k,m); 
                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.

package com.game.test;

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;

import com.game.conway.Cell;

@RunWith(JMock.class)

public class Game {

    Mockery context = new JUnit4Mockery();
    
    @SuppressWarnings("deprecation")
	@Test 
    public void mocksurvive() {
        // set up
    	context = new Mockery() {  
    		  {  
    		    setImposteriser(ClassImposteriser.INSTANCE);  
    		  }  
    		};
    	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() {
             {
                 oneOf(cell).setX(1);
                 oneOf(cell).setY(1);
                 oneOf(cell).survive(cells);
                 will(returnValue(false));
             }
         });
    	cell.setX(1);
    	cell.setY(1);
         final boolean result = cell.survive(cells);

    }
}


package com.game.conway;

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 cells.stream().filter( c -> neighbour(c)).count();
	}

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


	@Override
	public int compareTo(Cell o) {
		if( x == o.x && y == o.y)
			return 0;
		else
			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 java.lang.management.GarbageCollectorMXBean‘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() {
		
		connectJMXRemote(9010);
 	
			List<GCType> pools =
					ManagementFactory.getGarbageCollectorMXBeans().stream().map(p-> new GCType(p.getName(),
							                                                                   p.getCollectionCount(),
							                                                                   p.getCollectionTime()))
					.collect(Collectors.toCollection(() -> new ArrayList<GCType>()));
			pools.stream().forEach(p-> 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 =
			   memoryBeans
			    .stream()
			    .filter(p ->
			        {
			       	l.debug(p.getName());
			        return p.getName().equals(METASPACE);
			        })
			        .findFirst();

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")
  .jcall(realtimeyoungdataobserver,"V","consume")
  occupancy <- .jcall(realtimeyoungdataobserver ,"Lcom/rxjava/jmx/YoungGenOccupancy;","getOccupancy")
  used <- occupancy$getUsed()
  max <- occupancy$getMax()
  print(paste("User[", used,"] Max [", max,"]"))
  result <- c(used, max) 
  return(result) 
}

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.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.AbstractQueue;
import java.util.concurrent.ArrayBlockingQueue;

import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

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) {
	  		l.debug(getStackTrace(e));
	  	}

	}
	
	default String getTrace(Throwable t){
		return getStackTrace(t);
	}
	
    static String getStackTrace(Throwable t){
    	StringWriter sw = new StringWriter();
    	PrintWriter pw = new PrintWriter(sw);
    	t.printStackTrace(pw);
    	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