<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0">

<channel>
	<title>It's not a blog, It's a feature</title>
	
	<link>http://javazquez.com/juan</link>
	<description>Juan A. Vazquez</description>
	<lastBuildDate>Tue, 06 Apr 2010 03:43:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/ItsNotABlogItsAFeature" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="itsnotablogitsafeature" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Ruby’s variable variables</title>
		<link>http://javazquez.com/juan/2009/08/31/rubys-variable-variables/</link>
		<comments>http://javazquez.com/juan/2009/08/31/rubys-variable-variables/#comments</comments>
		<pubDate>Tue, 01 Sep 2009 02:13:15 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[scope]]></category>
		<category><![CDATA[variable]]></category>

		<guid isPermaLink="false">http://javazquez.com/juan/?p=229</guid>
		<description><![CDATA[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&#8217;s variables and their respective scopes. I know I had a chart to keep it all straight when I [...]]]></description>
			<content:encoded><![CDATA[<p>Hello everyone,</p>
<p>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&#8217;s variables and their respective scopes. I know I had a chart to keep it all straight when I first encountered the language.</p>
<ol>
<li>@ 	 An instance variable</li>
<li>[a-z] or _ 	A local variable</li>
<li>[A-Z] 	A constant</li>
<li>@@	A class variable</li>
<li>$ 	A global variable</li>
</ol>
<p>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 <img src='http://javazquez.com/juan/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  .</p>
]]></content:encoded>
			<wfw:commentRss>http://javazquez.com/juan/2009/08/31/rubys-variable-variables/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Windows GUI File Parser using Groovy</title>
		<link>http://javazquez.com/juan/2009/04/18/windows-gui-file-parser-using-groovy/</link>
		<comments>http://javazquez.com/juan/2009/04/18/windows-gui-file-parser-using-groovy/#comments</comments>
		<pubDate>Sat, 18 Apr 2009 19:53:29 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[DND]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[java swing]]></category>

		<guid isPermaLink="false">http://javazquez.com/juan/?p=221</guid>
		<description><![CDATA[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&#8217;t have the logic for searching using regex&#8217;s yet, but it should [...]]]></description>
			<content:encoded><![CDATA[<p>   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&#8217;t have the logic for searching using regex&#8217;s yet, but it should be really easy to add this functionality. </p>
<p> I hacked some Groovy Code with some Java Code and came up with the following script. Hope it is useful.</p>
<p><strong>DISCLAIMER:</strong></p>
<p>  As the title suggests, I have only been able to get this to work on my Windows XP machine, OS X didn&#8217;t like the <strong> javax.swing.TransferHandler </strong>and it appears some other operating systems have a hard time with this also.</p>
<p><code><br />
import java.awt.datatransfer.DataFlavor;<br />
import java.awt.datatransfer.Transferable;<br />
import java.awt.datatransfer.UnsupportedFlavorException;<br />
import java.io.File;<br />
import java.io.IOException;<br />
import java.security.NoSuchAlgorithmException;<br />
import java.util.List;<br />
import java.awt.BorderLayout;<br />
import java.awt.*;<br />
import java.awt.event.ActionListener;<br />
import java.awt.event.ActionEvent;<br />
import javax.swing.JFrame;<br />
import javax.swing.JPanel;<br />
import javax.swing.JLabel;<br />
import javax.swing.JButton;<br />
import javax.swing.JTextArea;<br />
import javax.swing.JTextField;<br />
import javax.swing.TransferHandler.*;</p>
<p>class FileDropHandler extends TransferHandler {</p>
<p>	private static final long serialVersionUID = 1L;</p>
<p>	def wordsToFind =[]<br />
	JTextArea output<br />
	private JLabel errorMsg;<br />
	private String fileText = "";<br />
	private boolean test = false;<br />
	private boolean same = true;</p>
<p>	public boolean canImport(TransferSupport supp) {<br />
	/* for the demo, we'll only support drops (not clipboard paste) */<br />
	if (!supp.isDrop()) {<br />
		return false;<br />
	}</p>
<p>	/* return false if the drop doesn't contain a list of files */<br />
	if (!supp.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {<br />
	return false;<br />
	}</p>
<p>	boolean copySupported = (COPY &#038; supp.getSourceDropActions()) == COPY;</p>
<p>	if (copySupported) {<br />
	supp.setDropAction(COPY);<br />
	return true;<br />
	}</p>
<p>	return false;<br />
	}</p>
<p>	public boolean importData(TransferSupport supp) {<br />
	if (!canImport(supp)) {<br />
	return false;<br />
	}</p>
<p>	/* get the Transferable */<br />
	Transferable t = supp.getTransferable();</p>
<p>	try {</p>
<p>	Object data = t.getTransferData(DataFlavor.javaFileListFlavor);</p>
<p>	List fileList = (List) data;</p>
<p>	for (int j = 0; j < fileList.size(); j++) {</p>
<p>	File file = (File) fileList.get(j);<br />
	//file.getAbsolutePath()<br />
	def tmpfh = new File("FileParser.txt")<br />
	println wordsToFind.inspect()<br />
	 new File(file.getAbsolutePath()).eachLine{line-><br />
	   wordsToFind.each{   if(line =~ "${it}" ){<br />
	        println "${line}"<br />
	        tmpfh.append(line)<br />
	        tmpfh.append("\n\n")<br />
			this.output.setText(this.output.getText()+line+"\n")<br />
	   }<br />
	  }<br />
	 }//end for</p>
<p>	tmpfh.close()</p>
<p>	}<br />
	} catch (UnsupportedFlavorException e) {<br />
	return false;<br />
	} catch (IOException e) {<br />
	return false;<br />
	} catch (NoSuchAlgorithmException e) {<br />
	// TODO Auto-generated catch block<br />
	e.printStackTrace();<br />
	}</p>
<p>	return true;<br />
	}</p>
<p>	public void setOutput(JTextArea jta) {<br />
	this.output = jta;<br />
	}</p>
<p>	public void setOutput(JLabel jta) {<br />
	errorMsg = jta;<br />
	}</p>
<p>	public String getText() {<br />
	return fileText;<br />
	}</p>
<p>	public void clearAll() {<br />
	fileText = "";<br />
	test = false;<br />
	same = true;</p>
<p>	}<br />
}</p>
<p>class AL implements ActionListener{<br />
   public JTextField jtf<br />
   public FileDropHandler dh<br />
    public AL(JTextField jtf,FileDropHandler dh){<br />
     this.jtf = jtf<br />
     this.dh =dh<br />
    }<br />
    public void actionPerformed(ActionEvent actionEvent){<br />
        println "${this.jtf.getText()}"<br />
        dh.wordsToFind= this.jtf.getText().split(' ')<br />
        }<br />
}</p>
<p>JTextArea dTextArea = new JTextArea("Drop on me");<br />
FileDropHandler dh = new FileDropHandler()<br />
dh.setOutput(dTextArea)<br />
JTextField jta = new JTextField("Enter words seperated by spaces")<br />
dh.wordsToFind= jta.getText().split(' ')<br />
JButton jb =new JButton("Update Word List")<br />
jb.addActionListener( new AL(jta ,dh  ))</p>
<p>dh.setOutput(dTextArea);<br />
dTextArea.setDragEnabled(true);<br />
dTextArea.setTransferHandler(dh);</p>
<p>JPanel p =new JPanel(new BorderLayout());<br />
JFrame f = new JFrame()<br />
p.add(jta, BorderLayout.NORTH)<br />
p.add(dTextArea, BorderLayout.CENTER)<br />
p.add(jb, BorderLayout.SOUTH)</p>
<p>f.getContentPane().add(p)<br />
f.setSize(400,400)<br />
f.setVisible(true)<br />
</code></p>
]]></content:encoded>
			<wfw:commentRss>http://javazquez.com/juan/2009/04/18/windows-gui-file-parser-using-groovy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Groovy Flickr API</title>
		<link>http://javazquez.com/juan/2009/03/30/a-groovy-flickr-api/</link>
		<comments>http://javazquez.com/juan/2009/03/30/a-groovy-flickr-api/#comments</comments>
		<pubDate>Mon, 30 Mar 2009 16:19:11 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Groovy]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[Flickr]]></category>
		<category><![CDATA[Howto]]></category>
		<category><![CDATA[image]]></category>
		<category><![CDATA[java swing]]></category>
		<category><![CDATA[pictures]]></category>
		<category><![CDATA[POST]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://javazquez.com/juan/?p=204</guid>
		<description><![CDATA[The hardest part of the whole thing was figuring out how to post images to Fickr, for that, I used the flickrj code as reference. If it was not for the available source code, I don't think I would have ever figured it out. So a big thanks to all the folks working on that project!]]></description>
			<content:encoded><![CDATA[<p>     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 <img src='http://javazquez.com/juan/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' />  </p>
<p>     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&#8217;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&#8217;t think I would have ever figured it out. So a big thanks to all the folks working on that project!</p>
<p>This is not a complete API for Flickr, but should provide enough to get started. Also, <a href="http://javazquez.com/code/Groovy/glickr.txt">here </a>is a link to a text file with the below code for an easier way to view the source.<br />
<code></p>
<p>import java.io.IOException<br />
import java.security.MessageDigest<br />
import java.security.NoSuchAlgorithmException<br />
import java.util.ArrayList<br />
import java.util.Date<br />
import java.util.Hashtable<br />
import javax.imageio.ImageIO<br />
import org.w3c.dom.Element<br />
import org.w3c.dom.NodeList<br />
import java.io.File;<br />
import java.net.*;<br />
import java.io.IOException;<br />
import org.xml.sax.SAXException;<br />
public class FlickrAPI {<br />
	 String nsid = ""</p>
<p>	private String secret = "your secret"</p>
<p>	/**<br />
	 * api key<br />
	 */<br />
	private String akey = "your key goes here"</p>
<p>	private String sig = ""</p>
<p>	private String url = ""</p>
<p>	 String authToken = ""</p>
<p>	private String frob = ""</p>
<p>	private String restString = "http://flickr.com/services/rest/?method="</p>
<p>	public FlickrAPI() {<br />
		println("Created FlickerAPI")<br />
	}</p>
<p>	public void authNewUser() {<br />
		constructFrobUrl()<br />
		createAuthURL()<br />
		getToken()<br />
	}<br />
	private String constructUrl(String flickrMethod,Map m,boolean authCall =false){<br />
	  String s= this.restString+flickrMethod+"&#038;api_key="+this.akey<br />
		m.each{key,value-><br />
			s+=key+value<br />
			}<br />
			if(authCall){s+="&#038;auth_token=${this.authToken}&#038;api_sig=${this.sig}"}<br />
		return s<br />
	}<br />
	def mapFlickrUser(){</p>
<p>	}<br />
	//if bool is true then this is a Authenticated call<br />
public void setSig(String method,boolean bool = false){<br />
			String sigString="${this.secret}api_key${this.akey}"<br />
		try {<br />
			if(bool){<br />
				sigString +="auth_token${this.authToken}${method}"<br />
				println "Sig is true"<br />
			}else{sigString+=method}<br />
		} catch (NoSuchAlgorithmException e) {<br />
			e.printStackTrace()<br />
		}<br />
	println "sig is " +sigString<br />
		this.sig = calcMD5(sigString)<br />
}</p>
<p>def jupload(String filePath,Map parameters=[:]){<br />
	println("parameters ${parameters.inspect()}")<br />
	def paramMessages=[]<br />
	int paramLength=0</p>
<p>	    if(parameters==[:]){<br />
			this.sig = calcMD5("${this.secret}api_key${this.akey}auth_token${this.authToken}")<br />
		}else{<br />
			//sort them and add them to the signature<br />
			String p=""<br />
			parameters.keySet().toList().sort().each{key-><br />
				//if the key ='tags' make it into space separated string<br />
		         p+= "${key}${parameters[key]}"<br />
				paramMessages.add(addParameter([key,parameters[key]]) )<br />
			}<br />
			this.sig = calcMD5("${this.secret}api_key${this.akey}auth_token${this.authToken}${p}")<br />
			paramMessages.each{stringMsg->paramLength+=stringMsg.length()}<br />
		}</p>
<p>		File file=new File(filePath)<br />
	    String CrLf = "\r\n";<br />
		def url = new URL("http://api.flickr.com/services/upload/")<br />
		//def connection = url.openConnection()<br />
		HttpURLConnection conn = url.openConnection()<br />
			def is = new FileInputStream(file)<br />
			def flength= file.length()<br />
			byte[] imgData= new byte[(int)flength]</p>
<p>			int offset = 0;<br />
			int numRead = 0;<br />
			while (offset < imgData.length &#038;&#038; (numRead=is.read(imgData, offset, imgData.length-offset)) >= 0) {<br />
				offset += numRead;<br />
			}</p>
<p>			// Ensure all the bytes have been read in<br />
			if (offset < imgData.length) {<br />
				throw new IOException("The file was not completely read: "+file.getName());<br />
			}<br />
			println "filesize ->${imgData.length}"<br />
			// Close the input stream, all file contents are in the bytes variable<br />
			is.close();<br />
        String message01=addParameter(['api_key',this.akey])<br />
		String message02 = addParameter(['auth_token',this.authToken])<br />
		String message03 = addParameter(['api_sig',this.sig])</p>
<p>		String message1 = "";<br />
		message1 += "---------------------------6d72u458s1587" + CrLf;<br />
		message1 += "Content-Disposition: form-data; name=\"photo\"; filename=\""+filePath+"\"" + CrLf;<br />
		message1 += "Content-Type: image/jpeg" + CrLf;<br />
		message1 += CrLf;</p>
<p>		// the image is sent between the messages in the multipart message.</p>
<p>		String message2 = "";<br />
		message2 += CrLf + "---------------------------6d72u458s1587--" + CrLf;</p>
<p>		def totalLength = String.valueOf((message01.length() + message02.length() + message03.length() + message1.length() + message2.length() + imgData.length+ paramLength))<br />
		conn.setRequestMethod("POST")<br />
		conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=-------------------------6d72u458s1587");<br />
		conn.setRequestProperty("Host", "api.flickr.com");<br />
		conn.setRequestProperty("Content-Length",totalLength );<br />
		conn.setDoOutput(true)</p>
<p>		System.out.println("open os");<br />
		def os = conn.getOutputStream();</p>
<p>		System.out.println(message01);<br />
		os.write(message01.getBytes());</p>
<p>		System.out.println(message02);<br />
		os.write(message02.getBytes());<br />
 //write the params here before the image<br />
    	paramMessages.each{msg->os.write(msg.getBytes())}</p>
<p>		System.out.println(message03);<br />
		os.write(message03.getBytes());</p>
<p>		System.out.println(message1);<br />
		os.write(message1.getBytes());<br />
    	os.write(imgData,0 ,imgData.length)</p>
<p>		os.write(message2.getBytes());</p>
<p>		println "end writing"<br />
		os.flush()<br />
		os.close()</p>
<p>		conn.connect()<br />
		conn.disconnect()<br />
		println	conn.content.text</p>
<p>}<br />
//[name value]<br />
private String addParameter(List para){<br />
	String CrLf = "\r\n";<br />
	String message01 = "";<br />
	message01 += "---------------------------6d72u458s1587" + CrLf;<br />
	message01 += "Content-Disposition: form-data; name=\"${para[0]}\"" + CrLf;<br />
	message01 += CrLf;<br />
	message01 += para[1] + CrLf;<br />
	return message01<br />
}</p>
<p>	public void constructFrobUrl() {<br />
		setSig("methodflickr.auth.getFrob")<br />
		this.url = "http://flickr.com/services/rest/?method=flickr.auth.getFrob&#038;api_key=${this.akey}&#038;api_sig=${this.sig}"<br />
		println("here is url-> ${this.url}")<br />
		def node = new XmlParser().parse(this.url)//dom.parseXML("frob")<br />
		this.frob = node['frob'].text().toString()<br />
		println("frob =>${this.frob}\n\n")<br />
	}</p>
<p>	/**<br />
	 * This function will calculate an MD5 sum of String Signature and return<br />
	 * the String value of the Hash via strBuildup<br />
	 *<br />
	 * @param signature<br />
	 * @throws NoSuchAlgorithmException<br />
	 * @returns strBuildup<br />
	 */<br />
	private String calcMD5(String signature) throws NoSuchAlgorithmException {<br />
		// get Instance from Java Security Classes<br />
		String strBuildup = ""<br />
		MessageDigest md5 = MessageDigest.getInstance("MD5")<br />
		byte[] md5summe = md5.digest(signature.getBytes())<br />
		for (int k = 0; k < md5summe.length; k++) {<br />
			byte b = md5summe[k]<br />
			String temp = Integer.toHexString(b &#038; 0xFF)<br />
			/*<br />
			 * toHexString has the side effect of making stuff like 0x0F only<br />
			 * one char F(when it should be '0F') so I check the length of<br />
			 * string<br />
			 */<br />
			if (temp.length() < 2) {<br />
				temp = "0" + temp<br />
			}<br />
			temp = temp.toUpperCase()<br />
			strBuildup += temp<br />
		}<br />
		return strBuildup<br />
	}</p>
<p>	/**<br />
	 * get the authentication token<br />
	 *<br />
	 * @return<br />
	 */<br />
	public checkToken(){<br />
		setSig("methodflickr.auth.checkToken",true)<br />
		this.url=constructUrl('flickr.auth.checkToken',[:],true)<br />
		println(this.url)<br />
		def node = new XmlParser().parse(this.url)<br />
		println("done parsing check Token INFO ===>${node.children()}")<br />
	}<br />
	public void getToken() {<br />
		println("Entering getToken\n\n")<br />
		setSig("frob${this.frob}methodflickr.auth.getToken")<br />
		this.url = "${this.restString}flickr.auth.getToken&#038;api_key=${this.akey}&#038;frob=${this.frob}&#038;api_sig=${this.sig}"<br />
		//println(this.url)<br />
		def node = new XmlParser().parse(this.url)<br />
		//need to get the nsid and the authtoken<br />
		this.authToken = node['auth']['token'].text()<br />
		this.nsid = node['auth']['user'].'@nsid'.text()<br />
		println "token is ${this.authToken}"<br />
		println("Token =>${node['auth']['token'].text()}")<br />
		println("nsid =>${node['auth']['user'].'@nsid'.text()}")<br />
		println("perms =>${node['auth']['perms'].text()}")</p>
<p>		// set user nsid<br />
		println("Exiting GET Token")<br />
	}</p>
<p>	public void createAuthURL() {<br />
		setSig("frob${this.frob}permsdelete")<br />
		String cmd = "open http://flickr.com/services/auth/?api_key="+ this.akey + "&#038;perms=delete" + "&#038;frob=" + this.frob + "&#038;api_sig=" + this.sig<br />
		try {<br />
			Process proc =	cmd.execute()<br />
			proc.waitForOrKill(10000)<br />
			sleep(2000)<br />
		} catch (IOException e) {<br />
			// TODO Auto-generated catch block<br />
			e.printStackTrace()<br />
		}<br />
	}</p>
<p>	/***************************************************************************<br />
	 * AUTH<br />
	 **************************************************************************/<br />
	/***************************************************************************<br />
	 * ACTIVITIES<br />
	 **************************************************************************/<br />
	//POLL ONLY ONCE AN HOUR!!!!!<br />
	public activityGetUserComments(){<br />
		setSig("methodflickr.activity.userComments",true)<br />
		this.url=constructUrl('flickr.activity.userComments',[:],true)<br />
		println(this.url)<br />
		def node = new XmlParser().parse(this.url)<br />
		println("done parsing GET user Comments INFO ===>${node.children()}")<br />
	}<br />
	/***************************************************************************<br />
	 * BLOGS<br />
	 **************************************************************************/<br />
	/***************************************************************************<br />
	 * CONTACTS<br />
	 **************************************************************************/<br />
	 public void contactsGetList(){<br />
			setSig("methodflickr.contacts.getList",true)<br />
			this.url=constructUrl('flickr.contacts.getList',[:],true)<br />
			println(this.url)<br />
			def node = new XmlParser().parse(this.url)<br />
			println("done parsing GET contact List INFO ===>${node.children()}")<br />
	}<br />
	/***************************************************************************<br />
	 * FAVORITES<br />
	 **************************************************************************/<br />
	/***************************************************************************<br />
	 * GROUPS<br />
	 **************************************************************************/<br />
	/***************************************************************************<br />
	 * GROUP POOLS<br />
	 **************************************************************************/</p>
<p>	/***************************************************************************<br />
	 * INTERESTINGNESS<br />
	 **************************************************************************/</p>
<p>/***************************************************************************<br />
 * PHOTOS<br />
*what if a return back an array of pictures?<br />
 **************************************************************************/<br />
def photosGetNotInSet(){<br />
		List piclist=[]<br />
		setSig("methodflickr.photos.getNotInSet",true)<br />
		this.url=constructUrl('flickr.photos.getNotInSet',[:],true)<br />
		println(this.url)<br />
		def node = new XmlParser().parse(this.url)<br />
		println("done parsing GET Not in Set INFO ===>${node.children()}\n\n\n")<br />
/*		test=f.photosGetNotInSet()<br />
		 println test.photos.each{it-> it.each{p-> println p}} //list of nodes</p>
<p>		test.photos.photo[3].attributes()<br />
		test.photos.photo.each{it-> println it.attribute('isfamily')} //gets the individual attr<br />
		test.photos.photo.each{it-> picList.push(new Picture(it))} //push a node into picture contructor</p>
<p>		*/</p>
<p>	return node<br />
	}</p>
<p>	def photosGetContactsPhotos(){<br />
		setSig("methodflickr.photos.getContactsPhotos",true)<br />
		this.url=constructUrl('flickr.photos.getContactsPhotos',[:],true)<br />
		def node = new XmlParser().parse(this.url)<br />
		return node<br />
	}</p>
<p>	def photosGetRecentlyUploaded() {<br />
		setSig("methodflickr.photos.getRecent",true)<br />
		//this.url = "flickr.photos.getRecent&#038;api_key",[:],true)<br />
	    this.url= constructUrl('flickr.photos.getRecent',[:],true)<br />
		def node = new XmlParser().parse(this.url)<br />
		println("done parsing RecentPhotos ===>${node.children()}")<br />
		return node<br />
	}<br />
	public void photosGetInfo(){</p>
<p>	}<br />
	/***************************************************************************<br />
	 * PEOPLE<br />
	 **************************************************************************/<br />
	def contactsGetList(){<br />
		setSig("methodflickr.contacts.getList",true)<br />
		this.url=constructUrl('flickr.contacts.getList',[:],true)<br />
		def node = new XmlParser().parse(this.url)<br />
		//println("done parsing GET contact List INFO ===>${node.children()}")<br />
		return node<br />
	}<br />
	def peopleGetUploadStatus(){<br />
		setSig("methodflickr.people.getUploadStatus",true)<br />
		this.url=constructUrl('flickr.people.getUploadStatus',[:],true)<br />
		def node = new XmlParser().parse(this.url)<br />
		println("done parsing GET upload Status INFO ===>${node.children()}")<br />
		return node<br />
	}<br />
	def peopleGetPublicPhotos() {<br />
		setSig("methodflickr.people.getPublicPhotosuser_id${this.nsid}",true)<br />
	 	this.url=constructUrl('flickr.people.getPublicPhotos',['&#038;user_id=':"${this.nsid}"],true)<br />
		def node = new XmlParser().parse(this.url)<br />
		//def peepsInfo = node['auth']['peeps'].text()<br />
		println("done parsing GET  Public Photos ===>${node.children()}")<br />
		return node<br />
	}<br />
	def peopleGetPeopleInfo() {<br />
		setSig("methodflickr.people.getInfouser_id${this.nsid}",true)<br />
	 	this.url=constructUrl('flickr.people.getInfo',['&#038;user_id=':"${this.nsid}"],true)<br />
		def node = new XmlParser().parse(this.url)<br />
		//def peepsInfo = node['auth']['peeps'].text()<br />
		return node<br />
	}</p>
<p>	/********************************************<br />
	* photosets<br />
	************************/<br />
   def photosetsGetList(String uid){<br />
		setSig("methodflickr.photosets.getListuser_id${uid}",true)<br />
	 	this.url=constructUrl('flickr.photosets.getList',['&#038;user_id=':"${uid}"],true)<br />
		def node = new XmlParser().parse(this.url)<br />
		//def peepsInfo = node['auth']['peeps'].text()<br />
		return node</p>
<p>}<br />
 def photosetsGetPhotos(String setID){<br />
		setSig("methodflickr.photosets.getPhotosphotoset_id${setID}",true)<br />
	 	this.url=constructUrl('flickr.photosets.getPhotos',['&#038;photoset_id=':"${setID}"],true)<br />
	println this.url<br />
		def node = new XmlParser().parse(this.url)<br />
		//def peepsInfo = node['auth']['peeps'].text()<br />
		return node</p>
<p>}<br />
/**<br />
Upload photos</p>
<p>http://api.flickr.com/services/upload/</p>
<p>*/<br />
//get the picture when supplied the proper args<br />
//http://farm{farm-id}.static.flickr.com/{server-id}/{id}_{secret}_[mstb].jpg</p>
<p> public String getPicture(String farmId, String serverId, String photoid, String secret,String size ="s"){<br />
	return "http://farm${farmId}.static.flickr.com/${serverId}/${photoid}_${secret}_${size}.jpg"</p>
<p>}</code></p>
]]></content:encoded>
			<wfw:commentRss>http://javazquez.com/juan/2009/03/30/a-groovy-flickr-api/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Adding and Resizing Images with Grails</title>
		<link>http://javazquez.com/juan/2009/01/24/adding-and-resizing-images-with-grails/</link>
		<comments>http://javazquez.com/juan/2009/01/24/adding-and-resizing-images-with-grails/#comments</comments>
		<pubDate>Sat, 24 Jan 2009 18:58:24 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[image]]></category>
		<category><![CDATA[imageTools]]></category>
		<category><![CDATA[pictures]]></category>
		<category><![CDATA[plugin]]></category>

		<guid isPermaLink="false">http://javazquez.com/juan/?p=179</guid>
		<description><![CDATA[Just wanted to provided a working example for those that are entering the Grails territory for the first time.]]></description>
			<content:encoded><![CDATA[<p>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!</p>
<p>I am using the imageTools plugin which you can read more about <a href="http://grails.org/ImageTools+plugin">here</a> </p>
<p><strong>NOTE: </strong>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&#8217;t call for high quality pictures. A quick google search for &#8220;imagemagick for grails&#8221; should get you started on your way.</p>
<p>I am using version 1.0.3 in the example below</p>
<p><strong>to install, I ran the following command from my grails application&#8217;s root directory</strong></p>
<p><code>grails install-plugin http://www.arquetipos.co.cr/blog/files/grails-image-tools-1.0.3.zip</code></p>
<p><strong>Domain-Class</strong><br />
<code><br />
class Picture {<br />
byte[] imagefile<br />
//Any other stuff you want to track</p>
<p>}<br />
</code></p>
<p><strong>Controller Code for Saving an image</strong><br />
<code><br />
    def save = {</p>
<p>		def downloadedfile = request.getFile('imagefile')<br />
	 	def pictureInstance = new Picture(params)<br />
		def imageTool = new ImageTool()</p>
<p>     	       if(downloadedfile &#038;&#038; pictureInstance.save()){<br />
			String imagepath = grailsAttributes.getApplicationContext().getResource("images/").getFile().toString() + 	File.separatorChar + "${pictureInstance.id}.jpg"<br />
			downloadedfile.transferTo(new File(imagepath))</p>
<p>			imageTool.load(imagepath)<br />
			imageTool.thumbnail(140)</p>
<p>			imageTool.writeResult(imagepath, "JPEG")<br />
			imageTool.square()<br />
            flash.message = "Picture ${pictureInstance.id} created"<br />
            redirect(action:show,id:pictureInstance.id)<br />
        }<br />
        else {<br />
           render(view:'create',model:[pictureInstance:pictureInstance])<br />
        }<br />
    }<br />
</code><br />
<strong>Code for displaying the image in both the &#8216;show&#8217; and &#8216;list&#8217; views</strong><br />
<code><br />
	&lt;td&gt;&lt;img  src="${createLinkTo(dir:'images', file: pictureInstance.id+'.jpg' )}" /&gt; &lt;/td&gt;<br />
</code></p>
]]></content:encoded>
			<wfw:commentRss>http://javazquez.com/juan/2009/01/24/adding-and-resizing-images-with-grails/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Mergesort and Quicksort with Dynamic Languages</title>
		<link>http://javazquez.com/juan/2009/01/03/mergesort-and-quicksort-with-dynamic-languages/</link>
		<comments>http://javazquez.com/juan/2009/01/03/mergesort-and-quicksort-with-dynamic-languages/#comments</comments>
		<pubDate>Sat, 03 Jan 2009 18:10:58 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Erlang]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[algorithms]]></category>
		<category><![CDATA[mergesort]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[quicksort]]></category>
		<category><![CDATA[sort]]></category>
		<category><![CDATA[sorting]]></category>

		<guid isPermaLink="false">http://javazquez.com/juan/?p=64</guid>
		<description><![CDATA[Groovy, Ruby, Python, Erlang Mergesort, and Quicksort code examples]]></description>
			<content:encoded><![CDATA[<p>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.<br />
  <strong>Interesting notes:</strong><br />
<strong>1)</strong> Python(2.5) returns a None type when appending a value to an empty list which forced me to use &#8216;+&#8217;<br />
 >>> ex= [].append()<br />
 >>> print ex<br />
 >>>None</p>
<p><strong>2)</strong> Groovy gave me a <strong>java.util.ConcurrentModificationException</strong> 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)</p>
<p> Here is my code&#8230; enjoy!</p>
<pre><code>
# 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)
</code>
<code>
-----------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])
</code>
<code>
--------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]).
</code>
<code>
-------------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() &#038;&#038; 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)
</code>

<code markup="none">
# 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)
</code>
<code>
----------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]
</code>
<code>
----------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])

</code>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://javazquez.com/juan/2009/01/03/mergesort-and-quicksort-with-dynamic-languages/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Fun with Python and Gmail API</title>
		<link>http://javazquez.com/juan/2008/12/24/fun-with-python-and-gmail-api/</link>
		<comments>http://javazquez.com/juan/2008/12/24/fun-with-python-and-gmail-api/#comments</comments>
		<pubDate>Wed, 24 Dec 2008 17:58:10 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[google api]]></category>

		<guid isPermaLink="false">http://javazquez.com/juan/?p=82</guid>
		<description><![CDATA[Quick demonstration on how to pull contacts from gmail using python]]></description>
			<content:encoded><![CDATA[<p>Yesterday I decided to play with Gmail&#8217;s API in order to grab my contacts. To my surprise, it was a snap. Google has instructions for python <a href="http://code.google.com/apis/gdata/articles/python_client_lib.html">Here</a>, 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 <br/>&#8220;<strong>sudo python setup.py install</strong>&#8221; <br /> and I was ready to go.</p>
<p><a href="http://gdata-python-client.googlecode.com/svn/trunk/pydocs/">Python Documentation for GDATA</a></p>
<p><code>
<pre>
#################################<br />
# javazquez.com<br />
# Google GMAIL API example<br />
##################################<br />
import gdata.contacts.service</p>
<p>user = 'user@gmail.com'<br />
pwd = 'password'<br />
client2 = gdata.contacts.service.ContactsService()<br />
# Authenticate using your Google Docs email address<br />
# and password.<br />
client2.ClientLogin(user, pwd)<br />
contacts_feed = client2.GetContactsFeed()</p>
<p>################################################<br />
# NOTE: The GetContactsFeed does not give back<br />
#		all contacts.<br />
#              This 'problem' can be solved by looping<br />
#		until the contacts_feed.GetNextLink<br />
#             returns  None.<br />
################################################<br />
l=[]<br />
while(contacts_feed) :<br />
	for x in contacts_feed.entry:<br />
		l.append([x.title.text, x.email[0].address])<br />
	ret = contacts_feed.GetNextLink()<br />
 	contacts_feed = client2.GetContactsFeed(ret.href)  if(ret) else ret</p>
<p>print "here are your %d contacts" % len(l)<br />
for contact in l:<br />
	print "%s -> %s" % (contact[0],contact[1])<br />
</ pre><br />
</code><br />
<strong>Output</strong></p>
<blockquote><p>here are your xxxx contacts<br />
ANDREW  -> adrew@somewhere.com<br />
...
</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://javazquez.com/juan/2008/12/24/fun-with-python-and-gmail-api/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby to Python Primer</title>
		<link>http://javazquez.com/juan/2008/12/16/ruby-to-python-primer/</link>
		<comments>http://javazquez.com/juan/2008/12/16/ruby-to-python-primer/#comments</comments>
		<pubDate>Tue, 16 Dec 2008 16:44:15 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[fun]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Ruby Questions]]></category>

		<guid isPermaLink="false">http://javazquez.com/juan/?p=35</guid>
		<description><![CDATA[Here is a quick list of similarities between the two languages.
#ruby
puts s.methods 

#python
print dir(s)
]]></description>
			<content:encoded><![CDATA[<p>If your like me, you bounce around between languages a lot. Lately, I have been writing python code. It&#8217;s not Ruby <img src='http://javazquez.com/juan/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' />  , but it can get the job done. Here is a quick list of similarities between the two languages. I hope it helps&#8230; don&#8217;t forget to this list in the comments section <img src='http://javazquez.com/juan/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /><br />
<code><br />
#-----find object methods-----<br />
s="hello, I am a string"</p>
<p>#ruby<br />
puts s.methods </p>
<p>#python<br />
print dir(s)</p>
<p>#find out more about a method using python<br />
help(s.split)</p>
<p>#-----view object's class-----<br />
#ruby<br />
s.class </p>
<p>#python<br />
s.__class__</p>
<p>#------Iterate hashes-------</p>
<p>#ruby<br />
h.each{|key,value| puts "#{key}, #{value}"} </p>
<p>#python<br />
for key,value in h.iteritems():<br />
  print key, value</p>
<p>#---ternary operators</p>
<p>#ruby<br />
condition ? var = x : var = y</p>
<p>#python.. not exactly an operator, but you get the meaning<br />
#---- var = y  if condition is false<br />
var = x if condition else y     </p>
<p>#----lengths------<br />
#ruby<br />
s="hello, I am a string"<br />
puts "Length of string is #{s.length} or #{s.size}" </p>
<p>h={:one=>2,:three=>4}<br />
puts "Length of hash is same as string, #{h.length} or #{h.size} "</p>
<p>#python<br />
print("This is the length of a string %s" % len("string"))<br />
print("number of key/value pair= %d" % len({'one':1,'two':2}))</p>
<p>#---slicing lists/arrays<br />
l=[1,2,3,4,5]</p>
<p>#ruby<br />
l[1..3] #=>[2,3]</p>
<p>#python<br />
l[1:3] #=>[2,3]</p>
<p>#--print string multiple times-----</p>
<p>#ruby<br />
4.times{print "hello"} #=> hellohellohellohello</p>
<p>#python<br />
print("hello" * 4) #=> hellohellohellohello</p>
<p></code></p>
]]></content:encoded>
			<wfw:commentRss>http://javazquez.com/juan/2008/12/16/ruby-to-python-primer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby HTTPS POST’ing</title>
		<link>http://javazquez.com/juan/2008/12/07/ruby-https-posting/</link>
		<comments>http://javazquez.com/juan/2008/12/07/ruby-https-posting/#comments</comments>
		<pubDate>Mon, 08 Dec 2008 05:21:58 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[Howto]]></category>
		<category><![CDATA[HTTPS]]></category>
		<category><![CDATA[POST]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://javazquez.com/juan/?p=15</guid>
		<description><![CDATA[Code that POST's to HTTPS with ruby]]></description>
			<content:encoded><![CDATA[<p>So for my own geeky pleasure, I decided to try writing cgi scripts with Ruby, Python, PHP, and Perl.  All had readily accessible documentation on how to POST to a https URL but ruby. My first thought was to look at the Net:HTTP documentation found <a href="http://www.ruby-doc.org/stdlib/libdoc/net/http/rdoc/index.html">HERE.</a></p>
<p>The one example I wanted was not listed. I did some searching around and pieced together the following code. I hope this is as big a help to you as it was to me. Looking at it, It seems pretty intuitive&#8230;.but if your like me, sometimes you need it spelled out <img src='http://javazquez.com/juan/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' />   </p>
<p><strong>As a side note, setting path to path = &#8216;/../&#8217; is my work-around for a script that is mapped to www.mysite.com</strong> rather than &#8216;/some_POST_handling_script.rb&#8217;</p>
<p><code><br />
#Juan Vazquez ->javazquez.com<br />
require 'net/http'<br />
require 'net/https'<br />
http = Net::HTTP.new('www.mysite.com', 443)<br />
http.use_ssl = true<br />
#path(a.k.a) ->www.mysite.com/some_POST_handling_script.rb'<br />
path = '/some_POST_handling_script.rb'<br />
data = 'badguy=Gargamel'</p>
<p>headers = {'Content-Type'=&gt; 'application/x-www-form-urlencoded'}</p>
<p>resp, data = http.post(path, data, headers)</p>
<p>puts 'Code = ' + resp.code<br />
puts 'Message = ' + resp.message<br />
resp.each {|key, val| puts key + ' = ' + val}<br />
puts data</p>
<p></code></p>
]]></content:encoded>
			<wfw:commentRss>http://javazquez.com/juan/2008/12/07/ruby-https-posting/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Recursive Directory Search with Ruby and Groovy</title>
		<link>http://javazquez.com/juan/2008/11/06/recursive-directory-search-with-ruby-and-groovy/</link>
		<comments>http://javazquez.com/juan/2008/11/06/recursive-directory-search-with-ruby-and-groovy/#comments</comments>
		<pubDate>Thu, 06 Nov 2008 23:58:45 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[code]]></category>

		<guid isPermaLink="false">http://javazquez.com/juan/?p=14</guid>
		<description><![CDATA[Recursive file directory search written in both Ruby and Groovy.]]></description>
			<content:encoded><![CDATA[<p>A while back I was bored and decided I need to brush up on my Ruby chops. I had been wanting to play with threads for quite some time and couldn&#8217;t think of anything that would be a fun project to do&#8230;until this crazy idea hit me.  <em>&#8220;</em><em>W</em><em>ouldn&#8217;t it be cool if could generate multiple threads to search different servers for any file of my choosing?&#8221;</em> The code I wrote doesn&#8217;t directly do this, but with some minor tweaks it could be done.</p>
<p><em> </em>I took that idea and ran with it using Ruby. After I finished coding, I thought I would try writing it from scratch using my second favorite language, Groovy (Ruby is my first).  I have to admit, writing the Groovy code was more intuitive because of the baked in file/directory iterators. I refactored my Ruby code a few times and ended up using the find module to maximize performance. Below is the code, and as always, I am open to suggestions on other ways of doing it <img src='http://javazquez.com/juan/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p><strong>Ruby code</strong><br />
 <br />
<code>
<pre>
#########################
#  Juan Vazquez
#  http://javazquez.com
#########################
require 'find'
class DirectoryWizard
  attr_accessor :root_dir,:exts, :thread_cnt, :thread_tracker, :count
  #initialize with a root , and file extensions
  def initialize(root, t_count,*extensions)
    @root_dir, @exts, @thread_cnt , @thread_tracker, @count = root, extensions, t_count, [], 0
  end

  def start_looking
    begin
      puts Dir.entries(@root_dir).select{|dir_item| is_in_ext(dir_item) }
      list_dirs(@root_dir).each do|di|
        @thread_tracker << Thread.new(@root_dir+di){|directory|
                                             recursive_file_search(directory) }
        wait_for_running_threads  if(@thread_tracker.size > @thread_cnt)
      end
      wait_for_running_threads
    rescue Exception => e; puts e;
    end
  end
  def recursive_file_search(directory)
    Find.find(directory){|dir_item|
      if(is_in_ext(dir_item))
       @count+=1
       puts dir_item
      end
    }
  end

    #return array of immediate subdirectories excluding . and ..
  def list_dirs(directory)
   Dir.entries(directory).select{|fh|(!is_p_c_directory?(fh) &#038;&#038;
                                          File.directory?(directory+fh))}
  end

  #return an array of all file/directories excluding '.' and '..'
  def list_contents(directory)
    Dir.entries(directory).delete_if{|x| is_p_c_directory?(x)}
  end

  #is Parent or Current Directory
  def is_p_c_directory?(filename);(filename =="." || filename == "..");end

#return an array of files that match ext
  def is_in_ext(dir_item); @exts.detect{|ext| dir_item.match(ext)}; end

 def wait_for_running_threads
    @thread_tracker.each{|th|th.join}
    @thread_tracker=[]
  end
end #end class

t= DirectoryWizard.new("\\\\server\\e$\\profiles\\",16,'filename')

t.start_looking

puts "Done with Program count is #{t.count}"
</pre>
<p></code></p></blockquote>
<p><strong>Groovy Code</strong></p>
<p><code>
<pre>
import java.util.regex.*;
class DirWiz{
   def root_dir, exts, thread_max_cnt, thread_tracker, count

   public DirWiz(String basedir, int t_count, List extensions){
        this.root_dir = basedir
        this.exts = compile_regex(extensions)
        this.thread_max_cnt = t_count
        this.thread_tracker = []
        this.count=0
    }
    def start_looking(){
      try{
          def dir = new File(this.root_dir)
           check_for_files(this.root_dir)
          //recursively search directories
           dir.eachDir{ subDir->
            //thread it off
           if(this.thread_tracker.size() > this.thread_max_cnt){
               this.thread_tracker.each{it->it.join()}
               this.thread_tracker=[]
           }
           this.thread_tracker << Thread.start{
                 subDir.eachFileRecurse{ fh ->
                    check_using_compiled_regex(fh.canonicalPath)
                 }
           }
        }
      }catch(Exception e){
        println("error ${e}")
      }
      this.thread_tracker.each{it->it.join()}
      println("Done")
    }
   def print_if_match(String file){this.exts.each{ext->
                if(file=~ext){this.count+=1;println(file)}}
   }
   def check_using_compiled_regex(String file){
    try{
	def var = this.exts.find{it.matcher(file).matches()}
	if(var){this.count+=1;println(file)}
    }catch(Exception e){println("Not a Directory ${dir}\n$e")}
   }
   def check_for_files(String dir){
      try{ new File(dir).eachFile{ file ->
	        check_using_compiled_regex(file.canonicalPath)
        }
      }catch(Exception e){println("Not a Directory ${dir}\n$e")}
   }
   def compile_regex(List list){
    List ret_list=[]
    list.each{ ret_list <<    Pattern.compile(it,Pattern.CASE_INSENSITIVE)}
    return ret_list
   }
}

def t = new DirWiz('c:\\',16,[".*\\.jpg.*"])//look for jpegs
//def t = new DirWiz('\\\\server\\dir\\',16,["filname"])
t.start_looking()

println("Done with the program total number of files is ${t.count}")
</pre>
<p></code><br />
 </p>
<p> </p>
]]></content:encoded>
			<wfw:commentRss>http://javazquez.com/juan/2008/11/06/recursive-directory-search-with-ruby-and-groovy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Proxy/ReverseProxy and Apache2</title>
		<link>http://javazquez.com/juan/2008/08/16/proxyreverseproxy-and-apache2/</link>
		<comments>http://javazquez.com/juan/2008/08/16/proxyreverseproxy-and-apache2/#comments</comments>
		<pubDate>Sat, 16 Aug 2008 14:37:45 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Administration]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[apache]]></category>
		<category><![CDATA[configuration]]></category>

		<guid isPermaLink="false">http://javazquez.com/juan/?p=13</guid>
		<description><![CDATA[I recently configured Apache2 to be a ReverseProxy/Proxy and thought I would share my experiences while it was still fresh. Having never configured any kind of proxy, I found this webpage very informative. The scenario I would like to use for my example is that I have three internal web servers called Site Local IP Remote [...]]]></description>
			<content:encoded><![CDATA[<p>I recently configured Apache2 to be a ReverseProxy/Proxy and thought I would share my experiences while it was still fresh. Having never configured any kind of proxy, I found <a href="http://httpd.apache.org/docs/2.0/mod/mod_proxy.html">this webpage </a> very informative.  The scenario I would like to use for my example is that I have three internal web servers called</p>
<table>
<th>Site</th>
<th>Local IP</th>
<th>Remote IP</th>
<th>Port</th>
<tr>
<td>www.reallycoolsite.com</td>
<td>192.168.1.102</td>
<td>10.15.22.1</td>
<td>80</td>
</tr>
<tr>
<td>www.justcoolsite.com</td>
<td>192.168.1.102 </td>
<td> 10.15.22.2 </td>
<td>80</td>
</tr>
<tr>
<td>www.reallylamesite.com</td>
<td> 192.168.1.44</td>
<td> 10.15.22.3</td>
<td>80</td>
</tr>
</table>
<p>Alright&#8230;pretty straight forward right? If you are in a situation that I was when I started, you haven&#8217;t done much more than install apache from source and added a few modules here and there occasionally. The way I solved the problem was to create <a href="http://httpd.apache.org/docs/1.3/vhosts/name-based.html">name-based virtual host</a> for each of the servers.<br />
our example would look like</p>
<p><code><br />
#you can listen on specific ports for requests if you like<br />
#(ex->Listen 192.168.1.102:80)<br />
#I use the below statement to listen on 80 for all requests<br />
Listen *:80<br />
#Because we have multiple names mapped to same ip<br />
NameVirtualHost 192.168.1.102:80</p>
<p>&lt;VirtualHost 192.168.1.102:80 &gt;<br />
ServerName www.reallycoolsite.com<br />
ProxyRequests Off<br />
ProxyPass / http://10.15.22.1/<br />
ProxyReverse / http://www.reallycoolsite.com/<br />
ProxyPreserveHost  On<br />
ErrorLog                 reallycoolsite_error_log<br />
<a href="http://httpd.apache.org/docs/2.0/mod/mod_log_config.html#customlog">CustomLog</a> reallycoolsite_access_logs<br />
&lt;/VirtualHost &gt;</p>
<p>&lt;VirtualHost 192.168.1.102:80 &gt;<br />
ServerName www.justcoolsite.com<br />
ProxyRequests Off<br />
ProxyPass / http://10.15.22.2/<br />
ProxyReverse / http://www.justcoolsite.com/<br />
ProxyPreserveHost  On<br />
ErrorLog                 justcoolsite_error_log<br />
<a href="http://httpd.apache.org/docs/2.0/mod/mod_log_config.html#customlog">CustomLog</a> justcoolsite_access_logs<br />
&lt;/VirtualHost &gt;</p>
<p>&lt;VirtualHost 192.168.1.44:80 &gt;<br />
ServerName www.reallylamesite.com<br />
ProxyRequests Off<br />
ProxyPass / http://10.15.22.3/<br />
ProxyReverse / http://www.reallylamesite.com/<br />
ProxyPreserveHost  On<br />
ErrorLog                 reallylamesite_error_log<br />
<a href="http://httpd.apache.org/docs/2.0/mod/mod_log_config.html#customlog">CustomLog</a> reallylamesite_access_logs<br />
&lt;/VirtualHost &gt;<br />
</code></p>
<p>If you receive errors during the communication of your proxy and your server, it may be a good idea to investigate if you have an http protocol error discussed at the bottom of this <a href="http://httpd.apache.org/docs/2.0/mod/mod_proxy.html">page</a><br />
The following two lines are pulled from the reference and fixed a problem I had with one of my IIS servers using SSL(for more info about the issue, go <a href="http://support.microsoft.com/kb/187504">here</a><br />
<strong><br />
SetEnv force-proxy-request-1.0 1<br />
SetEnv proxy-nokeepalive 1<br />
</strong><br />
My apache configuration file(httpd.conf) was the file I used to edit my settings.. Your file may be different depending on how new your apache version is. I found that some implementations called the configuration file apache.conf&#8230;. I hope this blog entry is helpful you, Happy Configuring!</p>
]]></content:encoded>
			<wfw:commentRss>http://javazquez.com/juan/2008/08/16/proxyreverseproxy-and-apache2/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
