Tag Archives: fun

Grails ldap integration with Active Directory via spring-security-ldap

The spring-security-ldap has great documentation. I put together a working example (at least in my environment) to complement the docs. When I was tasked with integrating our grails apps with Active Directory I remember there being a scarcity of examples.. so I hope this code will save you some time in getting ldap working with Active Directory in your grails environment.

Important files

grails-app/conf/Config.groovy
src/groovy/com/javazquez/ldapexample/MyUserDetailsContextMapper.groovy
src/groovy/com/javazquez/ldapexample/MyUserDetails.groovy
grails-app/conf/spring/resources.groovy

once you have your Active Directory configurations entered (grails-app/conf/Config.groovy), fire up your app and
test it out by logging in via the login controller.

Notes

  • You may have to update MyUserDetailsContextMapper.groovy as my Active Directory environment may differ from yours.
  • You may also want to update MyUserDetails.groovy to hold more or less info than my config.

-JV

Add Map, Reduce, and Filter to Groovy with an Extension Module

Having just read Michał Mally’s blog that was posted on Google+,
I was intrigued with two benefits listed in the blog:

  • The idea of being able to augment Groovy with changes that would behave as “if they were a part of original GDK”
  • support from your IDE like code completion shall be available out-of-the-box

In order to get my head around how Extension modules worked, I used the following as references
Creating an extension module
Groovy Goodness: Adding Extra Methods Using Extension Modules
Groovy Extension Modules

Cédric Champeau had this to say after I asked about the benefits of Extension Modules over using MetaClass/Expando/Category

@Juan: extension modules are automatically loaded and made available globally. You don’t have to bother with metaclasses (and potential issues with external changes). As well, categories are lexically scoped, although extension modules are global (meaning that they can be used anywhere in the code as long as the extension module is found on classpath).

Last but not least, extension modules are compatible with type checking and static compilation 🙂

To solidify my new understanding of Groovy’s Extension Modules, I decided that I needed to write some code. The example I came up with was to have the functional names (map, reduce, filter ) that I had come familiar with in using Clojure added to Groovy. These “extended methods” are using Groovy’s built-in collect, inject, and grep under the hood.

Source code can be found here

Here is the code for the new aliases found in the FuncProgUtilExtension.groovy class

package com.javazquez;

public class FuncProgUtilExtension {
    public static Collection filter(Collection self, Closure clozure) {
	   return self.grep(clozure)
   }
   public static Collection map(Collection self, Closure clozure) {
	   return self.collect(clozure)
   }
   public static Object reduce(Collection self, Closure clozure) {
	   return self.inject(clozure)
   }
   public static Object reduce(Collection self, String operator) {
	   switch(operator){
		   case '+' :
		      self.inject({acc, val -> acc + val})
			  break
		   case '-' :
			   self.inject({acc, val -> acc - val})
			   break
		   case'*' :
			   self.inject({acc, val -> acc * val})
			   break
		   case '/':
		   	   self.inject({acc, val -> acc / val})
			   break
		   case'**':
		   	   self.inject({acc, val -> Math.pow(acc, val)})
			   break
		   default:
			   throw new IllegalArgumentException()
			   break
	   }
   }
}

In a file named ‘org.codehaus.groovy.runtime.ExtensionModule’ located in ‘src/main/resources/META-INF/services/’

I have the following

moduleName=JavazquezFuncProgTest
moduleVersion=1.0
extensionClasses=com.javazquez.FuncProgUtilExtention

Using spock, I wrote the following tests :

package com.javazquez

import spock.lang.Specification

class FuncProgUtilSpec extends Specification{

	def "test map"(){
		expect:
			[ 1 ,2 ,3 ,4].map{it*2} == 	[ 1 ,2 ,3 ,4].collect{ it*2 } 	
	}	
	def "test reduce "(){
		expect:
			[ 1 ,2 ,3].reduce('*') == 6
			[ 1 ,2 ,3,4].reduce('+') == 10
			[ '1' ,'2' ,'3','4'].reduce('+') == '1234'
			[ 1 ,2 ,3].reduce('-') == -4
			[ 2, 2 ,2].reduce('**') == 16
			[ 1 ,2 ,3].reduce({acc, val -> acc + val}) ==[ 1 ,2 ,3].inject { acc, val -> acc + val}
	}
	def "test invalid argument"(){
	 	when:
	 		[ 1 ,2 ,3,4].reduce('%')
		then:
			thrown(IllegalArgumentException)
	}
	def "test filter"(){
		expect:
			[1,2,3,4,5,6,7,8,9].filter { it % 2 ==0 } == [2,4,6,8]
			[1,2,3,4,5,6,7,8,9].filter { it > 2 } == [3,4,5,6,7,8,9]
			"Juan Vazquez".toList().filter { it ==~ /[aeiou]/} == ['u','a','a','u','e']
	}
}

My biggest obstacle was getting the directory structure correct. It is amazing how little code was required to accomplish my goal. I hope my example project and listed references will help in your understanding of this powerful feature. My next step with this project going to be to make evaluation lazy.

Clojure Soundex

In need of a quick program to force myself to dive in to clojure, I chose to implement a soundex program that I at one time had written in C++. It was a fun exercise to step back and look at how my thought process changed based on the language I used. Hope you find this useful.

 

;steps
;1 keep first letter
;2 replace consonants
;3 remove w and h
;4 two adjacent are same, letters with h or w separating are also the same
;5 remove vowels
;6 continue until 1 letter 3 nums
(use 'clojure.contrib.str-utils)

(defn trnsfrm[ word]
  (->>
    (re-gsub #"(?i)[fbvp]" "1" word)
    (re-gsub #"(?i)[cgjkqsxz]" "2" ,,) 
    (re-gsub #"(?i)[dt]" "3" ,,) 
    (re-gsub #"(?i)[l]" "4" ,,)
    (re-gsub #"(?i)[mn]" "5" ,,)
    (re-gsub #"(?i)[r]" "6" ,,)))

(defn replace-adjacent [word] 
  (->> (re-gsub  #"(?i)[wh]" "" word ) 
  	trnsfrm 
  	(re-gsub #"(?i)([a-z0-9])\1+" "$1" )))  	

(defn pad [word](subs (str word "0000") 0 4))  	

(defn do-soundex [word]
    (pad ( str (first word)(re-gsub #"[aeiouy]"  "" (subs (replace-adjacent word) 1)))))

Update Refactored version
Not quite happy with the above example, I decided to see if I could refactor my code. Below is what I came up with(4 less lines code).

(use 'clojure.contrib.str-utils)

(def re-map{ #"(?i)[fbvp]" "1",#"(?i)[cgjkqsxz]" "2",#"(?i)[dt]" "3",#"(?i)[l]" "4",#"(?i)[mn]" "5",#"(?i)[r]" "6" })

(defn trns [word] (map #(re-gsub (key %1) (val %1) word) re-map))

(defn pad [word](subs (str word "0000") 0 4))

(defn rm1 [word] (apply str(drop 1 word)))

(defn do-soundex [word]
    (pad(str (first word) (->>
        (re-gsub #"(?i)[^aeiou\d]" "" (apply str (apply interleave (trns word ))))
        (re-gsub #"(?i)([a-z\d])\1+" "$1" )
        rm1
        (re-gsub #"(?i)[a-z]" "" )))))

 

UPDATE 2:Always one to go back to my previous works, I thought I would try a different approach. 

Now for the test cases

;;;Start test
(=(do-soundex  "Ashcroft") "A261")
(=(do-soundex  "Ashcraft") "A261")
(=(do-soundex  "Tymczak") "T522")
(=(do-soundex  "Pfister") "P236")
(=(do-soundex"lukaskiewicz")"l222")
(=(do-soundex"Rubin")"R150")
(=(do-soundex"Rupert")"R163")
(=(do-soundex"Robert")"R163")
(=(do-soundex "Vazquez")"V220")

;;;end test

Simple Groovy project using Gradle

Hello fellow Groovyists 🙂

I have been kicking the tires on using Gradle for my Groovy projects. I had a few stumbles along the way and wanted to share what I came up with for getting a very simple example working.

build.gradle

apply plugin: 'groovy'
version = "1.0-${new Date().format('yyyyMMdd')}"

manifest.mainAttributes("Main-Class" : "com.javazquez.HelloThere")

repositories {
mavenCentral()
mavenRepo urls: "http://groovypp.artifactoryonline.com/groovypp/libs-releases-local"
}
dependencies {
groovy group: 'org.codehaus.groovy', name: 'groovy-all', version: '1.8.4'
groovy group: 'org.mongodb', name: 'mongo-java-driver', version: '2.6.5'
groovy group: 'com.gmongo', name: 'gmongo', version: '0.9.1'
testCompile "org.spockframework:spock-core:0.5-groovy-1.8"
}

jar {
from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
}

below is the the HelloThere.groovy file located src/main/groovy/com/javazquez/HelloThere

package com.javazquez
public class HelloThere {

public static void main(String []args) {
println "Hello coders!"

}

}

after running gradle build, I can navigate to the build/libs directory and run java -jar HelloThere-1.0-20111115.jar and get the following ouptut

Hello coders!

Gradle is a fantastic tool and I hope this article helps show the ease of getting a project set up.

Writing a PayPal SOAP client with Java 6

I have always been mystified on the inner workings of SOAP. That was until I learned about the “wsimport” utility that comes with Java 6. It makes the entire process very easy. Below is an example of writing a SOAP client for PayPal’s Sandbox. This code will execute the SetExpressCheckout API call.

Just enter the following on your command line to generate the com.javazquez package

wsimport -keep -XadditionalHeaders -Xnocompile -p com.javazquez http://www.sandbox.paypal.com/wsdl/PayPalSvc.wsdl

open your favorite java editor(I used eclipse) and add the package(“com.javazquez”..created in the above command) to your new project

next, write some code to test out the APIs

package com.javazquez;

import javax.xml.ws.Holder;
public class TestEC {

public static void main(String[] args) {
SetExpressCheckoutReq req = new SetExpressCheckoutReq();
SetExpressCheckoutRequestType reqType = new SetExpressCheckoutRequestType();
SetExpressCheckoutRequestDetailsType details = new SetExpressCheckoutRequestDetailsType();
AddressType addr = new AddressType();
addr.cityName = "omaha";
addr.street1 = "123 main";
addr.country = CountryCodeType.US;
addr.name = "joe tester";

details.address = addr;
details.orderTotal = new BasicAmountType();
details.orderTotal.currencyID = CurrencyCodeType.USD;
details.orderTotal.value = "1.00";
details.cancelURL = "http://javazquez.com/cancel";
details.returnURL = "http://javazquez.com/return";

reqType.setVersion("2.10");

reqType.setExpressCheckoutRequestDetails = details;
req.setSetExpressCheckoutRequest(reqType);

UserIdPasswordType user = new UserIdPasswordType();
user.username = "XXX";
user.password = "XXXX";
user.signature = "XXXX";

PayPalAPIInterfaceService pp = new PayPalAPIInterfaceService();
PayPalAPIAAInterface pinterface = pp.getPayPalAPIAA();
Holder security = new Holder(new CustomSecurityHeaderType());
security.value.setCredentials(user);
try{
SetExpressCheckoutResponseType resp = pinterface.setExpressCheckout(req, security);
System.out.println(resp.token);
System.out.println(resp.correlationID);
for(ErrorType msg: resp.errors){
System.out.println(msg.longMessage);
}
}
catch(Exception ex){
System.out.println(ex.getMessage());

}
}

}

Login with Basic Authentication using Groovy

Hey there fellow Groovyists! I was recently in need of performing Basic Authentication on Apache using Groovy for a proof of concept. Below is what I was able to quickly put together.

//Here is a quick groovy 1.7.4 Basic Auth Example
@Grab(group=’org.codehaus.groovy.modules.http-builder’, module=’http-builder’, version=’0.5.0′ )

def authSite = new groovyx.net.http.HTTPBuilder( ‘http://10.110.201.115/~juanvazquez/basicAuth/’ )
authSite.auth.basic ‘user’, ‘pwd’
println authSite.get( path:’testAuth.html’ )

Fun with Python

Hey there fellow developers 😀
I have been working with Python lately(specifically Python3) and wanted to share some things I thought were pretty cool from an outsider’s(learning the language) perspective. I hope the following helps with getting to know this great language.. Enjoy


#construct a tuple using()
t=(1,2,3)

#contruct a list using [] 
 lst= [1,2,4]

#iterate a string and print each character
for i in "This is a String":
	print(i)
	
#getting the length of a string 
print ("length is",len("12345"))	

#test x is in a range
x=6
if(3< x <10 ):
	print( "I am true")
else:
	print( "I am false")
	
#test membership

if "2" in "1234":
	print("I am in the string")
if int("2") in [1,2,3,4]:
	print( "I am in the list")

#replication
print( "hithreetimes, "*3)

#using math class
import math
print(math.sqrt(4))

#print all methods
print(dir(math))


#named Tuples
import collections
Movie = collections.namedtuple("Movie","title rating")
collection =[Movie("Jaws", 4.0)]
collection.append(Movie("Toy Story", 5.0))
for movie in collection:
	print("I watched {0} and gave it {1} stars".format(movie.title,movie.rating))

#sequence unpacking
head, *rest = [1,2,3,4,5]
print("head is {0} and rest is {1}".format(head,rest))

#passing and unpacking parameters
def fullname(f,m,l):
	print("First Name ="+f)
	print("Middle Name ="+m)
        print("Last Name  ="l)

fakenamelist =["Homer","J","Simpson"]
fullname(*fakenamelist)		

#list comprehensions (print all odd numbers from 0 to 99)
print( [item for item in range(0,100) if item % 2])


#named parameters
def count_animals(number,*,	animal="ducks"):
	return "{0} {1}".format(number,animal)
print( count_animals(3,animal="cows"))
print( count_animals(3))



print(sorted([-1,2,-3],key=abs)) #same order

line = input("enter something.. ")
print("your line was " ,line)



I have been using python for web requests and recommend using the httplib2 library. It has a lot of really nice features.

Ruby to Python Primer

If your like me, you bounce around between languages a lot. Lately, I have been writing python code. It’s not Ruby 😀 , but it can get the job done. Here is a quick list of similarities between the two languages. I hope it helps… don’t forget to this list in the comments section 😉

#-----find object methods-----
s="hello, I am a string"

#ruby
puts s.methods

#python
print dir(s)

#find out more about a method using python
help(s.split)

#-----view object's class-----
#ruby
s.class

#python
s.__class__

#------Iterate hashes-------

#ruby
h.each{|key,value| puts "#{key}, #{value}"}

#python
for key,value in h.iteritems():
print key, value

#---ternary operators

#ruby
condition ? var = x : var = y

#python.. not exactly an operator, but you get the meaning
#---- var = y if condition is false
var = x if condition else y

#----lengths------
#ruby
s="hello, I am a string"
puts "Length of string is #{s.length} or #{s.size}"

h={:one=>2,:three=>4}
puts "Length of hash is same as string, #{h.length} or #{h.size} "

#python
print("This is the length of a string %s" % len("string"))
print("number of key/value pair= %d" % len({'one':1,'two':2}))

#---slicing lists/arrays
l=[1,2,3,4,5]

#ruby
l[1..3] #=>[2,3]

#python
l[1:3] #=>[2,3]

#--print string multiple times-----

#ruby
4.times{print "hello"} #=> hellohellohellohello

#python
print("hello" * 4) #=> hellohellohellohello

BarCamp Omaha

I have just been informed/invited to Omaha’s BarCamp! According to the site, this is a “unconference born from the desire for people to share and learn in an open environment.”

The list of topics that have been submitted thus far are already enough to get any developer’s inner geek super-charged. At this point I am not sure what I will talk about, but here are a few ideas.

  1. uploading/updating multiple models in one form (ROR)
  2. Groovy and flickr
  3. Action Script 3 concepts
  4. Linux Administration
  5. Setting up Twiki

Any suggestions or votes on what I could bring to the BarCamp would be awesome. If you can make it, I suggest checking this event out! After all, you don’t want to be sitting there listening to you fellow IT buddies raving about the great time they had learning at BarCamp…right?