Showing posts with label perl. Show all posts
Showing posts with label perl. Show all posts

06 March 2012

Uploading file using Dojo and CGI AJAX

Sample Html file: (upload.html)

<html>
    <title>Upload file </title>
    <link href="/css/sitestyles.css" rel="stylesheet" type="text/css"/>
    <link rel="stylesheet" type="text/css" href="/js/dojo/dojo/resources/dojo.css"/>
    <link rel="stylesheet" type="text/css" href="/js/dojo/dijit/themes/tundra/tundra.css"/>
    <script type="text/javascript" src="/js/dojo/dojo/dojo.js" djConfig="parseOnLoad: true"></script>

    <script type="text/javascript">
    dojo.require("dijit.form.Form");
    dojo.require("dijit.form.Button");
    dojo.require("dojox.form.FileUploader");
    dojo.require("dijit.form.Button");
    dojo.require("dojo.parser");

    //using this early for the forceNoFlash test:
    dojo.require("dojox.embed.Flash");

    // Function to upload the file to server
    function doUpload () {
        var f0 = dijit.byId('btn0');
        console.log("doUpload")
        dojo.byId("fileToUpload").innerHTML = "uploading...";

        // If we want to send other fields along with the file
        // use submit method other use simple f0.upload() method
            f0.submit(dijit.byId('logoForm').domNode);
    }

    dojo.addOnLoad(function() {
        var f0 = dijit.byId('btn0');
       
        // Show file selected in div
        // data contains list of files selected
        dojo.connect(f0, "onChange", function(data){
        console.log("DATA:", data);
        var n = dojo.byId('fileToUpload');
        n.innerHTML = "";
        dojo.forEach(data, function(d){
            n.innerHTML += d.name
        });
        });

        // When file upload is in progress
        // Showing status inprogress
        dojo.connect(f0, "onProgress", function(data){
        console.warn("onProgress", data);
        var n = dojo.byId('fileToUpload');
        n.innerHTML = 'Uploading file';
        });

        //
        // Show the uploaded image
        // on successful upload of image
        //
        dojo.connect(f0, "onComplete", function(data){
        console.log("Uploaded file");
        var uf = dojo.byId('fileToUpload');
        var d = data[0];
        if ( d.status == "0" ) {
            uf.innerHTML = "<img src='" + data[0]['file'] + "'/>";
        } else {
            uf.innerHTML = d.message;
        }
        console.log(data);
        });
    });
    </script>

<body class='tundra'>
<center>

    <!-- Will show the status of file upload -->
    <table border='1' width='30%'>
    <tr>
    <td align='center'>
    <div id="uploadedFile"></div>
    <br>

    <!-- Other data to send to server along with file -->
    <form id='logoForm' dojoType='dijit.form.Form' accept="image/gif,image/jpeg">
        <div class='disabled'>
        <input name='action' value='upload' type='input'>
        </div>
    </form>
    <br>
    <!-- Show uploaded file -->
    <div id="fileToUpload"></div>
    <br>
    <!-- File uploader dijit -->
    <div id="btn0"
        dojoType="dojox.form.FileUploader"
        force="html"
        uploadOnChange=false isdebug=true htmlFieldName=orglogo
        uploadUrl="/sampleapp/upload-file" >
        Browse
    </div>
    <br>
    <div dojoType='dijit.form.Button' label='Upload' onClick='doUpload()'></div>
    <br>
    <br>
    </td>
    </tr>
    </table>
</center>
</body>
</html>


HTML tag


div id btn0 is File upload dijit with following properties :
force="html" if "html" html file uploader is used to upload file.
To use flash uploader set to "flash"

uploadOnChange=false If true selected file will be uploaded as soon as selected.

htmlFieldName=orglogo Name of html field under which the file-content to send

uploadUrl="/sampleapp/upload-file" Upload URL


Java script function:

dojo.connect(f0, "onChange", function(data){
});


Function used to display the selected file. This function will be called when file
browser dialoug is opened and we select a file. data will look like
[{ name="icon-server.png", size=0}]

dojo.connect(f0, "onProgress", function(data){
})

Function will be called when file uploading is in progress data will contain the
list of files. data will look like
[{bytesLoaded=1, bytesTotal=1, name="icon-server.png", percent=100, size=0, type=""}]

dojo.connect(f0, "onComplete", function(data){
})

Function will be called with server finishes the file process. It doesn't mean
successful file upload. You need send correct message and need to check from
data. data will look like
[{ status=0, file="/var/tmp/icon-server.png"}]

Server should send response in following format only and the should set header
Content-type: text/html.

Response format for success
<textarea>{"status":0,"file":"/var/tmp/a.xcf","message":null}</textarea>

Response format for error
<textarea>{"status":1,"file":"/var/tmp/a.xcf","message":"Invalid file format"}</textarea>

Response should be written in "textarea" tag

To send other form fields along with file use
var formdomNode = dijit.byId("logoForm").domNode;
dijit.byId("btn0").submit(formdomNode)


If you don't want any other field to send along file use
dijit.byId("btn0").upload() method


Sample server side code using Perl CGI
upload-file cgi


#!/usr/bin/perl -w

use strict;

use CGI;
my $result = {status => 1};

my $cgi = new CGI;
my $action = $cgi->param('action');

print "Content-type: text/html \n\n";

if ($action eq "upload") {

    #
    # Set MAX max upload limit
    #
    $CGI::POST_MAX = 1024 * 5000;


    my $msg;
    my $status = 0;
    my $INTERNAL_ERR = "Internal error";

    # What is field having file contain
    my $fieldname = 'orglogo0';
    my $filename = $cgi->param($fieldname);
    if (! $filename) {
    $msg = "File size exceded";
    }

    # Get file upload handle
    my $upload_filehandle = $cgi->upload($fieldname);
    my $uploadfilepath = "/var/tmp/$filename";

    # Write the file to disk
    if (open(UPLOADFILE, ">$uploadfilepath")) {
    if (! binmode UPLOADFILE)  {
        $msg = $INTERNAL_ERR;
    } else {
        while (<$upload_filehandle>) { 
        print UPLOADFILE;
        } 
        unless (close UPLOADFILE) {
        $msg = $INTERNAL_ERR;
        }
    }
    } else {
    $msg = $INTERNAL_ERR;
    }

    if ($msg) {
    $status = 1;
    }

    # Send status to client
    my $out = {
        file => $uploadfilepath,
        status => $status, 
        message => $msg
        };

    #
    # To handle cross platform problem dojo need the response in following format.
    # Reference: http://dojotoolkit.org/reference-guide/dojox/form/FileUploader.html
    #
    print "<textarea>". JSON::to_json ($out)."</textarea>";
    exit 0;

}

$result->{message} = "command not found";
print "<textarea>" . JSON::to_json($result) . "</textarea>"; 



17 June 2011

Getting select query result from DB2 database using perl script


First Install following modules

1. DBI
2. DBD (DB2 Database module)

Use following script to connect to database and fetch the rows from required table.


#!/usr/bin/perl
use strict;
use DBI;

# Open a connection
my $dbh = DBI->connect('dbi:DB2:DATABASE_NAME',
        "DB_USERNAME", "DB_PASSWORD", {RaiseError => 1}) or 

        die "can not connect to database" . $dbh->errstr;

my $stmt = "SELECT * FROM TABLE_NAME";


# Prepare query
my $sth = $dbh->prepare($stmt) or die "Can not prepare statement" . $dbh->errstr;


# Execute Query

my $x = $sth->execute() or  die "Cannot execute: " . $sth->errstr;


# Fetch result
while (my $hash = $sth->selectrow_hashref) {
    print $hash;
}


selectrow_hashref will contain the columname => value pairs for each row.

Removing a perl module


Use following script to remove the Installed perl module.

#!/usr/bin/perl

use ExtUtils::Packlist;
use ExtUtils::Installed;

$ARGV[0] or die "Usage: $0 Module::Name\n";

my $mod = $ARGV[0];

my $inst = ExtUtils::Installed->new();

foreach my $item (sort($inst->files($mod))) {
         print "removing $item\n";
         unlink $item;
}

my $packfile = $inst->packlist($mod)->packlist_file();
print "removing $packfile\n";
unlink $packfile;




Save above script as u.pl
# chmod +x u.pl

Running script 
# ./u.pl

e.g.
# ./u.pl 'Date::Manip'

It will remove the package Date::Manip

24 May 2011

Getting IP location (city, country) using perl Geo::IP

Geo::IP module a simple file-based database. This database simply contains IP blocks as keys, and countries as values.  The data contains all public IP addresses and should be more complete and accurate than reverse DNS lookups. This module can be used to automatically select the geographically closest mirror, or to analyze your web server logs, or to determine the countries of your visitors.

To find a country for an IP address, this module uses the database contained in /usr/local/share/GeoIP/GeoIP.dat to find a Network that contains the IP address.


Installing Geo::IP module:

# wget http://www.maxmind.com/download/geoip/database/GeoIP.dat.gz
# gunzip GeoIP.dat.gz
# mv GeoIP.dat /usr/local/share/GeoIP/GeoIP.dat


Download Geo-IP-PurePerl-1.17.tar from
http://geolite.maxmind.com/download/geoip/api/pureperl/
now extract it using
# tar -xvf Geo-IP-PurePerl-1.17.tar


now install the module using following the steps
# perl Makefile.PL
# make
# make test
# make install


Sample Code to get IP to location:
#!/usr/bin/perl
use strict;

use Geo::IP::PurePerl;
my $addr = shift;

my $gi = Geo::IP::PurePerl->new("/usr/local/share/GeoIP/GeoLiteCity.dat", GEOIP_STANDARD);

if ($addr){
  my ($country_code,
          $country_code3,
          $country_name,
          $region,$city,
          $postal_code,
          $latitude,
          $longitude,
          $dma_code,
          $area_code) = $gi->get_city_record($addr);

  print $country_code  . "\n";
  print $country_code3 . "\n";
  print $country_name  . "\n";
  print $region        . "\n";
  print $city          . "\n";
  print $postal_code   . "\n";
  print $latitude      . "\n";
  print $longitude     . "\n";
  print $dma_code      . "\n";
  print $area_code     . "\n";
} else {
  print STDERR "Usage: $0 ipaddr\n";
  exit;
}


save it as ipdetails.pl
#chmod +x ipdetails.pl


run the script
# ./ipdetails.pl 122.177.211.119

sample output:
IN
IND
India
07
Delhi

28.6667
77.2167

29 March 2011

Generating random IP, String, Hash key, Array Element in perl

Getting a random key from hash:

my $hash = {
           key1 => 'val1',
           key2 => 'val2',
           key3 => 'val3'
        };

print "\n Random key from hash : " . randomKey($hash);

sub randomKey
{
    my $hashRef = shift;
    my @keyArray = keys %$hashRef;
    my $randVal = $keyArray[rand @keyArray];
    return $randVal;
}



Getting a random element from array:

my @array = qw(element1 element2 element3);
print "\n Random element from array : " .randomElement(\@array);

sub randomElement
{
    my $keyArray = shift;
    my $arrLen = scalar @$keyArray -1;
    my $randNum = int(rand($arrLen));
    return $keyArray->[$randNum];
}


Generating a random IP address:

print "\n Random IP address: " . getRandomIP();

sub getRandomIP
{
    return join ".", map int rand 256, 1 .. 4;
}



Generating a random Session ID:

print "\n Random Session ID : " . getRandomSessionID();

sub getRandomSessionID
{
    return sprintf("%0.8x",rand()*0xffffffff);
}


Generating a random string

print "\n Random string of 15 chars : " . getRandomString(15);

sub getRandomString
{
    my $len = shift;
    my @chars=('a'..'z','A'..'Z','0'..'9');
    my $random_string;
    foreach (1..$len) {
    $random_string.=$chars[rand @chars];
    }
    return $random_string;
}

23 December 2010

Fetching and Decoding Mails in Perl

Fetching Mails using Mail::IMAPClient and parsing mail Using MIME::Parser

Requisite:
Before running the sample script please install the following modules from CPAN
Mail::IMAPClient
MIME::Parser
Data::Dumper

Sample Code:


#!/usr/bin/perl -w

# Always be safe
use strict;
use warnings;

# Use the module
use Mail::IMAPClient;
use MIME::Parser;
use Data::Dumper;

use constant {
MULTIPART => "MULTIPART",
TEXT => "TEXT"
};

my $imap = Mail::IMAPClient->new(
Server => 'localhost',
User => 'user',
password => 'password',
Port => 143,
Ssl=> 0,
Uid=> 1,
# FOR SSL
#Server => 'imap.gmail.com',
#User => 'user',
#Password => "password",
#Port => 993,
#Ssl => 1,
#Uid => 0,
) or die "IMAP Failure: $@";

$imap->select("INBOX") or die "IMAP Select Error: $@";
foreach my $box qw( INBOX ) {
# How many msgs are we going to process
print "There are ". $imap->message_count($box). " messages in the $box folder.\n";
# Select the mailbox to get messages from
$imap->select($box) or die "IMAP Select Error: $@";

# Store each message as an array element
my @msgseqnos = $imap->messages() or die "Couldn't get all messages $@\n";

# Loop over the messages and store in file
foreach my $seqno (@msgseqnos) {
my $parser = MIME::Parser->new;
my $entity = $parser->parse_data($imap->message_string($seqno));
my $header = $entity->head;
my $from = $header->get_all("From");
my $msg_id = $header->get("message-id");
my $to = $header->get_all("To");
my $date = $header->get("date");
my $subject = $header->get("subject");
print "From: ". Dumper($from);
print "Message-id: $msg_id";
print "To: $to";
print "Date: $date";
print "Subject: $subject";
my $content = split_entity($entity);
#$entity->purge();
print "Content: $content";
}

# Expunge and close the folder
$imap->expunge($box);
$imap->close($box);
}

# We're all done with IMAP here
$imap->logout();


sub split_entity
{
my $entity = shift;
my $num_parts = $entity->parts; # how many mime parts?
if ($num_parts) { # we have a multipart mime message
foreach (1..$num_parts) {
split_entity( $entity->parts($_ - 1) ); # recursive call
}
} else { # we have a single mime message/part
if ($entity->effective_type =~ /^text\/plain$/ || $entity->effective_type =~ /text\/html$/) { # text message
print "Part Content: " . $entity->bodyhandle->as_string;
} else { # no text message
return handle_other($entity->bodyhandle);
}
}
}

sub handle_other()
{
my $handle = shift;
my $path = $handle->path;
print "\n Path : $path";
}


21 July 2010

Perl: Finding MD5 checksum of files recusrsivly in directory



#! /usr/bin/perl -w
use strict;
use Digest::MD5 qw(md5_base64);
use constant SUCESS => 0; # Code for succesful execution.
use constant ERROR => 1; # Code for error in execution.
my $exit_status = 0;
my $digest = Digest::MD5->new;

if ($#ARGV < 0) {
print " Inssuficient number of arguments";
print "\nUsage : $0 [dir1]..\n";
exit ERROR;
}

#
# Check provided directories exists.
# If not exists then exit showing error,
# otherwise process the directory.
#
foreach my $dirname (@ARGV) {
chomp ($dirname);
$dirname = trimall($dirname);
if (! -d $dirname) {
print "$dirname is not directory \n";
$exit_status = ERROR;
next;
} elsif (! -r $dirname) {
print "$dirname is not readable. \n";
$exit_status = ERROR;
next;
}
processfiles($dirname);
}
print "\n";
exit $exit_status;

#
# processfiles:
# Read recursively through the directory.
# If it is file calculate MD5 check sum of
# conceptual string from the file's
# [userid] [groupid] [permission] [inode]
# and file content. Print the file full path
# and MD5 check sum against it.
#
# parameters:
# string filename: input file for processing.
# return type: integer: return sucess/failure code.
#

sub processfiles
{
use Cwd 'abs_path';
#my $dirname = $_[0];
my $dirname = abs_path($_[0]);
chomp ($dirname);
opendir(DIRH, $dirname);

#
# Read all the files and directories execluding the current
# '.' and parent directory '..'
#

my @files = sort (grep { !/^\.|\.\.}$/ } readdir (DIRH));
closedir(DIRH);
my $file;
foreach $file (@files) {
my $fullpath = $dirname . "/" . $file;
print "\n$fullpath";
if (-d "$fullpath") {
processfiles("$fullpath");
} else {
print "\t" . getmd5checksum ("$fullpath");
}
}
return 0;
}

#
# getmd5checksum:
# Generate a 64 bit Hex MD5 checksum for file contents
# and string [userid] [groupid] [permission] [inode]
#
# parametrs: string file: file of which MD5 check sum need
# to calculated.
# return type: MD5 checksum of the contents of the file
# with conceptual string
#

sub getmd5checksum
{
my $file = shift;
if (! -r $file) {
return "Not readable";
} else {
open (FILE, $file) or return"";
$digest->reset();
my $fileInfo = getfileinfo($file);
$digest->add($fileInfo);
$digest->addfile(*FILE);
close (FILE);
return $digest->b64digest;
}
}

#
# getfileinfo:
# Returns formated string for entered file as
# [uid] [gid] [mode] [ino]
#
# parameters:
# string filename: filename of which we need to
# find the conceptual string.
# return type: string: return conceptual string in
# format [uid] [gid] [permission] [ino]
#

sub getfileinfo
{
my $file = shift;
my (undef, $ino, $mode, undef, $uid, $gid) = stat($file);
my $oct = sprintf("%o", $mode & 07777);
return $uid . " " . $gid . " " . $oct . " " . $ino;
}

#
# trimall:
# used to trim leading and trailing white space characters
# from string.
# parameters:
# string str: input string from which spaces needs
# to be removed.
# return type : string
# trimed string.
#

sub trimall
{
my $arg = shift;
$arg =~ s/^\s+|\s+$//g;
return $arg;
}

Perl: Finding higest UID from passwd file



#! /usr/bin/perl -w
use strict;

#
# Program to find the maximum
# User ID from /etc/passwd.
#

use constant CONF_FILE => "/etc/passwd"; # PATH of the file
use constant SEPERATOR => ":"; # Record seperator
use constant COLTOSPLIT => 4; # Number of columns to split.
use constant COL_USRID => 2; # User id column number.
my $userID = 0; # Temp variable for finding max UID.

#
# Open /etc/passwd file.
# If any error occurs while
# reading file terminate program
# print the error message occured.
#

open (FILE, CONF_FILE) or die ($!);
my @data = ;

#
# Read one line, split the line using SPERATOR.
# Check value at COL_USRID column.
# Store the maximum UID in userID.
#
foreach my $line (@data) {
chomp($line);
my @user = split(SEPERATOR, $line, COLTOSPLIT);
if ($userID < $user[COL_USRID]) {
$userID = $user[COL_USRID];
}
}
#
# Close the file handler.
# close(FILE);
print "Higest user ID : " , $userID;
print "\n"; exit 0;