//def cmd = "cmd /C dir" def cmd = ["cmd","/C","dir g*.bat"] // more flexible format //Groovyish Java// Runtime r = Runtime.runtime Process p = r.exec(cmd.toArray(new String())) BufferedReader inp = new BufferedReader(new InputStreamReader(p.getInputStream())) while (line = inp.readLine()) { println line } //Groovy!// println cmd.execute().text
Thursday, February 16, 2012
Shell/Command line execution
Friday, February 10, 2012
Colt - Random Number Generators
/* * see: http://acs.lbl.gov/software/colt/ */ @Grapes( @Grab(group='colt', module='colt', version='1.2.0') ) import cern.jet.random.* println Binomial.staticNextInt(500,0.5d) println ChiSquare.staticNextDouble(10.0d) println Exponential.staticNextDouble(1.0d) println ExponentialPower.staticNextDouble(1.0d) println Normal.staticNextDouble(10.0d,1.0d) println Poisson.staticNextInt(100.0d) println Uniform.staticNextDoubleFromTo(1.0d,100.0d) println VonMises.staticNextDouble(10.0d)
Apache Commons Collections
@Grapes( @Grab(group='commons-collections', module='commons-collections', version='3.2.1') ) import org.apache.commons.collections.* import org.apache.commons.collections.map.* import org.apache.commons.collections.bidimap.* IterableMap map1 = [a:1, b:2] as HashedMap map1.each { print it.key println it.value } OrderedMap map = new LinkedMap() map.with { put("FIVE", "5") put("SIX", "6") put("SEVEN", "7") assert firstKey() == "FIVE" assert nextKey("FIVE") == "SIX" assert nextKey("SIX") == "SEVEN" } BidiMap bidi = new TreeBidiMap() bidi.with { put("SIX", "6") assert get("SIX") == "6" assert get("SIX") == "6" assert getKey("6") == "SIX" removeValue("6") assert getKey("SIX") == null put("ONE", "1") } BidiMap inverse = bidi.inverseBidiMap() // returns a map with keys and values swapped assert inverse.getKey("ONE") == "1" Buffer buffer = new UnboundedFifoBuffer() buffer.with { add("ONE") add("TWO") add("THREE") assert remove() == "ONE" assert remove() == "TWO" } Bag bag = new HashBag() bag.with { add("ONE", 6) // add 6 copies of "ONE" remove("ONE", 2) // removes 2 copies of "ONE" assert getCount("ONE") == 4 }
Trove - high speed regular and primitive collections
/* * see: http://trove.starlight-systems.com/ */ @Grapes( @Grab(group='net.sf.trove4j', module='trove4j', version='3.0.2') ) import gnu.trove.set.* import gnu.trove.set.hash.* import gnu.trove.list.* import gnu.trove.list.array.* import gnu.trove.list.linked.* import gnu.trove.map.* import gnu.trove.map.hash.* //Most Trove classes start with the letter "T" to indicate that they're part of the Trove library. THashSet s = new THashSet() 100.times { i -> s.add ((i / 2).toInteger()) } assert s.size() == 50 assert s.contains(0) TIntArrayList a = new TIntArrayList() 100.times { i -> a.add ((i / 3).toInteger()) } assert a.size() == 100 assert a.get(0) == 0 TIntLinkedList l = new TLinkedList() 100.times { i -> l.add ((i / 4).toInteger()) } assert l.size() == 100 assert l.get(0) == 0 THashMap m = new THashMap() m['a'] = 1 m.b = 2 assert m.a == 1
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) }
Subscribe to:
Posts (Atom)