Thursday, February 9, 2012

Google Guava

/*
 * see: http://code.google.com/p/guava-libraries/
 * grails caching idea: http://refactr.com/blog/2012/05/grails-in-memory-cache-using-googles-guava-library/
 */
@Grapes([
     @Grab("com.google.guava:guava:14.0.1")
])
import java.util.concurrent.TimeUnit
import com.google.common.primitives.Ints
import com.google.common.collect.Iterables
import com.google.common.collect.ImmutableList
import com.google.common.collect.ImmutableMap
import com.google.common.hash.Hashing
import com.google.common.cache.Cache
import com.google.common.cache.CacheBuilder
import com.google.common.cache.CacheLoader

List list = [1,2,3,3]
assert Iterables.frequency(list, 2) == 1
assert Iterables.frequency(list, 3) == 2

String temp = "test"
md5 = Hashing.md5()
String hash = md5.newHasher().putBytes(temp as byte[]).hash()
assert hash != temp
assert hash == "098f6bcd4621d373cade4e832627b4f6"

ImmutableList of = ImmutableList.of("a", "b", "c", "d");
// Same one for map
ImmutableMap map = ImmutableMap.of("key1", "value1", "key2", "value2");
//list of ints
List theList = Ints.asList(1, 2, 3, 4, 522, 5, 6);

//see: https://code.google.com/p/guava-libraries/wiki/CachesExplained
Cache cache = 
CacheBuilder.newBuilder()
  .weakKeys()
  .maximumSize(10000)
  .expireAfterWrite(10, TimeUnit.MINUTES)
  .build( new CacheLoader() {
    @Override
    public String load(Integer key) throws Exception {
      return retreveStringForKey(key);
    }
    @Override
    public Object load(Object o) { return o; } //???
  });

cache.metaClass.propertyMissing { k -> delegate.get(k) }
cache.metaClass.propertyMissing { k, v -> delegate.put(k, v) }
cache["a"] = 9
assert cache.size() == 1
assert cache["a"] == 9

Wednesday, February 8, 2012

Java2Html

@Grapes(
    @Grab(group='de.java2html', module='java2html', version='5.0')
)
import de.java2html.*;
import de.java2html.options.*;

String javaText = '''
/**
 * This is about ClassName.
 * {@link com.yourCompany.aPackage.SuperClass}
 * @author author
 */
public class ClassName extends SuperClass {
  /* This comment may span multiple lines. */
  private int integer = 0;
  public final static char character = 'A';
  // This comment may span only this line
  private String string = "zero";
}
'''

JavaSourceConversionSettings conversionOptions = new JavaSourceConversionSettings(new JavaSourceConversionOptions());
String htmlText = Java2Html.convertToHtmlPage(javaText, conversionOptions);
println (htmlText)

Tuesday, February 7, 2012

Geb Web Test

//updated Jan 12 2013
//check out Geb/Phantomjs integration via RemoteWebDriver support!

@Grapes([
     @Grab("junit:junit-dep:4.8.2"),
     @Grab("org.codehaus.geb:geb-junit4:0.7.2"),  //soon to go 0.9.0
     @Grab("org.seleniumhq.selenium:selenium-firefox-driver:2.28.0"),
     @Grab("org.seleniumhq.selenium:selenium-remote-driver:2.28.0"),
     @Grab("org.seleniumhq.selenium:selenium-support:2.28.0")
])
import geb.*
import geb.driver.CachingDriverFactory
import org.openqa.selenium.*
import org.openqa.selenium.remote.*
//import org.openqa.selenium.firefox.FirefoxProfile
//import org.openqa.selenium.firefox.FirefoxDriver
//import java.awt.Robot // see http://docs.oracle.com/javase/7/docs/api/java/awt/Robot.html#createScreenCapture(java.awt.Rectangle)


def cachedDriver = CachingDriverFactory.clearCacheAndQuitDriver() // clean-up old window & driver if any :)

File path = new File("C:\\geb-test\\")
path.mkdirs()

String searchFor = "dogs" // or null = off

String downloadImgURL = 'http://freemailtemplates.com/wp-content/themes/psdfiles-freemailtemplates/images/download-button.png' // or null = off
String downloadImgPathFile = path.absolutePath+'\\pic.png'

String screenshotURL = 'http://www.yahoo.com' // or null = off
String screenshotPathFile = path.absolutePath+'\\screenshot.png'
// NOTE: these two webdrivers ONLY init'ed for the URL page screenshots (which need a headless/remote browser like phantomjs) //
// you could probably just go to the URL and generate a report, too...? //
final RemoteWebDriver rdriver
final WebDriver augmentedDriver
if (screenshotURL) {
    try {
        rdriver = new RemoteWebDriver( "http://localhost:9134".toURL(), DesiredCapabilities.firefox() )
        augmentedDriver = new Augmenter().augment(rdriver)
    } 
    catch (Exception e) { screenshotURL = null }
}

// NOTE: config ONLY init'ed for reporting purposes //
def config = new Browser().getConfig() // steal a default config(??)
config.reportsDir = path

try{

    Browser.drive(config) {
        if (searchFor) {
            go "http://www.google.ca/"
            assert title.contains("Google")
            
            // basic searching/reading/etc ////////////////////////////////////////////
            def inputs = $("input, button")
            assert inputs.size() > 2
            inputs.each {
                println ":"+it.value()
            }
            
            // try a real Google search! ////////////////////////////////////////////
            def textSearch = $("form[action='/search'] input[type='text']")
            assert textSearch.size() == 1

            textSearch.value( searchFor )
            
            def buttonSearch = waitFor { $("input[type='button'], button") }.findAll{ it.text().toLowerCase().contains("search") }
            if (buttonSearch.size() == 0)
                // try another DOM node search //
                buttonSearch = waitFor { $("input[type='button']#gbqfb, button#gbqfb", 0) }
            
            assert buttonSearch.size() == 1
            
            buttonSearch.click()
            
            def items = waitFor { $("li.g") }
            // show the first item's text
            println items[0].text()
                
            def imgs = $("img")
            def srcs = imgs*.@src
            srcs.each { src ->
                // show the img sources
                println "img: " + (src ?: 'n/a')
            }
        }

        // try another page! ////////////////////////////////////////////
        go "http://cnn.com"
        assert title.contains("CNN.com")
        println ">>>" + title

        // try to dump the page's HTML and screenshot! ////////////////////////////////////////////
        reportGroup "cnn"
        report "homepage"

        // try to inject jQuery into the page! ////////////////////////////////////////////
        injectLibrary(js, 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js') ////////////////////////////////////////////
        js."jQuery.noConflict"()

        // try to grab the body's raw HTML! ////////////////////////////////////////////
        String body = ''+js."document.body.innerHTML"+''

        // try a URL file download! ////////////////////////////////////////////
        if (downloadImgURL) {
            try {
                downloadFile(browser, downloadImgURL, downloadImgPathFile)
            }
            catch (Exception e) { println "[ERROR] downloading: ${e.message}\n${e.printStackTrace()}" }
        }

        // try a URL page screenshot! ////////////////////////////////////////////
        if (screenshotURL) {
            try {
                screenshot(augmentedDriver, screenshotURL, screenshotPathFile)
            } 
            catch(Exception e) { println "[ERROR] screenshot: ${e.message}\n${e.printStackTrace()}" }
        }
        
        println '==Done=='

        //close() // close window, not neccesary with CachingDriverFactory.clearCacheAndQuitDriver()
        //quit()  // quit window, not neccesary with CachingDriverFactory.clearCacheAndQuitDriver()
    }

    cachedDriver = CachingDriverFactory.clearCacheAndQuitDriver() // clean-up window & driver if successful :)
    
} 
catch(Exception e) { println "[ERROR] Please try again: ${e.message}" }
//==END MAIN==//


//these util methods all get their context object passed in as a final//
def downloadFile(final Browser browser, String downloadImgURL, String downloadImgPathFile) {
    input = browser.downloadStream(downloadImgURL) // geb function
    output = new BufferedOutputStream(new FileOutputStream(downloadImgPathFile))
    output << input
}

def screenshot(final WebDriver driver, String url, String filename) {
    /*********************************************************
     * Note: you need a headless/remote web server running (like phantomjs)
     *  - beware, this doesn't seem to like HTTP redirects
     *********************************************************/
    driver.get(url)

    final File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE)
    scrFile.renameTo(filename ?: 'screenshot.png')
}

def injectLibrary(final js, String library){
    if (!js."document.body.innerHTML".contains(library))
        js.exec("document.body.appendChild(document.createElement('script')).src='$library'");
    //assert js."document.body.innerHTML".contains(library)
}

Thursday, January 26, 2012

Simple SHA Digest/Hash

import java.security.*

makeDigest = {String msg, int loops = 1, long t1 = (new Date()).getTime(), double q1 = Math.random() ->
    MessageDigest md = MessageDigest.getInstance("SHA")
    (Math.abs(loops) ?: 1).times {
        byte[] randm = {
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream()
            DataOutputStream dataOut = new DataOutputStream(byteOut)
            dataOut.writeLong(t1)
            dataOut.writeDouble(q1)
            return byteOut.toByteArray()
        }()
        md.update(randm)
        md.update(msg.getBytes())
    }
    return md.digest()
}

String user = "admin"
String password = "s3cr3t"

int loops = 1
byte[] hash1 = makeDigest(user+password, loops, 0, 0) // not randomized
byte[] hash2 = makeDigest(user+password) // randomized
assert hash1 != hash2
println "$hash1\n$hash2"

Wednesday, January 25, 2012

File/Directory Traverse

//helpful file properties: http://groovy.codehaus.org/JN2015-Files
 
import groovy.io.FileType

def walkFiles = {filepath, filterOnly, onFind, onEnd = {} ->
    try {
        File f = new File(filepath)
        f.traverse([type:FileType.FILES, nameFilter:filterOnly], onFind)
        onEnd()
    }
    catch (FileNotFoundException e) { println "ERROR: invalid file/directory"}
}

def pf = { file ->
    if (file.name.contains("a"))
        println file.name
}

walkFiles("C:\\123", ~/.*\.ico/, pf)

Tuesday, January 24, 2012

FastMap and IdentityHashMap

@Grapes(
    @Grab(group='javolution', module='javolution', version='5.5.1')
)
import javolution.util.FastMap // also FastSet, FastList

Map labels1 = new FastMap().shared()
Map labels2 = [:] as IdentityHashMap // unsorted

100.times { i ->
    labels1[String.valueOf(i)] = i*i
    labels2[String.valueOf(i)] = i*i
}

assert labels1 == labels2.sort()

see http://javolution.org/target/site/apidocs/javolution/util/FastMap.html

Fibonacci

/**
 * Fibonacci series:
 * the sum of two elements defines the next
 */

int LIMIT = 1000

(a,b) = [0,1]
while (b < LIMIT) {
    print "$b "
    (a,b) = [b, a+b]
}

(source)