Wednesday, March 28, 2012

JRegex

@Grapes(
    @Grab(group='net.sourceforge.jregex', module='jregex', version='1.2_01')
)
import jregex.*
//http://jregex.sourceforge.net/gstarted-advanced.html#imatching

String userNameChars="[\\w.\\-]+" //letters, dots, hyphens
String alphaNums="\\w+"
String dot="\\."
Pattern email=new Pattern(userNameChars + "@" + "(?:"+ alphaNums + dot + ")*" + alphaNums)

List ls = ['s@1.com','2@3.com','howdy@d.']

ls.each {
    println email.matcher(it).matches()
}

Pattern re=new Pattern("\\d\\d:\\d\\d") //two digits + colon + two digits
println("Pattern: "+re)

Matcher m=re.matcher()
test(m,"") // true
test(m,"1") // true
test(m,"12") // true
test(m,"1:2") // true
test(m,"12:") // true
test(m,"12:1") // true
test(m,"12:12") // true
test(m,"12:123") // true
test(m,"1:") // false
test(m,"123:1") // false

void test(Matcher m1, String s) {
   m1.setTarget(s)
   println("\""+s+"\" : "+m1.matchesPrefix()) //note: .matchesPrefix()
}

////*Pure Java/Groovy*////
//credit: http://glaforge.appspot.com/article/incomplete-string-regex-matching
List inp = [
    /12:/,/12:1/,/1/,/12:12/ //trues
    ,/1:/,/123:1/ //falses
]

inp.each {
    def matcher = it =~ /\d{2}:\d{2}/
    println matcher.matches() || matcher.hitEnd()
}

println 'done'

Sunday, March 4, 2012

Thread Pools

import java.util.concurrent.Callable
import java.util.concurrent.Executors

long ts // timer
def pool = Executors.newFixedThreadPool(THREADS)
def defer = { c -> pool.submit(c as Callable) }

//PLAIN//////////////////////////////////////////

ts = (new Date().time)
doit = { n ->
  def left = { def slp = Math.random()*n*1000+500l as Long; Thread.sleep(slp);  println Thread.currentThread().name + '!!left!!'+slp }()
  def right = { def slp = Math.random()*n*1000+500l as Long; Thread.sleep(slp);  println Thread.currentThread().name + '!!right!!'+slp }()
}
(1..3).each{ n -> println "n=$n => ${doit(n)}" }
println ((new Date().time)-ts)

//POOLED//////////////////////////////////////////////

ts = (new Date().time)
THREADS = 3
fib = { n ->
  def left = defer{ def slp = Math.random()*n*1000+500l as Long; Thread.sleep(slp);  println Thread.currentThread().name + '!!left!!'+slp }
  def right = defer{ def slp = Math.random()*n*1000+500l as Long; Thread.sleep(slp);  println Thread.currentThread().name + '!!right!!'+slp }
}
(1..3).each{ n -> println "n=$n => ${fib(n)}" }
pool.shutdown()
while(!pool.isTerminated()) { Thread.sleep(100) }
println ((new Date().time)-ts)

//FIB//////////////////////////////////////////////////

println "Calculating Fibonacci sequence in parallel..."
CUTOFF = 12    // not worth parallelizing for small n
THREADS = 10
serialFib = { n -> (n < 2) ? n : serialFib(n-1) + serialFib(n-2) }
fib = { n ->
  if (n < CUTOFF) return serialFib(n)
  def left = defer{ println Thread.currentThread().name; fib(n-1) }
  def right = defer{ println Thread.currentThread().name; fib(n-2) }
  left.get() + right.get()
}

(11..16).each{ n -> println "n=$n => ${fib(n)}" }
pool.shutdown()

Thursday, March 1, 2012

Jetty server

//src: http://www.redtoad.ca/ataylor/2012/02/simple-servlets-in-groovy/

@Grab(group='org.mortbay.jetty', module='jetty-embedded', version='6.1.26')
import org.mortbay.jetty.Server
import org.mortbay.jetty.servlet.*
import groovy.servlet.*;
import javax.servlet.http.*;
import javax.servlet.ServletConfig;
 
class SimpleGroovyServlet extends HttpServlet {
    def requestHandler
    def context
    void init(ServletConfig config) {
        super.init(config)
        context = config.servletContext
    }
    void service(HttpServletRequest request, HttpServletResponse response) {
        requestHandler.binding = new ServletBinding(request, response, context)
        use (ServletCategory) {
            requestHandler.call()
        }
    }
    static void run(int port, Closure requestHandler) {
        def servlet = new SimpleGroovyServlet(requestHandler: requestHandler)
        def jetty = new Server(port)
        def context = new Context(jetty, '/', Context.SESSIONS)
        context.addServlet(new ServletHolder(servlet), '/*')
        jetty.start()
    }
}

SimpleGroovyServlet.run(8080) { ->
    response.contentType = 'text/plain'
    println "hello world!"
    println "my path is ${request.pathInfo}"
    println "my params are $params"
}

//also try: groovy -l 8080 -e "println 'hello world'"
//alternate: https://github.com/groovypp/gretty/wiki/Getting-Started