Archive for the ‘ Languages ’ Category

HtmlUnit : GUI Java Less browser

HtmlUnit – Welcome to HtmlUnit.

HtmlUnit is a “GUI-Less browser for Java programs”. It models HTML documents and provides an API that allows you to invoke pages, fill out forms, click links, etc… just like you do in your “normal” browser.

It has fairly good JavaScript support (which is constantly improving) and is able to work even with quite complex AJAX libraries, simulating either Firefox or Internet Explorer depending on the configuration you want to use.

It is typically used for testing purposes or to retrieve information from web sites.

Sending email with ruby – TMail

http://yakinikunotare.boo.jp/orebase/index.php?Ruby/TMail
http://tmail.rubyforge.org/rdoc/classes/TMail/Mail.html

Simple email sending:

require 'NET / SMTP'
require 'TMail'
require 'base64'
 
Mail = TMail:: Mail.new
 
Mail.to = 'you@gmail.com'
Mail.from = 'me@gmail.com'
Mail.subject = 'Test Mail '
Mail.date = Time.now
Mail.Mime_Version = '1 .0 '
Mail.Set_Content_Type 'text', 'plain', {'charset'=>'UTF-8'}
Mail.Body = 'This is Test Mail . '
 
Net:: SMTP.start("smtp.yourhost.com", 587, "smtp.yourhost.com", "username", "password") do | SMTP | SMTP.sendmail(Mail.encoded, Mail .from, Mail.to)
end

Send attachments:

require 'NET / SMTP'
require 'TMail'
require 'base64'
 
# object
Mail = TMail:: Mail.new
 
Mail.to = 'you@gmail.com'
Mail.from = 'me@gmail.com'
Mail.subject = 'Test Mail'
Mail.date = Time.now
Mail.Mime_Version = '1 .0 '
Mail.Set_Content_Type 'multipart', 'mixed', {"boundary" => "Somethingspecial"}
 
# body
Mail_Body = TMail:: Mail.new
Mail_Body.Set_Content_Type 'text', 'plain', {'charset'=>'UTF-8'}
Mail_Body.Body = 'Ge almost'
Mail.Parts.push(@ Mail_Body)
 
# Attachments
Attach = TMail:: Mail.new
Attach.Body = Base64.Encode64 File.Open('foo.jpg', "rb").read
Attach.Set_Content_Type 'image','jpg','name'=>'foo.jpg'
Attach.Set_Content_Disposition ' Attachment ','filename'=>'foo.jpg'
Attach.transfer_encoding = 'base64'
 
# attach
Mail.Parts.push(Attach)
 
# send
Net:: SMTP.start("smtp.yourhost.com", 587, " smtp.yourhost.com ", "username", "password") do | SMTP | SMTP.sendmail(Mail.encoded, Mail.from, Mail.to)
end

Avoid race condition for file creation

race condition in the common lock on file? – Stack Overflow.

A possible solution to this is to use IO redirection and bash’s noclobber mode, which won’t redirect to an existing file. We can use something similar to:

if ( set -o noclobber; echo "$$" > "$lockfile") 2> /dev/null;
then
   # BK: this will cause the lock file to be deleted in case of other exit
   trap 'rm -f "$lockfile"; exit $?' INT TERM EXIT

   # critical-section BK: (the protected bit)

   rm -f "$lockfile"
   trap - INT TERM EXIT
else
   echo "Failed to acquire lockfile: $lockfile."
   echo "Held by $(cat $lockfile)"
fi