Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 21-30 of 72 total

Load CSV data into a database (Scriptella ETL tool)

This example demonstrates usage of Scriptella ETL Tool to load CSV data into a database table.

Input CSV file data.csv:
   1  
   2  id,priority,summary,status
   3  1,Critical,NullPointerException in Main class,Open
   4  5,Low,"Checkstyle, PMD, Findbugs issues",Reopened
   5  7,Low,Maven integration,Open
   6  10,High,SPI API,Closed

The CSV loading script has the following content:
   1  
   2  <!DOCTYPE etl SYSTEM "http://scriptella.javaforge.com/dtd/etl.dtd">
   3  <etl>
   4    <connection id="in" driver="csv" url="data.csv"/>
   5    <connection id="out" driver="oracle" url="jdbc:oracle:thin:@localhost:1521:ORCL" 
   6        classpath="ojdbc14.jar" user="scott" password="tiger"/>
   7    <!-- Copy all CSV rows to a database table -->
   8    <query connection-id="in">
   9        <!-- Empty query means select all columns -->
  10        <script connection-id="out">
  11            INSERT INTO Table_Name VALUES (?id,?priority, ?summary, ?status)
  12        </script>
  13    </query>
  14  </etl>


Use RegEx to filter CSV data:
   1  
   2  <query connection-id="in">
   3      <!--Select bugs with status open or reopened.-->
   4      ,,,open|reopened
   5      <!--Inserts imported rows into a database-->
   6      <script connection-id="out">
   7         INSERT INTO Table_Name VALUES (?id, ?priority, ?summary, ?status);
   8      </script>
   9  </query>

Request Database Authentication

Simple solution to a problem that may not affect very many folks.
If you don't like your password displayed in plain text in database.yml, this might help you.
It utilizes the Highline gem (big thanks to James Edward Gray II).
<http://www.bigbold.com/snippets/posts/show/3361>

   1  
   2  # database.yml
   3  
   4  <%
   5  require 'highline/import'
   6  
   7  def request_input(msg, show_input = true)
   8    ask(msg) { |q| q.echo = show_input }
   9  end
  10  %>
  11  
  12  #...
  13    username: <%= request_input 'Username: ' %>
  14    password: <%= request_input 'Password: ', false %>
  15  #...

[Java] Read DataSource from connection pool (Tomcat and WAS4)

   1  
   2  Context initContext;
   3  initContext = new InitialContext();
   4  DataSource ds = null;
   5  
   6  if ("TOMCAT".equals(appServer)) {
   7  
   8        //Apache Tomcat Server
   9        ds = (DataSource)initContext.lookup("java:comp/env/jdbc/yourJNDI");
  10  
  11  } else if  ("WAS4".equals(appServer)) {
  12  
  13        //IBM WebSphere 4.x
  14        ds = (DataSource)initContext.lookup("jdbc/yourJNDI");
  15                                  
  16  }

Rails - ‘poor mans’ SQL cache.

Rails memcached is not very easy to introduce to a large rails installation. Memcached also chews up a lot of memory on the box and overall cached model does not work the way I needed it to. Basically, I have just a “few? queries that I needed to cache because pagination sucks just that bad in rails.
So, I built my own cache, similar to how I build them in PHP except I am not using disk cache, I am using MySQL itself to cache it’s own results

First, we need a table to hold all this info (note the ‘blob’ field)
   1  
   2  CREATE TABLE `cacheditems` (
   3  `id` int(11) NOT NULL auto_increment,
   4  `cachekey` varchar(255) default NULL,
   5  `created` datetime default NULL,
   6  `expires` datetime default NULL,
   7  `content` longblob,
   8  `cachehit` int(11) NOT NULL,
   9  PRIMARY KEY  (`id`),
  10  KEY `cacheditems_cachekey_index` (`cachekey`),
  11  KEY `cacheditems_created_index` (`created`),
  12  KEY `cacheditems_expires_index` (`expires`)
  13  )

Then we create a model called “cacheditem? which has the following functions
   1  
   2  require 'digest/sha1'
   3  class Cacheditem < ActiveRecord::Base
   4  
   5  def self.checkfor(sql)
   6  key = Digest::MD5.hexdigest(Marshal.dump(sql))
   7  logger.info "%%% checking for key #{key}"
   8  #logger.info "%%% checking by sql #{sql[0]}"
   9  Cacheditem.find( :first, :conditions => [ “cachekey = ? AND expires > NOW()?, key] )
  10  end
  11  
  12  def self.getcached(sql)
  13  key = Digest::MD5.hexdigest(Marshal.dump(sql))
  14  logger.info%%% getting by key #{key}?
  15  #logger.info “%%% getting by sql #{sql[0]}?
  16  getc = Cacheditem.find( :first, :conditions => [ “cachekey = ??, key] )
  17  hitcount = getc.cachehit + 1
  18  Cacheditem.update(getc.id, {:cachehit => hitcount})
  19  Cacheditem.delete_all “expires < NOW()"  # cleaner
  20  return Marshal.load( getc.content )
  21  end
  22  
  23  def self.storeresult(sql, result)
  24  key = Digest::MD5.hexdigest(Marshal.dump(sql))
  25  logger.info "%%% storing by key #{key}"
  26  content = Marshal.dump(result)
  27  logger.level = (4) # this stops display in logs of the marshal data
  28  ci = new()
  29  ci.cachekey    = key
  30  ci.created       = Time.now()
  31  ci.expires        = 30.minutes.from_now() # change as needed
  32  ci.content        = content
  33  ci.cachehit       = 0
  34  ci.save
  35  return  result
  36  end
  37  
  38  end

Then, in application.rb I added the following function
   1  
   2  def find_by_sql_cache(sql)
   3  iscached = Cacheditem.checkfor(sql)
   4  if iscached
   5  Cacheditem.getcached(sql)
   6  else
   7  result = connection.select_all(sanitize_sql(sql), "#{name} Load").collect! { |record| instantiate(record) }
   8  Cacheditem.storeresult(sql, result)
   9  end
  10  end

just throw “_cache? after any “find_by_sql? statement you have a need to cache and there you are.

This works very fast, very well, and doesn’t hog your memory. It cleans up after itself in the database, and perhaps it does that too much.. It would be easy to add in a standard garbage collection function which runs on a random but I felt this gave me much better stats of the actual thirty-minute cache…
If you use zabbix for monitoring your network, you can have fun graphs of cache statistics by adding the following to your zabbix_agentd.conf
   1  
   2  UserParameter=mysql.totalcache,mysql –batch –skip-column-names -D {YOUR_DATABASE} -u{YOUR_USERNAME} -p{YOUR_PASSWORD} -e “SELECT count( * ) AS total, SUM( cachehit ) AS amount from cacheditems;? | cut -f1
   3  UserParameter=mysql.cachehits,mysql –batch –skip-column-names -D {YOUR_DATABASE} -u{YOUR_USERNAME} -p{YOUR_PASSWORD} -e “SELECT count( * ) AS total, SUM( cachehit ) AS amount from cacheditems;? | cut -f2

Change sessions, transaction and processes parameters in Oracle 10g

   1  
   2  alter system set PROCESSES=100 scope=SPFILE;
   3  alter system set TRANSACTIONS=126 scope=SPFILE;
   4  alter system set SESSIONS=115 scope=SPFILE;

PHP: Connecting Flash to a Database (remoting)

There are many ways to do this.

Depending on the backend language you're using, whether PHP, ColdFusion or other... you'll need to create some components (CFC's for ColdFusion), (Classes for PHP)... these are referred to as "services"

Then you'll need to connect Flash to a remoting gateway (I use AMFPHP for PHP: www.amfphp.org).

Either way, you'll need NetServices.as from Flash MX Remoting, call a gateway and retrieving a list of functions from your classes/components/services.

Enough with the theory, here's how to do it with PHP:
   1  
   2  /* /flashservices/services/Catalog.php */
   3  class Catalog {
   4          var $products_array = array();
   5  
   6  // Constructor: Contains the list of methods available to the gateway
   7  function Catalog() {
   8  	$this->methodTable = array (
   9  		"getProducts" => array (
  10  			"description" => "Get list of products",
  11  			"access" => "remote",
  12  			"arguments" => "" // arguments could be optional, not tested
  13  		)
  14  	); // end methodTable
  15  }
  16  
  17  function getProducts() {	
  18  	// your code goes here
  19  
  20  	return $this->products_array;
  21  }
  22  }


!!!!!!!!! The code below is now deprecated !!!!!!!!
---- see my other snippet to do this in Flash 8 ----

Flash ActionScript (PHP Gateway):
   1  
   2  #include "NetServices.as"
   3  NetServices.setDefaultGatewayUrl("http://yourserver.com/flashservices/gateway.php");
   4  gw = NetServices.createGatewayConnection();
   5  CatalogREMOTE = gw.getService("Catalog", this);
   6  CatalogREMOTE.getProducts();
   7  
   8  getProducts_Result = function(result) {
   9  	_root.products_results = result;
  10  }


You parse the _root.products_results array however you want :D

How flash connects with database

// description of your code here

   1  
   2  // insert code here..

Clone dev DB schema to test DB in Rails

Ruby on Rails

Command to clone the 'dev' DB to 'test' DB
   1  
   2  rake clone_structure_to_test

*note* clones the structure/schema but NOT the content in the tables.

HABTM relationship MySQL tables for use in Rails

This is an example of the tables I create when I want to have an HABTM relationship between 2 tables:
Table 1: products
Table 2: tags

   1  
   2  DROP TABLE IF EXISTS `products_tags`;
   3  DROP TABLE IF EXISTS `tags`;
   4  DROP TABLE IF EXISTS `products`;
   5  
   6  CREATE TABLE `products` (
   7    `id` int(11) NOT NULL auto_increment,
   8    `title` varchar(100) NOT NULL,
   9    `price` decimal(10,2) NOT NULL,
  10    PRIMARY KEY  (`id`)
  11  )
  12  
  13  CREATE TABLE `tags` (
  14    `id` int(11) NOT NULL auto_increment,
  15    `title` varchar(64) NOT NULL,
  16    PRIMARY KEY  (`id`)
  17  )
  18  
  19  CREATE TABLE `products_tags` (
  20    `product_id` int(11) NOT NULL default '0',
  21    `tag_id` int(11) NOT NULL default '0',
  22    PRIMARY KEY  (`product_id`,`tag_id`)
  23  )


Simple Ruby ActiveRecord example

Using Ruby ActiveRecord with an in-memory SQLite database. A nice simple example of this wonderful library.

   1  
   2  require 'active_record'
   3  
   4  ActiveRecord::Base.logger = Logger.new(STDERR)
   5  ActiveRecord::Base.colorize_logging = false
   6  
   7  ActiveRecord::Base.establish_connection(
   8      :adapter => "sqlite3",
   9      :dbfile  => ":memory:"
  10  )
  11  
  12  ActiveRecord::Schema.define do
  13      create_table :albums do |table|
  14          table.column :title, :string
  15          table.column :performer, :string
  16      end
  17  
  18      create_table :tracks do |table|
  19          table.column :album_id, :integer
  20          table.column :track_number, :integer
  21          table.column :title, :string
  22      end
  23  end
  24  
  25  class Album < ActiveRecord::Base
  26      has_many :tracks
  27  end
  28  
  29  class Track < ActiveRecord::Base
  30      belongs_to :album
  31  end
  32  
  33  album = Album.create(:title => 'Black and Blue',
  34      :performer => 'The Rolling Stones')
  35  album.tracks.create(:track_number => 1, :title => 'Hot Stuff')
  36  album.tracks.create(:track_number => 2, :title => 'Hand Of Fate')
  37  album.tracks.create(:track_number => 3, :title => 'Cherry Oh Baby ')
  38  album.tracks.create(:track_number => 4, :title => 'Memory Motel ')
  39  album.tracks.create(:track_number => 5, :title => 'Hey Negrita')
  40  album.tracks.create(:track_number => 6, :title => 'Fool To Cry')
  41  album.tracks.create(:track_number => 7, :title => 'Crazy Mama')
  42  album.tracks.create(:track_number => 8,
  43      :title => 'Melody (Inspiration By Billy Preston)')
  44  
  45  album = Album.create(:title => 'Sticky Fingers',
  46      :performer => 'The Rolling Stones')
  47  album.tracks.create(:track_number => 1, :title => 'Brown Sugar')
  48  album.tracks.create(:track_number => 2, :title => 'Sway')
  49  album.tracks.create(:track_number => 3, :title => 'Wild Horses')
  50  album.tracks.create(:track_number => 4,
  51      :title => 'Can\'t You Hear Me Knocking')
  52  album.tracks.create(:track_number => 5, :title => 'You Gotta Move')
  53  album.tracks.create(:track_number => 6, :title => 'Bitch')
  54  album.tracks.create(:track_number => 7, :title => 'I Got The Blues')
  55  album.tracks.create(:track_number => 8, :title => 'Sister Morphine')
  56  album.tracks.create(:track_number => 9, :title => 'Dead Flowers')
  57  album.tracks.create(:track_number => 10, :title => 'Moonlight Mile')
  58  
  59  puts Album.find(1).tracks.length
  60  puts Album.find(2).tracks.length
  61  
  62  puts Album.find_by_title('Sticky Fingers').title
  63  puts Track.find_by_title('Fool To Cry').album_id
« Newer Snippets
Older Snippets »
Showing 21-30 of 72 total