Friday, May 18, 2012

Performance test of find cell


public void testFindCell_ICell() throws OutOfBoundsException {
       System.out.println("findCell");
        int testSize = 1000000;
        UniqueRandomNumber urn = new UniqueRandomNumber(testSize);
       
        ArrayListCellColl instance = new ArrayListCellColl();
        AliveCell ac;
     
     
     
        while (urn.hasNext()){
             ac = new AliveCell();
            int x = urn.getNext();
           
            ac.setX(x);
            ac.setY(x);
            instance.addCell(ac);
        }
         TimerClass timer = new TimerClass();
          timer.startTimer();
          int counter = 0;
          for (int i = 0; i<testSize;i++){
              Random gen = new Random();
              int z = gen.nextInt(testSize*2);
               ac = new AliveCell();
               ac.setX(z);
            ac.setY(z);
            if (instance.findCell(ac))counter++;
           
           
          }
          System.out.println("number found = " + counter);
         timer.stopTimer();
        System.out.println(timer.duration());
   
     
    }

Saturday, April 28, 2012

Unique Random Number Generator



package utilities;

import java.util.ArrayList;
import java.util.Collections;

/**
 *
 * @author noel
 */
public class UniqueRandomNumber {

    public static class OutOfBoundsException extends Exception {

        public OutOfBoundsException() {
            super("Generator past bounds");
        }
    }
    private int size;
    private int counter = 0;
 
    private boolean hasNext = false;
    private ArrayList <Integer> listOfValues = new ArrayList<Integer>();
    public UniqueRandomNumber(int size){
        this.size = size;
        if (size > 0 ) hasNext = true;
        for (int i = 0; i < size; i++){
            listOfValues.add(i);
        }
        Collections.shuffle(listOfValues);
     
    }
    public int getNext() throws OutOfBoundsException{
        if (counter >= size) throw new OutOfBoundsException();
        int returnVal = listOfValues.get(counter);
        counter++;
        if (counter >= size) hasNext = false;
        return returnVal;
     
    }
         

    /**
     * @return the hasNext
     */
    public boolean hasNext() {
        return hasNext;
    }
 
 
}

Wednesday, April 25, 2012

Timer Class for Performance Testing


package gameoflifeiversion;

/**
 *
 * @author noel
 */
public class TimerClass {
    private long startTime;
    private long currentTime;
    private long endTime;
 
    public TimerClass(){
     
    }
    public void startTimer(){
        startTime = System.currentTimeMillis();
    }
    public String lapTime(){
        currentTime = System.currentTimeMillis();
       return (currentTime - startTime) + " milliseconds";

   }
    public void stopTimer(){
         endTime = System.currentTimeMillis();
    }
     public String duration(){
     
       return (endTime - startTime) + " milliseconds";

   }
}

More Game of life code




package gameoflifeiversion;


import java.util.Collection;


/**
 *
 * @author noel
 */
public interface ICellColl {
    public ICell findCell(int x, int y);
    public ICell findCell (ICell cell);
    public Collection<ICell> getNeighbours(ICell cellToFind);   
    public Collection<ICell> getNeighbours(int x, int y);   
    public void addCell(ICell cell);
    
    public static class Extent{
        private int leastx = 1;
        private int greatestx = 1;
        private int leasty = 1;
        private int greatesty = 1;


        /**
         * @return the leastx
         */
        public int getLeastx() {
            return leastx;
        }


        /**
         * @param leastx the leastx to set
         */
        public void setLeastx(int in) {
            leastx = in;
        }


        /**
         * @return the greatestx
         */
        public  int getGreatestx() {
            return greatestx;
        }


        /**
         * @param greatestx the greatestx to set
         */
        public void setGreatestx(int in) {
            greatestx = in;
        }


        /**
         * @return the leasty
         */
        public  int getLeasty() {
            return leasty;
        }


        /**
         * @param leasty the leasty to set
         */
        public void setLeasty(int in) {
            leasty = in;
        }


        /**
         * @return the greatesty
         */
        public int getGreatesty() {
            return greatesty;
        }


        /**
         * @param greatesty the greatesty to set
         */
        public void setGreatesty(int in) {
            greatesty = in;
        }
    }
}






/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gameoflifeiversion;


/**
 *
 * @author noel
 */
public abstract class AbstractICellColl  implements ICellColl {


    public AbstractICellColl() {
    }
    private ICellColl.Extent extent = new ICellColl.Extent(); 
    @Override
    public void addCell(ICell cell){
       
        if (cell.getX() < extent.getLeastx()) {
            extent.setLeastx(cell.getX());
        }
        if (cell.getX() > extent.getGreatestx()) {
            extent.setGreatestx(cell.getX());
        }
        if (cell.getY() < extent.getLeasty()) {
            extent.setLeasty(cell.getY());
        }
        if (cell.getY() > extent.getGreatesty()) {
            extent.setGreatesty(cell.getY());
        }
    }


    /**
     * @return the extent
     */
    public ICellColl.Extent getExtent() {
        return extent;
    }


    
    
}


package gameoflifeiversion;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

/**
 *
 * @author noel
 */
public class ArrayListCellColl extends AbstractICellColl{

    private ArrayList<ICell> coll = new ArrayList<ICell>();
    private boolean hasNewCell = false; 
    
    @Override
    public ICell findCell(int x, int y) {
        AliveCell ac = new AliveCell();
        ac.setX(x);
        ac.setY(y);
        return findCell(ac);
        
    }

    @Override
    public ICell findCell(ICell cell) {
        if (hasNewCell){
           Collections.sort(coll);
           hasNewCell = false;
        }
        if (cell == null) return null;
        int index = Collections.binarySearch(this.coll, cell);
        if (index < 0 )return null;
        return coll.get(index);
        
        
    }

    @Override
    public Collection<ICell> getNeighbours(ICell cellToFind) {
         ArrayList<ICell> neighbours = new ArrayList<ICell>();
        ICell addCell = findCell(cellToFind.getX() - 1, cellToFind.getY() - 1);
        if (addCell != null) {
            neighbours.add(addCell);
        }
        addCell = findCell(cellToFind.getX(), cellToFind.getY() - 1);
        if (addCell != null) {
            neighbours.add(addCell);
        }
        addCell = findCell(cellToFind.getX() + 1, cellToFind.getY() - 1);
        if (addCell != null) {
            neighbours.add(addCell);
        }
        addCell = findCell(cellToFind.getX() - 1, cellToFind.getY());
        if (addCell != null) {
            neighbours.add(addCell);
        }
        addCell = findCell(cellToFind.getX() + 1, cellToFind.getY());
        if (addCell != null) {
            neighbours.add(addCell);
        }
        addCell = findCell(cellToFind.getX() - 1, cellToFind.getY() +1);
        if (addCell != null) {
            neighbours.add(addCell);
        }
        addCell = findCell(cellToFind.getX(), cellToFind.getY() +1);
        if (addCell != null) {
            neighbours.add(addCell);
        }
        addCell = findCell(cellToFind.getX() + 1, cellToFind.getY() +1);
        if (addCell != null) {
            neighbours.add(addCell);
        }
        return neighbours;

    }

    @Override
    public Collection<ICell> getNeighbours(int x, int y) {
        AliveCell ac = new AliveCell();
        ac.setX(x);
        ac.setY(y);
        return getNeighbours(ac);
    }

    @Override
    public void addCell(ICell cell) {
        hasNewCell = true;
        coll.add(cell);
       super.addCell(cell);
    }
    
}

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gameoflifeiversion;


import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;


/**
 *
 * @author noel
 */
public class HashMapCellColl extends AbstractICellColl {
private HashMap<ICell, ICell> coll = new HashMap<ICell,ICell>();
    
    @Override
    public ICell findCell(int x, int y) {
       AliveCell ac = new AliveCell();
        ac.setX(x);
        ac.setY(y);
        return findCell(ac);
    }


    @Override
    public ICell findCell(ICell cell) {
       return coll.get(cell);
    }


   
    @Override
    public Collection<ICell> getNeighbours(ICell cellToFind) {
         ArrayList<ICell> neighbours = new ArrayList<ICell>();
        ICell addCell = findCell(cellToFind.getX() - 1, cellToFind.getY() - 1);
        if (addCell != null) {
            neighbours.add(addCell);
        }
        addCell = findCell(cellToFind.getX(), cellToFind.getY() - 1);
        if (addCell != null) {
            neighbours.add(addCell);
        }
        addCell = findCell(cellToFind.getX() + 1, cellToFind.getY() - 1);
        if (addCell != null) {
            neighbours.add(addCell);
        }
        addCell = findCell(cellToFind.getX() - 1, cellToFind.getY());
        if (addCell != null) {
            neighbours.add(addCell);
        }
        addCell = findCell(cellToFind.getX() + 1, cellToFind.getY());
        if (addCell != null) {
            neighbours.add(addCell);
        }
        addCell = findCell(cellToFind.getX() - 1, cellToFind.getY() +1);
        if (addCell != null) {
            neighbours.add(addCell);
        }
        addCell = findCell(cellToFind.getX(), cellToFind.getY() +1);
        if (addCell != null) {
            neighbours.add(addCell);
        }
        addCell = findCell(cellToFind.getX() + 1, cellToFind.getY() +1);
        if (addCell != null) {
            neighbours.add(addCell);
        }
        return neighbours;


    }


    @Override
    public Collection<ICell> getNeighbours(int x, int y) {
        AliveCell ac = new AliveCell();
        ac.setX(x);
        ac.setY(y);
        return getNeighbours(ac);
    }


    @Override
    public void addCell(ICell cell){
        if (cell==null) return;
        super.addCell(cell);
        coll.put(cell, cell);
    }
    
}




The Following blog posts the code for The Game of life
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gameoflifeiversion;

/**
 *
 * @author noel
 */
public interface ICell extends Comparable{
    @Override
    public int hashCode();
    @Override
    public String toString(); 
    public void setX(int x);
    public void setY(int y);
    public int getX();
    public int getY();
    
    @Override
    public boolean equals(Object c);
    
    @Override
    public int compareTo(ICell cell);
    
}

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gameoflifeiversion;

/**
 *
 * @author noel
 */
public abstract class AbstractCell implements ICell{
  private int x;
  private int y;
@Override
    public int compareTo(ICell comparison) {
        
        if (this.getY()comparison.getY()) return 1;
        if (this.getY() == comparison.getY()
                && this.getX() < comparison.getX()) return -1;
        if (this.getY() == comparison.getY()
                && this.getX() > comparison.getX()) return 1;
        return 0;
 
    }
 @Override
 public boolean equals(Object obj){
     if (!(obj instanceof AbstractCell)) return false;
    AbstractCell ac = (AbstractCell)obj;
    return ac.getX() == this.getX() && ac.getY() == this.getY();

 }
  
  
  
  
    @Override
  public int hashCode() {
      int returnValue = 0;
        if (x != 0){
            returnValue = x * 31;
            
        }
        if (y!=0){
         returnValue *= y;   
        }
        return returnValue;
        }
    
    /**
     * @return the x
     */
    public int getX() {
        return x;
    }

    /**
     * @param x the x to set
     */
    public void setX(int x) {
        this.x = x;
    }

    /**
     * @return the y
     */
    public int getY() {
        return y;
    }

    /**
     * @param y the y to set
     */
    public void setY(int y) {
        this.y = y;
    }
    public String toCellString(){
        return getX() + "_" + getY();
    }
    
    
}


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gameoflifeiversion;

/**
 *
 * @author noel
 */
public class AliveCell extends AbstractCell{
    @Override
    public String toCellString(){
        return "A_"+super.toCellString();
    }

    
    
}

Thursday, March 3, 2011

Overriding hash code and equals in collections


package SDMXDatabaseUploader;

import java.util.HashMap;


public class SDMXSeries {
public HashMap SeriesKey = new HashMap();

public HashMap Obs = new HashMap();
/**
* Since SeriesKeys have to be unique this is
* what defines if an SDMXSeries equals another.
*/

public boolean equals(Object o){
SDMXSeries comparison = (SDMXSeries)o;
return SeriesKey.equals(comparison.SeriesKey);

}
/**
*
*/
public int hashCode(){
return SeriesKey.hashCode();

}

/**
*
* @param key
* @param value
* @throws NullPointerException if key or value is null.
* @throws DuplicateKeyException if key is repeated.
*/
public void addSeriesKeyValue(String key, String value)throws NullPointerException, DuplicateKeyException{

if (key == null || value == null)throw new NullPointerException("Key or Value is null");
if (SeriesKey.containsKey(key))throw new DuplicateKeyException("Failed trying to add a duplicate key to the series key" + key);
SeriesKey.put(key, value);

}
/**
*
* @param key
* @param value
* @throws NullPointerException if key or value is null.
* @throws DuplicateKeyException if key is repeated.
*/
public void addObsKeyValue(String key, String value)throws NullPointerException, DuplicateKeyException{

if (key == null || value == null)throw new NullPointerException("Key or Value is null");
if (Obs.containsKey(key))throw new DuplicateKeyException("Failed Trying to add a duplicate key to the series key" + key);
Obs.put(key, value);
}
public String toString(){
return SeriesKey.toString() + " " + Obs.toString();

}
}


Exception code...


package SDMXDatabaseUploader;

public class DuplicateKeyException extends Exception {

/**
*
*/
private static final long serialVersionUID = 1L;
public DuplicateKeyException (String message){
super(message);
}
public DuplicateKeyException (){
super("Failed attempting to add duplicate key.");

}

}

package SDMXDatabaseUploader;

public class EmptyValueException extends Exception {
public EmptyValueException (int lineNumber){
super("Processed Line "+ lineNumber +"has an empty string for one or more entries.");
}

}

Crypto Utils

This is taken directly from http://www.rgagnon.com/javadetails/java-0400.html


It is wholly this persons work and what follows is a copy for my future reference...

package SDMXDatabaseUploader;
/*
* Taken directly with thanks from http://www.rgagnon.com/javadetails/java-0400.html
*/
import java.io.File;
import java.io.FileWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class CryptoUtils {

public static final String AES = "AES";

/**
* encrypt a value and generate a keyfile
* if the keyfile is not found then a new one is created
* @throws GeneralSecurityException
* @throws IOException
*/
public static String encrypt(String value, File keyFile)
throws GeneralSecurityException, IOException
{
if (!keyFile.exists()) {
KeyGenerator keyGen = KeyGenerator.getInstance(CryptoUtils.AES);
keyGen.init(128);
SecretKey sk = keyGen.generateKey();
FileWriter fw = new FileWriter(keyFile);
fw.write(byteArrayToHexString(sk.getEncoded()));
fw.flush();
fw.close();
}

SecretKeySpec sks = getSecretKeySpec(keyFile);
Cipher cipher = Cipher.getInstance(CryptoUtils.AES);
cipher.init(Cipher.ENCRYPT_MODE, sks, cipher.getParameters());
byte[] encrypted = cipher.doFinal(value.getBytes());
return byteArrayToHexString(encrypted);
}

/**
* decrypt a value
* @throws GeneralSecurityException
* @throws IOException
*/
public static String decrypt(String message, File keyFile)
throws GeneralSecurityException, IOException
{
SecretKeySpec sks = getSecretKeySpec(keyFile);
Cipher cipher = Cipher.getInstance(CryptoUtils.AES);
cipher.init(Cipher.DECRYPT_MODE, sks);
byte[] decrypted = cipher.doFinal(hexStringToByteArray(message));
return new String(decrypted);
}



private static SecretKeySpec getSecretKeySpec(File keyFile)
throws NoSuchAlgorithmException, IOException
{
byte [] key = readKeyFile(keyFile);
SecretKeySpec sks = new SecretKeySpec(key, CryptoUtils.AES);
return sks;
}

private static byte [] readKeyFile(File keyFile)
throws FileNotFoundException
{
Scanner scanner =
new Scanner(keyFile).useDelimiter("\\Z");
String keyValue = scanner.next();
scanner.close();
return hexStringToByteArray(keyValue);
}


private static String byteArrayToHexString(byte[] b){
StringBuffer sb = new StringBuffer(b.length * 2);
for (int i = 0; i < b.length; i++){
int v = b[i] & 0xff;
if (v < 16) {
sb.append('0');
}
sb.append(Integer.toHexString(v));
}
return sb.toString().toUpperCase();
}

private static byte[] hexStringToByteArray(String s) {
byte[] b = new byte[s.length() / 2];
for (int i = 0; i < b.length; i++){
int index = i * 2;
int v = Integer.parseInt(s.substring(index, index + 2), 16);
b[i] = (byte)v;
}
return b;
}

}

Calling code

package JUnitTests;

import java.io.File;
import java.io.IOException;
import java.security.GeneralSecurityException;

import SDMXDatabaseUploader.CryptoUtils;
import junit.framework.Assert;
import junit.framework.TestCase;

public class CryptoUtilsTest extends TestCase {
public void testCrypto(){
final String KEY_FILE = "./src/crypto.key";
//final String PWD_FILE = "c:/temp/howto.properties";

String clearPwd= "JUnitTestPassword";

// Properties p1 = new Properties();

//p1.put("user", "Real");
String encryptedPwd = null;
try {
encryptedPwd = CryptoUtils.encrypt(clearPwd, new File(KEY_FILE));
} catch (GeneralSecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//p1.put("pwd", encryptedPwd);
// p1.store(new FileWriter(PWD_FILE), "");

// ==================
//Properties p2 = new Properties();

//p2.load(new FileReader(PWD_FILE));
//encryptedPwd = p2.getProperty("pwd");
//System.out.println(encryptedPwd);
try {
//System.out.println
// (CryptoUtils.decrypt(encryptedPwd, new File(KEY_FILE)));
Assert.assertEquals("Encryption Failed", CryptoUtils.decrypt(encryptedPwd, new File(KEY_FILE)), clearPwd);
} catch (GeneralSecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}