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());

}
}

}

(def Bonjour-Clojure “Welcome to functional programming”)

After the briefest of introductions to functional programming in college(a la Lisp) and dabbling with Scala, I took the functional plunge and started using Clojure recently. At this point, I have only written a couple of small programs and haven’t formed much of an opinion on where it stacks against my current favorite language at the moment(Groovy). This post will follow my usual getting started with a language snippets. I plan to write more entries as I get more familiar with the language. On to the code!


;binding
user=> (def Bonjour-Clojure “Welcome to functional programming”)
#’user/Bonjour-Clojure
user=> Bonjour-Clojure
“Welcome to functional programming”

;items in a list can be seperated via a comma or white space..
user=> (= [ 1 2 3] [1,2,3])
true

;count the number of consonants in a string
(defn count-consonants [string] (count ( re-seq #”[^aeiouAEIOU\s]” string )))
user=> (count-consonants “writing code is fun”)
10

;count the number of vowels in a string
(defn count-vowels [string] (count ( re-seq #”[aeiouAEIOU\s]” string )))
user=> (count-vowels “lukaskiewicz”)
5

;read a file into a list.. any suggestions on other ways are welcome 🙂
;usage (file-lines “string_path_to_file”) or to read a webpage ((file-lines “http://javazquez.com”)
(defn file-lines [file] (with-open [rdr (clojure.java.io/reader file)] ( set ( line-seq rdr))))

;view objects class
user=>(class “Im a string”)
java.lang.String

;length of string
user=>(count “I am 18 chars long”)
18

user=>(range 1 9)
(1 2 3 4 5 6 7 8 )

;repeat a digit
user=>(repeat 4 3)
(3 3 3 3)

;list comprehension
user=>(for [fruit [“apple” “orange” “grape”] ] (str fruit))
(“apple” “orange” “grape”)

;use map to create a new list… #() is a shortcut for an anonymous
user=>(map #(* 2 %1) [1 2 3 4])
(2 4 6 8 )

; also an anonymous function
user=> (map (fn [item](* 2 item)) [1 2 3 4])
(2 4 6 8 )

;simple fiter example on a list using odd?
user=> (filter odd? [1, 2,3,4,5])
(1 3 5)

;factorial using reduce
user=> (reduce * [1 2 3])
6

;if statement
user=> (if true (str “i am true”)(str “i am false”))
“i am true”

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’s variable variables

Hello everyone,

This is a quick post that should help developers new to Ruby. It may also help out those that have been away from the language for a while. Its just a quick reference to Ruby’s variables and their respective scopes. I know I had a chart to keep it all straight when I first encountered the language.

  1. @ An instance variable
  2. [a-z] or _ A local variable
  3. [A-Z] A constant
  4. @@ A class variable
  5. $ A global variable

This information is easily found on the net if you know what you are looking for. I just posted it to help make it even easier to find for those that are new to Ruby, or new to code writing 🙂 .

Windows GUI File Parser using Groovy

I find myself doing a lot of file parsing on my Windows XP machine lately. I decide to write a quick utility that would allow me to drag and drop files and search for the key words that I have identified. The utility doesn’t have the logic for searching using regex’s yet, but it should be really easy to add this functionality.

I hacked some Groovy Code with some Java Code and came up with the following script. Hope it is useful.

DISCLAIMER:

As the title suggests, I have only been able to get this to work on my Windows XP machine, OS X didn’t like the javax.swing.TransferHandler and it appears some other operating systems have a hard time with this also.


import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.awt.BorderLayout;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.TransferHandler.*;

class FileDropHandler extends TransferHandler {

private static final long serialVersionUID = 1L;

def wordsToFind =[]
JTextArea output
private JLabel errorMsg;
private String fileText = "";
private boolean test = false;
private boolean same = true;

public boolean canImport(TransferSupport supp) {
/* for the demo, we'll only support drops (not clipboard paste) */
if (!supp.isDrop()) {
return false;
}

/* return false if the drop doesn't contain a list of files */
if (!supp.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
return false;
}

boolean copySupported = (COPY & supp.getSourceDropActions()) == COPY;

if (copySupported) {
supp.setDropAction(COPY);
return true;
}

return false;
}

public boolean importData(TransferSupport supp) {
if (!canImport(supp)) {
return false;
}

/* get the Transferable */
Transferable t = supp.getTransferable();

try {

Object data = t.getTransferData(DataFlavor.javaFileListFlavor);

List fileList = (List) data;

for (int j = 0; j < fileList.size(); j++) { File file = (File) fileList.get(j); //file.getAbsolutePath() def tmpfh = new File("FileParser.txt") println wordsToFind.inspect() new File(file.getAbsolutePath()).eachLine{line->
wordsToFind.each{ if(line =~ "${it}" ){
println "${line}"
tmpfh.append(line)
tmpfh.append("\n\n")
this.output.setText(this.output.getText()+line+"\n")
}
}
}//end for

tmpfh.close()

}
} catch (UnsupportedFlavorException e) {
return false;
} catch (IOException e) {
return false;
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return true;
}

public void setOutput(JTextArea jta) {
this.output = jta;
}

public void setOutput(JLabel jta) {
errorMsg = jta;
}

public String getText() {
return fileText;
}

public void clearAll() {
fileText = "";
test = false;
same = true;

}
}

class AL implements ActionListener{
public JTextField jtf
public FileDropHandler dh
public AL(JTextField jtf,FileDropHandler dh){
this.jtf = jtf
this.dh =dh
}
public void actionPerformed(ActionEvent actionEvent){
println "${this.jtf.getText()}"
dh.wordsToFind= this.jtf.getText().split(' ')
}
}

JTextArea dTextArea = new JTextArea("Drop on me");
FileDropHandler dh = new FileDropHandler()
dh.setOutput(dTextArea)
JTextField jta = new JTextField("Enter words seperated by spaces")
dh.wordsToFind= jta.getText().split(' ')
JButton jb =new JButton("Update Word List")
jb.addActionListener( new AL(jta ,dh ))

dh.setOutput(dTextArea);
dTextArea.setDragEnabled(true);
dTextArea.setTransferHandler(dh);

JPanel p =new JPanel(new BorderLayout());
JFrame f = new JFrame()
p.add(jta, BorderLayout.NORTH)
p.add(dTextArea, BorderLayout.CENTER)
p.add(jb, BorderLayout.SOUTH)

f.getContentPane().add(p)
f.setSize(400,400)
f.setVisible(true)

A Groovy Flickr API

A long time ago I wanted to write a desktop GUI interface for Flickr. At the time I had just learned Java and thought it would be really cool to write it using swing. Little did I know how not cool working with swing would be 🙁

About halfway through the project I heard about a cool new dynamic way to write Java code called Groovy. From that day on Groovy has been making my life a whole lot easier. I didn’t need all the functionality in the flickrj library, so I decide to write a few methods for my app using Groovy. The hardest part of the whole thing was figuring out how to post images to Flickr, for that, I used the flickrj code as a reference. If that source code was not available, I don’t think I would have ever figured it out. So a big thanks to all the folks working on that project!

This is not a complete API for Flickr, but should provide enough to get started.
Link to my GitHub Repo

Adding and Resizing Images with Grails

Here is a quick post on how to upload images within your Grails project to your file system(rather than your database). It seems simple enough, but I ran into a few snags as I was working on one of my projects. Just wanted to provided a working example for those that are entering the Grails territory for the first time. Happy Coding!

I am using the imageTools plugin which you can read more about here

NOTE: The imageTools plugin has been criticized for its low quality of output. ImageMagick may be a better fit for you project(s). My particular project didn’t call for high quality pictures. A quick google search for “imagemagick for grails” should get you started on your way.

I am using version 1.0.3 in the example below

to install, I ran the following command from my grails application’s root directory

grails install-plugin http://www.arquetipos.co.cr/blog/files/grails-image-tools-1.0.3.zip

Domain-Class

class Picture {
byte[] imagefile
//Any other stuff you want to track

}

Controller Code for Saving an image

def save = {

def downloadedfile = request.getFile('imagefile')
def pictureInstance = new Picture(params)
def imageTool = new ImageTool()

if(downloadedfile && pictureInstance.save()){
String imagepath = grailsAttributes.getApplicationContext().getResource("images/").getFile().toString() + File.separatorChar + "${pictureInstance.id}.jpg"
downloadedfile.transferTo(new File(imagepath))

imageTool.load(imagepath)
imageTool.thumbnail(140)

imageTool.writeResult(imagepath, "JPEG")
imageTool.square()
flash.message = "Picture ${pictureInstance.id} created"
redirect(action:show,id:pictureInstance.id)
}
else {
render(view:'create',model:[pictureInstance:pictureInstance])
}
}

Code for displaying the image in both the ‘show’ and ‘list’ views

<td><img src="${createLinkTo(dir:'images', file: pictureInstance.id+'.jpg' )}" /> </td>

Mergesort and Quicksort with Dynamic Languages

The other day I was flipping through an algorithms book and came across a section on sorting. I remembered that I had a blast writing them c++ during my undergrad and thought it would be fun to write them in a couple of different languages. I settled on writing a quicksort, and mergesort.
Interesting notes:
1) Python(2.5) returns a None type when appending a value to an empty list which forced me to use ‘+’
>>> ex= [].append()
>>> print ex
>>>None

2) Groovy gave me a java.util.ConcurrentModificationException when I transcribed my Ruby code to Groovy. Because of the fact that I was deleting items from a list that I would read in later(while loop which checks size of left and right), I got this error. Accounting for that, the groovy code is pretty nasty.(anyone that would like to provide a better example without relying on the built in Collections.sort(list) would be welcome)

Here is my code… enjoy!


# javazquez.com
==========MERGE SORT========

-------------RUBY----------------

def merge_sort(ary)
  return ary if (ary.length <= 1)
  half = ary.length/2
  left = merge_sort(ary[0...half])
  right = merge_sort(ary[half..ary.length-1])
  result =[]
#compare first left and first right
  while left.length > 0 and right.length > 0
    result << (left[0] < right[0] ? left.shift : right.shift)
  end
  result.concat((left.length > 0 ? left : right))
  return result
end

ary=[1,5,14,3,2,45,2,0,01,-1]
p merge_sort(ary)


-----------Python Mergesort-------------

def merg_sort(lst):
    if(len(lst) <= 1):  return lst
    left = merg_sort(lst[:len(lst)/2])
    right = merg_sort(lst[len(lst)/2:len(lst)])
    result = []
    while len(left) > 0 and len(right)> 0:
        if( left[0] > right[0]):
            result.append(right.pop(0))
        else:
            result.append(left.pop(0))

    if(len(left)>0): result.extend(merg_sort(left))
    else: result.extend(merg_sort(right))

    return result

print merg_sort([8,7,43,2,5])


--------Erlang Mergesort-------------
-module(mergesort).
-export([ms/1,msTestSuite/1]).

ms(Lst)->break(Lst).
break([]) -> [];
break([L]) -> [L];
break(List) ->
    {Left, Right} = lists:split(length(List) div 2, List),
    merge(break(Left),break(Right)).

merge(L, []) -> L;
merge([], R) -> R;
merge([Lh|Ltail],[Rh|Rtail])->
	 if
	 Lh < Rh -> [Lh | merge(Ltail,[Rh|Rtail])];
	 Lh >= Rh -> [Rh | merge(Rtail,[Lh|Ltail])]
	 end.

%to test, run mergesort:msTestSuite(run).
msTestSuite(run)->
	[mstest1(run),mstest2(run),
	mstest3(run),mstest4(run),
    mstest5(run)].

mstest1(run)-> ms([3,2,1]).
mstest2(run)-> ms([3,3,3,1]).
mstest3(run)-> ms([]).
mstest4(run)-> ms([1]).
mstest5(run)-> ms([123,0,-1,23,2,34,5,678,7,5,8]).	 


-------------GROOVY MERGESORT--------
def ms(lst){
    if(lst.size() <= 1){return lst}
    def sz=lst.size()
    int half = (int)(sz/2)
    def l = lst [ 0 .. < half]
    def r = lst [ half.. < sz]
    def lft = ms(l)
    def rht  = ms(r)
    def result = []  
    def rcnt = 0
    def lcnt = 0
   while( lcnt < lft.size() && rcnt < rht.size()){
        if(lft[lcnt] < rht[rcnt]){
        	result += lft[lcnt++]
		}
        else{
			result += rht[rcnt++]
		}
     }
    if(lcnt < lft.size()){ 
		result +=  ms(lft[lcnt..< lft.size()]) 
	}
    else{
		result += ms(rht[rcnt..< rht.size()])
	}
    return result
}

sl=[3,88,5,3,2,1,-2,2]
println ms(sl)



# javazquez.com
========QUICKSORT========

-----RUBY----------------
def quick_sort(ary)
  return ary if(ary.length <= 1)
  greater,less = [],[]
  pos = rand(ary.length)
  pivot = ary[pos]
  ary.delete_at(pos)
  ary.each{|item|
       (item < pivot) ? less << item :greater << item}
  return (quick_sort(less) << pivot).concat(quick_sort(greater))
end

ary=[1,5,14,3,2,45,2,0,01,-1]
p quick_sort(ary)


----------Python Quicksort--------------

import random
def quickSort(lst):
	if(len(lst) <= 1):return lst
	greater = []
	less = []
	pivot = lst.pop(random.randint(0,len(lst)-1))
	for item in lst:
		if(item < pivot): less.append(item)
		else: greater.append(item)
	return quickSort(less)+[pivot]+quickSort(greater)

ary=[1,5,14,3,2,45,2,0,01,-1]


----------Erlang Quicksort--------------
-module(quicksort).
-export([qsort/1]).

qsort([]) ->[];
qsort([Pivot|T]) ->
		lists:append( [qsort([X || X <- T, X < Pivot]),
		[Pivot], qsort([X || X <- T, X >= Pivot]) ).

-------GROOVY QUICKSORT--------------
def quickSort(lst){
	if(lst.size() <= 1){return lst}
	def greater = []
	def less = []
	def pivot = lst.remove(new  Random().nextInt(lst.size()))
	lst.each{item-> 
		if(item < pivot){ less.add(item)}
		else{greater.add(item)}
	}
	return quickSort(less)+[pivot]+quickSort(greater)
}
print quickSort([1,5,14,3,2,45,2,0,01,-1])


Fun with Python and Gmail API

Yesterday I decided to play with Gmail’s API in order to grab my contacts. To my surprise, it was a snap. Google has instructions for python Here, I wrote my example using Python 2.5 on OS X. Once I had unzipped the GData contents, I just changed to the GData directory and ran
sudo python setup.py install
and I was ready to go.

Python Documentation for GDATA

#################################
# javazquez.com
# Google GMAIL API example
##################################
import gdata.contacts.service

user = 'user@gmail.com'
pwd = 'password'
client2 = gdata.contacts.service.ContactsService()
# Authenticate using your Google Docs email address
# and password.
client2.ClientLogin(user, pwd)
contacts_feed = client2.GetContactsFeed()

################################################
# NOTE: The GetContactsFeed does not give back
# all contacts.
# This 'problem' can be solved by looping
# until the contacts_feed.GetNextLink
# returns None.
################################################
l=[]
while(contacts_feed) :
for x in contacts_feed.entry:
l.append([x.title.text, x.email[0].address])
ret = contacts_feed.GetNextLink()
contacts_feed = client2.GetContactsFeed(ret.href) if(ret) else ret

print "here are your %d contacts" % len(l)
for contact in l:
print "%s -> %s" % (contact[0],contact[1])


Output

here are your xxxx contacts
ANDREW -> adrew@somewhere.com
...