Latest Snippets

Find the Calling Class

Here is a simple snippet to find out the calling Java Class.

Class.forName(new Throwable().getStackTrace()[2].getClassName()));

Basically it create a exception object (Throwable in this case), then get the Stack Trace associated witht he thread so far. Since the stack trace if FIFO, the Calling classes would have called this current class and would have been positioned at the 2 place in the stack. So get the class name for 2nd element by calling getClassName() and finally wraping all this by the outer Class.forName(....)

 

 

 

Compute size of Mysql database with it's tables

Basically a database is a collection of tables.
So the size of the database is sum total of size of its individual tables.
Size of the table = Size of its Data + Size of its Indexes.
Size of database = Sum of {Individual Table Size}
The following snippet uses that above logic to compute the overall size of the database by computing the size of its individual tables.
<?php
// Script to compute total size of a mysql database.
$host = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

// connect to the mysql server
mysql_connect($host,$username,$password);

// select the database
mysql_select_db($dbname);

// execute the query
$result = mysql_query("show table status");

$db_data_size = 0;
$db_index_size = 0;
$out = "";

// loop through the resultset (each table)
while($row = mysql_fetch_array($result)) {
$table_data_size = $row["Data_length"];
$table_index_size = $row["Index_length"];

// table size
$table_size = $table_data_size + $table_index_size;

// increment the over all size
$db_data_size += $table_data_size;
$db_index_size += $table_index_size;

$table_stats = $row["Name"];
$table_stats = $table_stats .": Data(" .round(($table_data_size/1024)/1024, 2) ."MB)";
$table_stats = $table_stats .": Index(" .round(($table_index_size/1024)/1024, 2) ."MB)";
$table_stats = $table_stats .": Total(" .round(($table_size/1024)/1024, 2) ."MB)";
$out = $out . $table_stats . "\n";
}

// convert to MB and round it of
$db_data_size_mb = round(($db_data_size/1024)/1024, 2);
$db_index_size_mb = round(($db_index_size/1024)/1024, 2);
$db_size_mb = $db_data_size_mb + $db_index_size_mb;

$out = $out ."DB Size : Data(". $db_data_size_mb ."MB)";
$out = $out .": Index(". $db_index_size_mb ."MB)";
$out = $out .": Total(". $db_size_mb ."MB)\n";
echo $out;
?>

Recursively Convert Gif Images To Jpg

Converting images from gif to jpg for web or other reason can be done easily using the ImageIO package. The following snippet convert all the gif images in directory rootDir to jpg images.Compile this class and execute using java command line. This utility class is also available as part of the Livrona Tools Project.The following is the code for the Image Converter.

 

package com.livrona.image.tools;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FilenameFilter;
import java.util.Date;

import javax.imageio.ImageIO;

/**
* @author mvohra
*
*/

public class
ImageConverter
{

public static void
main(String args[])
{
// root directory where gif images are stored
String rootDir = "c:\\gif-image-dir";
File dir = new File(rootDir);

// It is also possible to filter the list of returned files.
// This example does not return any files that start with `.'.
FilenameFilter filter = new FilenameFilter()
{
public boolean
accept(File dir, String name)
{
return
name.endsWith("gif");
}
};
String[] children = dir.list(filter);

for
(int i = 0; i < children.length; i++)
{
// Get filename of file or directory
String filename = children[i];
log("Converting " + filename);

File myGifFile = new File(rootDir + "\\" + filename);
File outFile = new File(rootDir + "
\\" + filename.replace("gif", "jpg"));
try
{
// Using Image IO
BufferedImage bufi = ImageIO.read(myGifFile);
ImageIO.write(bufi, "
JPEG", outFile);
}
catch (Exception e)
{
log(e.getMessage());
}
}

}

public static void log(String msg)
{
System.out.println(new Date() + "
- " + msg);
}
}

Usage: java com.livrona.image.tools.ImageConverter c://web//images

 

Clean up Rail Sessions

By default rails does not clear out stale sessions from the session store. Depending on the configuration session can be stored in the local file system or the database.

Method 1: (Applies to File Store)
Delete sessions say over ten hours old every four hours.
Otherwise your /tmp will end up overflowing.
This only applies you use the file store method of session storage with Rails.
1 */4 * * * find /tmp/ -name "ruby_sess*" -cmin +600 -exec rm \{} \;

By default the session files are stored in /tmp. To change the location where the session files are created add the following to application.rb

ActionController::Base.session_options[:tmpdir] = "/path/to/session/folder/"

Method2 : (Application to both File or Database Store)

class SessionCleaner
def self.remove_stale_sessions
CGI::Session::ActiveRecordStore::Session.
destroy_all( ['updated_on <?', 20.minutes.ago] )
end
end

And then invoke the remove_stale_sessions method every let say every 15 minutes via;

*/15 * * * * ruby /full/path/to/script/runner -e production "SessionCleaner.remove_stale_sessions"

Retrieve Page Contents via Http Get

This script retrieves the content of url and dumps it to the output

Example copy this script into file named : get_page.rb

#!/usr/bin/ruby
require 'net/http'
host,port,url = ARGV
http = Net::HTTP.new(host, port)
STDERR.puts "url {#url}"
response, data = http.get(url)
puts data

Usage

ruby get_page.rb <host> <port> <url>

The url is specified as a relative path

ruby get_page.rb livrona.com 80 /resource/home

A compact single line version can also be used

ruby -rnet/http -e 'Net::HTTP.get_print(URI.parse(ARGV[0]))' http://dzone.com/links/index.html

Back to top