Thursday, September 23, 2010

search for array within an array

import junit.framework.Assert;

import org.junit.Test;


public class SearchArray {


    public static void main(String[] args) {
        System.out.println( new SearchArray().findArray(new int[] {1,2,3,4,5,1,2,3,4,5}, new int[]{2,3,4})  );

    }
   
    /**
     * This method returns a -1 if no match is found else returns the index where
     * the sub array exists.
     * @param array1
     * @param array2
     * @return
     */
    private int findArray(int[] array1, int[] array2){
        int startIndex = -1;
        if(array1 !=null && array2 != null ){
            for (int i = 0; i < array1.length; i++){
                if(startIndex != -1){
                    break;
                }
                if( array2[0] == array1[i] ){
                    startIndex = i;    //we have found a starting point
                    for (int j = 0; j < array2.length; j++){                   
                        if( array2[j] != array1[startIndex + j]){
                            startIndex = -1;
                            break;
                        }                   
                    }
                }
            }
        }else{
            throw new IllegalArgumentException("The arrays should not be null");
        }
        return startIndex;       
    }
   
    @Test
    public void testNotFound() {   
        Assert.assertEquals( -1,  new SearchArray().findArray(new int[] {1,2,3,4,5,6,7,8,9,0}, new int[]{5,9,7}) );
    }
   
    @Test
    public void testFoundFirst() {   
        Assert.assertEquals( 1,  new SearchArray().findArray(new int[] {1,2,3,4,5,1,2,3,4,5}, new int[]{2,3,4}) );
    }
   
    @Test
    public void testFound() {   
        Assert.assertEquals( 4,  new SearchArray().findArray(new int[] {1,2,3,4,5,6,7,8,9,0}, new int[]{5,6,7}) );
    }

    @Test
    public void testException() {   
        try{
         new SearchArray().findArray( null, null) ;
        }catch(Exception e){
            Assert.assertTrue(e instanceof IllegalArgumentException);
           
        }
    }
}

java property loading and template substitution

public class PropertyLoader {
    private Properties properties;
    public PropertyLoader() {
        properties = loadProperties("input.properties");
        substitutePropertiesWithinProperties( properties );
    }
   
    public static void main(String[] args) throws IOException {
        PropertyLoader loader = new PropertyLoader();
        String htmlFile = loader.loadHtmlFileAsString("template.html");       
        System.out.println("The substituted HTML is : " + loader.substituteTemplateValues( htmlFile) );       
    }
   
    private String substituteTemplateValues(String htmlFile ) {
        Pattern pattern = Pattern.compile( "\\$\\{\\w+}" );
        Matcher matcher = pattern.matcher( htmlFile );
        while( matcher.find( ) ){//Look for a place holder in prop value.
            String placeHolder = htmlFile.substring( matcher.start(), matcher.end());
            String placeHolderKey = placeHolder.substring( 2, placeHolder.length() - 1 );
            String placeHolderValue = (String)properties.get( placeHolderKey );
            if (placeHolderValue == null){
                throw new IllegalArgumentException("Property " + placeHolder + " cannot be substituted.");               
            }
            htmlFile =  htmlFile.replaceFirst( "\\$\\{\\w+}" , placeHolderValue);
            matcher = pattern.matcher( htmlFile );    //Update the matcher for the next iteration
        }       
           
        return htmlFile;
    }

    private String loadHtmlFileAsString(String filePath) throws java.io.IOException{
        StringBuffer fileData = new StringBuffer(1000);
        ClassLoader loader = Thread.currentThread ().getContextClassLoader ();       
        BufferedReader reader = new BufferedReader( new InputStreamReader(loader.getResourceAsStream(filePath) ) );
        char[] buf = new char[1024];
        int numRead=0;
        while((numRead=reader.read(buf)) != -1){
            fileData.append(buf, 0, numRead);
        }
        reader.close();
        return fileData.toString();
    }   
   
    private void substitutePropertiesWithinProperties( Properties properties) {
        Pattern pattern = Pattern.compile( "\\$\\{\\w+}" );
        for(Object key : properties.keySet()){
            String val = (String) properties.get(key);
            Matcher matcher = pattern.matcher(val);   
            while( matcher.find( ) ){//Look for a place holder in prop value.
                String placeHolder = val.substring( matcher.start(), matcher.end());
                String placeHolderKey = placeHolder.substring( 2, placeHolder.length() - 1 );
                String placeHolderValue = (String) properties.get( placeHolderKey );
                if (placeHolderValue == null){
                    throw new IllegalArgumentException("Property strToReplace cannot be substituted.");               
                }
                val =  val.replaceFirst( "\\$\\{\\w+}" , placeHolderValue);
                properties.put(key, val);    //Update the properties set
                matcher = pattern.matcher(val);    //Update the matcher for the next iteration
            }
        }
    }

    public Properties loadProperties (String name){
        ClassLoader loader = Thread.currentThread ().getContextClassLoader ();
        Properties result = null;       
        InputStream in = null;
        try{                               
            in = loader.getResourceAsStream (name);            // Returns null on lookup failures:
            if (in != null){
                result = new Properties ();
                result.load (in); // Can throw IOException
            }
        }
        catch (Exception e){
            result = null;
        }
        finally{
            if (in != null) try { in.close (); } catch (Throwable ignore) {}
        }
       
        return result;
    }
}