Archive

Posts Tagged ‘Groovy’

Windows GUI File Parser using Groovy

April 18th, 2009

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)

Groovy, Windows, code, java , , , ,

A Groovy Flickr API

March 30th, 2009

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 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. Also, here is a link to a text file with the below code for an easier way to view the source.

import java.io.IOException
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.util.ArrayList
import java.util.Date
import java.util.Hashtable
import javax.imageio.ImageIO
import org.w3c.dom.Element
import org.w3c.dom.NodeList
import java.io.File;
import java.net.*;
import java.io.IOException;
import org.xml.sax.SAXException;
public class FlickrAPI {
String nsid = ""

private String secret = "your secret"

/**
* api key
*/
private String akey = "your key goes here"

private String sig = ""

private String url = ""

String authToken = ""

private String frob = ""

private String restString = "http://flickr.com/services/rest/?method="

public FlickrAPI() {
println("Created FlickerAPI")
}

public void authNewUser() {
constructFrobUrl()
createAuthURL()
getToken()
}
private String constructUrl(String flickrMethod,Map m,boolean authCall =false){
String s= this.restString+flickrMethod+"&api_key="+this.akey
m.each{key,value->
s+=key+value
}
if(authCall){s+="&auth_token=${this.authToken}&api_sig=${this.sig}"}
return s
}
def mapFlickrUser(){

}
//if bool is true then this is a Authenticated call
public void setSig(String method,boolean bool = false){
String sigString="${this.secret}api_key${this.akey}"
try {
if(bool){
sigString +="auth_token${this.authToken}${method}"
println "Sig is true"
}else{sigString+=method}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace()
}
println "sig is " +sigString
this.sig = calcMD5(sigString)
}

def jupload(String filePath,Map parameters=[:]){
println("parameters ${parameters.inspect()}")
def paramMessages=[]
int paramLength=0

if(parameters==[:]){
this.sig = calcMD5("${this.secret}api_key${this.akey}auth_token${this.authToken}")
}else{
//sort them and add them to the signature
String p=""
parameters.keySet().toList().sort().each{key->
//if the key ='tags' make it into space separated string
p+= "${key}${parameters[key]}"
paramMessages.add(addParameter([key,parameters[key]]) )
}
this.sig = calcMD5("${this.secret}api_key${this.akey}auth_token${this.authToken}${p}")
paramMessages.each{stringMsg->paramLength+=stringMsg.length()}
}

File file=new File(filePath)
String CrLf = "\r\n";
def url = new URL("http://api.flickr.com/services/upload/")
//def connection = url.openConnection()
HttpURLConnection conn = url.openConnection()
def is = new FileInputStream(file)
def flength= file.length()
byte[] imgData= new byte[(int)flength]

int offset = 0;
int numRead = 0;
while (offset < imgData.length && (numRead=is.read(imgData, offset, imgData.length-offset)) >= 0) {
offset += numRead;
}

// Ensure all the bytes have been read in
if (offset < imgData.length) {
throw new IOException("The file was not completely read: "+file.getName());
}
println "filesize ->${imgData.length}"
// Close the input stream, all file contents are in the bytes variable
is.close();
String message01=addParameter(['api_key',this.akey])
String message02 = addParameter(['auth_token',this.authToken])
String message03 = addParameter(['api_sig',this.sig])

String message1 = "";
message1 += "---------------------------6d72u458s1587" + CrLf;
message1 += "Content-Disposition: form-data; name=\"photo\"; filename=\""+filePath+"\"" + CrLf;
message1 += "Content-Type: image/jpeg" + CrLf;
message1 += CrLf;

// the image is sent between the messages in the multipart message.

String message2 = "";
message2 += CrLf + "---------------------------6d72u458s1587--" + CrLf;

def totalLength = String.valueOf((message01.length() + message02.length() + message03.length() + message1.length() + message2.length() + imgData.length+ paramLength))
conn.setRequestMethod("POST")
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=-------------------------6d72u458s1587");
conn.setRequestProperty("Host", "api.flickr.com");
conn.setRequestProperty("Content-Length",totalLength );
conn.setDoOutput(true)

System.out.println("open os");
def os = conn.getOutputStream();

System.out.println(message01);
os.write(message01.getBytes());

System.out.println(message02);
os.write(message02.getBytes());
//write the params here before the image
paramMessages.each{msg->os.write(msg.getBytes())}

System.out.println(message03);
os.write(message03.getBytes());

System.out.println(message1);
os.write(message1.getBytes());
os.write(imgData,0 ,imgData.length)

os.write(message2.getBytes());

println "end writing"
os.flush()
os.close()

conn.connect()
conn.disconnect()
println conn.content.text

}
//[name value]
private String addParameter(List para){
String CrLf = "\r\n";
String message01 = "";
message01 += "---------------------------6d72u458s1587" + CrLf;
message01 += "Content-Disposition: form-data; name=\"${para[0]}\"" + CrLf;
message01 += CrLf;
message01 += para[1] + CrLf;
return message01
}

public void constructFrobUrl() {
setSig("methodflickr.auth.getFrob")
this.url = "http://flickr.com/services/rest/?method=flickr.auth.getFrob&api_key=${this.akey}&api_sig=${this.sig}"
println("here is url-> ${this.url}")
def node = new XmlParser().parse(this.url)//dom.parseXML("frob")
this.frob = node['frob'].text().toString()
println("frob =>${this.frob}\n\n")
}

/**
* This function will calculate an MD5 sum of String Signature and return
* the String value of the Hash via strBuildup
*
* @param signature
* @throws NoSuchAlgorithmException
* @returns strBuildup
*/
private String calcMD5(String signature) throws NoSuchAlgorithmException {
// get Instance from Java Security Classes
String strBuildup = ""
MessageDigest md5 = MessageDigest.getInstance("MD5")
byte[] md5summe = md5.digest(signature.getBytes())
for (int k = 0; k < md5summe.length; k++) {
byte b = md5summe[k]
String temp = Integer.toHexString(b & 0xFF)
/*
* toHexString has the side effect of making stuff like 0x0F only
* one char F(when it should be '0F') so I check the length of
* string
*/
if (temp.length() < 2) {
temp = "0" + temp
}
temp = temp.toUpperCase()
strBuildup += temp
}
return strBuildup
}

/**
* get the authentication token
*
* @return
*/
public checkToken(){
setSig("methodflickr.auth.checkToken",true)
this.url=constructUrl('flickr.auth.checkToken',[:],true)
println(this.url)
def node = new XmlParser().parse(this.url)
println("done parsing check Token INFO ===>${node.children()}")
}
public void getToken() {
println("Entering getToken\n\n")
setSig("frob${this.frob}methodflickr.auth.getToken")
this.url = "${this.restString}flickr.auth.getToken&api_key=${this.akey}&frob=${this.frob}&api_sig=${this.sig}"
//println(this.url)
def node = new XmlParser().parse(this.url)
//need to get the nsid and the authtoken
this.authToken = node['auth']['token'].text()
this.nsid = node['auth']['user'].'@nsid'.text()
println "token is ${this.authToken}"
println("Token =>${node['auth']['token'].text()}")
println("nsid =>${node['auth']['user'].'@nsid'.text()}")
println("perms =>${node['auth']['perms'].text()}")

// set user nsid
println("Exiting GET Token")
}

public void createAuthURL() {
setSig("frob${this.frob}permsdelete")
String cmd = "open http://flickr.com/services/auth/?api_key="+ this.akey + "&perms=delete" + "&frob=" + this.frob + "&api_sig=" + this.sig
try {
Process proc = cmd.execute()
proc.waitForOrKill(10000)
sleep(2000)
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace()
}
}

/***************************************************************************
* AUTH
**************************************************************************/
/***************************************************************************
* ACTIVITIES
**************************************************************************/
//POLL ONLY ONCE AN HOUR!!!!!
public activityGetUserComments(){
setSig("methodflickr.activity.userComments",true)
this.url=constructUrl('flickr.activity.userComments',[:],true)
println(this.url)
def node = new XmlParser().parse(this.url)
println("done parsing GET user Comments INFO ===>${node.children()}")
}
/***************************************************************************
* BLOGS
**************************************************************************/
/***************************************************************************
* CONTACTS
**************************************************************************/
public void contactsGetList(){
setSig("methodflickr.contacts.getList",true)
this.url=constructUrl('flickr.contacts.getList',[:],true)
println(this.url)
def node = new XmlParser().parse(this.url)
println("done parsing GET contact List INFO ===>${node.children()}")
}
/***************************************************************************
* FAVORITES
**************************************************************************/
/***************************************************************************
* GROUPS
**************************************************************************/
/***************************************************************************
* GROUP POOLS
**************************************************************************/

/***************************************************************************
* INTERESTINGNESS
**************************************************************************/

/***************************************************************************
* PHOTOS
*what if a return back an array of pictures?
**************************************************************************/
def photosGetNotInSet(){
List piclist=[]
setSig("methodflickr.photos.getNotInSet",true)
this.url=constructUrl('flickr.photos.getNotInSet',[:],true)
println(this.url)
def node = new XmlParser().parse(this.url)
println("done parsing GET Not in Set INFO ===>${node.children()}\n\n\n")
/* test=f.photosGetNotInSet()
println test.photos.each{it-> it.each{p-> println p}} //list of nodes

test.photos.photo[3].attributes()
test.photos.photo.each{it-> println it.attribute('isfamily')} //gets the individual attr
test.photos.photo.each{it-> picList.push(new Picture(it))} //push a node into picture contructor

*/

return node
}

def photosGetContactsPhotos(){
setSig("methodflickr.photos.getContactsPhotos",true)
this.url=constructUrl('flickr.photos.getContactsPhotos',[:],true)
def node = new XmlParser().parse(this.url)
return node
}

def photosGetRecentlyUploaded() {
setSig("methodflickr.photos.getRecent",true)
//this.url = "flickr.photos.getRecent&api_key",[:],true)
this.url= constructUrl('flickr.photos.getRecent',[:],true)
def node = new XmlParser().parse(this.url)
println("done parsing RecentPhotos ===>${node.children()}")
return node
}
public void photosGetInfo(){

}
/***************************************************************************
* PEOPLE
**************************************************************************/
def contactsGetList(){
setSig("methodflickr.contacts.getList",true)
this.url=constructUrl('flickr.contacts.getList',[:],true)
def node = new XmlParser().parse(this.url)
//println("done parsing GET contact List INFO ===>${node.children()}")
return node
}
def peopleGetUploadStatus(){
setSig("methodflickr.people.getUploadStatus",true)
this.url=constructUrl('flickr.people.getUploadStatus',[:],true)
def node = new XmlParser().parse(this.url)
println("done parsing GET upload Status INFO ===>${node.children()}")
return node
}
def peopleGetPublicPhotos() {
setSig("methodflickr.people.getPublicPhotosuser_id${this.nsid}",true)
this.url=constructUrl('flickr.people.getPublicPhotos',['&user_id=':"${this.nsid}"],true)
def node = new XmlParser().parse(this.url)
//def peepsInfo = node['auth']['peeps'].text()
println("done parsing GET Public Photos ===>${node.children()}")
return node
}
def peopleGetPeopleInfo() {
setSig("methodflickr.people.getInfouser_id${this.nsid}",true)
this.url=constructUrl('flickr.people.getInfo',['&user_id=':"${this.nsid}"],true)
def node = new XmlParser().parse(this.url)
//def peepsInfo = node['auth']['peeps'].text()
return node
}

/********************************************
* photosets
************************/
def photosetsGetList(String uid){
setSig("methodflickr.photosets.getListuser_id${uid}",true)
this.url=constructUrl('flickr.photosets.getList',['&user_id=':"${uid}"],true)
def node = new XmlParser().parse(this.url)
//def peepsInfo = node['auth']['peeps'].text()
return node

}
def photosetsGetPhotos(String setID){
setSig("methodflickr.photosets.getPhotosphotoset_id${setID}",true)
this.url=constructUrl('flickr.photosets.getPhotos',['&photoset_id=':"${setID}"],true)
println this.url
def node = new XmlParser().parse(this.url)
//def peepsInfo = node['auth']['peeps'].text()
return node

}
/**
Upload photos

http://api.flickr.com/services/upload/

*/
//get the picture when supplied the proper args
//http://farm{farm-id}.static.flickr.com/{server-id}/{id}_{secret}_[mstb].jpg

public String getPicture(String farmId, String serverId, String photoid, String secret,String size ="s"){
return "http://farm${farmId}.static.flickr.com/${serverId}/${photoid}_${secret}_${size}.jpg"

}

Groovy, code, java , , , , , , , ,

Adding and Resizing Images with Grails

January 24th, 2009

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>

Grails, Groovy, code , , , , , ,

Mergesort and Quicksort with Dynamic Languages

January 3rd, 2009

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..


# 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])


Erlang, Groovy, Ruby, code, python , , , , , , , , , , ,

Recursive Directory Search with Ruby and Groovy

November 6th, 2008

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’t think of anything that would be a fun project to do…until this crazy idea hit me.  Wouldn’t it be cool if could generate multiple threads to search different servers for any file of my choosing?” The code I wrote doesn’t directly do this, but with some minor tweaks it could be done.

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 :D

Ruby code
 

#########################
#  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) &&
                                          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}"

Groovy Code

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}")


 

 

Groovy, Ruby, code , ,

Rotating Java Images

July 11th, 2008

I am working on a swing flickr app and thought I would share some code to help those that are new to java gui programming( like me) and get them on their way to making their killer application.

I’ll start off with my first problem,  “How do I show an Image?” After looking through Java forums and going through my Java books, I settled on using Image Icons in JLabels. The next thing I wanted to do was rotate the image 90 degrees. I used Java’s Graphics class to accomplish this. The following groovy code loads 100 JLabels containing a JPEG of Pixar’s Wall-e that I had in the same directory rotated 90 degrees.

import java.awt.image.BufferedImage
import javax.swing.*
import java.awt.*;
import java.util.*;
import java.awt.image.AffineTransformOp
import java.awt.geom.AffineTransform

class ImageButton extends JLabel{
	ImageIcon picture

public ImageButton(ImageIcon icon){
	super(icon)
	this.setBackground(Color.BLACK)
	this.setForeground(Color.BLACK)
	this.picture=icon
	this.setPreferredSize(new Dimension(120,100))
}

public void rotateImage( int angle) {
	int w = this.picture.getImage().getWidth()
	int h = this.picture.getImage().getHeight()
	BufferedImage bi = new BufferedImage(w,h,
                      BufferedImage.TYPE_INT_RGB)
	Graphics bg = bi.createGraphics();
	bg.rotate(Math.toRadians(angle), w/2, h/2);
	bg.drawImage(this.picture.getImage(),0,0,w, h,
			0,0,w, h, null);

	bg.dispose()//cleans up resources
	this.setIcon(new ImageIcon(bi))
	this.setPreferredSize(new Dimension(this.picture.getIconHeight(),
                       this.picture.getIconWidth()))
	}
}

JFrame f= new JFrame()
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
JPanel panel=new JPanel();
def img= new ImageIcon("walle.jpg")
(1..100).each{i->
	def btn=new ImageButton(new ImageIcon(img.getImage()
                        .getScaledInstance(120,100,4)))
	panel.add(btn)
	btn.rotateImage(90)//rotate the image now
	println i
}

panel.setBackground(Color.BLACK)

f.setSize(300,400)
f.getContentPane().add(panel)
f.setVisible(true)

 

My first few attempts at the code gave me out of memory Heap errors. I unknowingly had BufferedImage references hanging around.  Once I realized this, I cleaned up my code and remembered to call dispose() on the graphics bg object and everything came together quite nicely.

Groovy, code, java ,

File I/O Part 1

June 27th, 2008

I love to learn and try new languages. Not only is learning a new language fun, many times it teaches me something new about a language that I am already familiar with. The only problem that I have with learning so many languages, is keeping them straight. I decided that I would take a few of the dynamic languages I use most often and compile a list of how to handle File I/O with each of them. If you have a Dynamic language(part 2 of this post will be on static languages) not represented below or have another method of File I/O with the represented languages, please add to the list with its respective File I/O code:D
Without further ado…

//Groovy open file for writing
def target ="filename"
File wf= new File(target)
wf.write( "I am in your file eating your space" )

//Groovy open file for appending
def target ="filename"
File af= new File(target)
af.append("I have all of your base")

//Groovy read each line in file
new File("filename").eachLine{line-> println line}

//Groovy read whole document and put into List

List lines = new File("filename").readLines()
//lines contains two lines that we need
println "first line  $lines[0]"
println "second line $lines[1]"

//Groovy reading one line
File rf= new File("filename") //open for reading
//read first line, trim, assign to tmp
rf.withReader { line ->tmp = line.readLine().trim()}

//Groovy test if file exists
File src = new File(srcFile)
if (src.exists() ){ println "I exist"}
else{println "I don't exist"}

#Ruby openfile for reading
fh = File.new(path, "r")  # open file "path" for reading only
fh.close

#Ruby open file for writing
fout   = File.new(path, "w")  # open file "path" for writing only
fout.puts "Up, Up, Down, Down, Left, Right, Left, Right, B, A, Select, Start"
fout.close

#Ruby open file for apending
fa= File.new("DeleteMe.txt","a")
fa.puts "I am at the end of file"
fa.close

#Ruby read eachline in a file
File.open("file").each { |line| p line}

#Ruby read entire file to string
fh = File.new(filename)
str = fh.read

#Ruby read entire file into array(each line is an element in the array)
fh = File.new(filename)
str = fh.readlines

#Python Write a file
fout = open("DeletMe.txt", "w")
fout.write("Writing to fout\nCheck it out!")
fout.close()

#Python Read an entire file
fin = open("ReadingTest.txt", "r")
fin_text =  fin.read()
fin.close()
print fin_text

#Python read entire file into list
fin = open("ReadingTest.txt", "r")
txt= fin.readlines()
fin.close()
print txt[0]

#Python append to a file
fh= open ( 'DeleteMe.txt', 'a' )
fh.write ( '\n\n\nBottom line.' )
fh.close()

#Perl reading a file
open(FILE,  '<', $file) or die "Can't read $file: $!\n";
while(<FILE>)
{
print ;
}

#Perl append to a file
open(FILE, '>>', $file) or    die "Can't append to $file: $!\n";
print FILE "text";
close(FILE);

#Perl read and write to a file
#+< allows reading and writing, and keeps the data that was
#already in the file.  open() will fail if file doesn't exist.
open(FILE, "+<$file" ) or die ("Can't  read|write: $file\n");
close(FILE);

#Perl read and write to a file
#+>allows writing and reading, but replaces/overwrites the
#data in the file if the file exists. Creates it if it doesn't exist.
open(FILE, "+>$file" ) or die ("Can't write or read:$file \n");

close(FILE);

PHP code doesn’t display properly within WordPress, so here is an image of the code

PHP File I/O

Linux, Ruby, code, perl, php, python , , , , ,