28 Nov 2009 @ 8:44 AM 

As most of you are aware, when working with currency values, FLOAT types just don’t cut it due to their innaccuracy in handling of decimal places. For example – 0.0006 is stored as 0.0005998035. For most instances this is acceptable, BUT when you start working with large values, it becomes a problematic.

Lets say we are writing a banking transaction module that handles 10 million transactions a day. This would result in an inbalance of (10 000 000 x 0.0006) – (10 000 000 x 0.0005998035) = (6000) – (5998.035) = 1.965 out of balance every day. I’m sure you can see why this would become a problem.

The solution? java.math.BigDecimal

However, be warned! BigDecimal isnt a primitive datatype, so you cannot handle it like you would a float.

Lets look at a basic example

//declare and initialize variables
BigDecimal customer_tx_amount;
BigDecimal customer_tx_vatamount;
BigDecimal vatrate = new BigDecimal("14");
//calculate vatrate divider.
//if vatrate = 14%, then to work out the exclusive amount, we divide the inclusive amount by 
//((100+14)/100), or 1.14
vatrate = vatrate.add(new BigDecimal("100"));
//we want 6 decimal places
vatrate = vatrate.divide(new BigDecimal("100"), 6, BigDecimal.ROUND_HALF_UP);
 
customer_tx_amount = new BigDecimal("235345.37");
customer_tx_vatamount = customer_tx_amount.divide(vatrate, 6, BigDecimal.ROUND_HALF_UP);
customer_tx_vatamount = customer_tx_amount.subtract(customer_tx_vatamount);

So, as you can see, bigdecimal is accurate, but rather clunky to use.

In most instances you will be happy using float, but if you require extreme accuracy, then BigDecimal is definitely the way to go

Posted By: Zayin
Last Edit: 28 Nov 2009 @ 08:44 AM

EmailPermalinkComments (2)
Tags
Tags:
Categories: java
 23 Nov 2009 @ 9:45 AM 

Firstly, create a method to get a connection from the pool

    private static Connection getJNDIConnection(){
        String DATASOURCE_CONTEXT = "java:comp/env/jdbc/airtime";
 
        Connection result = null;
        try {
          Context initialContext = new InitialContext();
          if ( initialContext == null){
            errorMsg = "ERROR: JNDI problem. Cannot get InitialContext.";
            return null;
          }
          DataSource datasource = (DataSource)initialContext.lookup(DATASOURCE_CONTEXT);
          if (datasource != null) {
            result = datasource.getConnection();
          }
          else {
            errorMsg = "ERROR: Failed to lookup datasource.";
            return null;
          }
        }
        catch ( Exception ex ) {
          errorMsg = "ERROR: Cannot get connection: " + ex;
          return null;
        }
        return result;
    }

Secondly, in your “sun-web.xml” and “web.xml” deployment descriptors, add a reference to the resource

sun-web.xml :

  <resource-ref>
    <res-ref-name>jdbc/airtime</res-ref-name>
    <jndi-name>jdbc/airtime</jndi-name> 
  </resource-ref>

web.xml :

    <resource-ref>
        <res-ref-name>jdbc/airtime</res-ref-name> 
        <res-type>javax.sql.DataSource</res-type> 
          <res-auth>Container</res-auth> 
          <res-sharing-scope>Shareable</res-sharing-scope> 
    </resource-ref>
Posted By: Zayin
Last Edit: 23 Nov 2009 @ 12:18 PM

EmailPermalinkComments (2)
Tags
Tags: , ,
Categories: glassfish, mysql
 23 Nov 2009 @ 9:01 AM 

This post will describe step-by-step how to setup a MySQL connection pool in Glassfish v2. Lookout for the next blog entry that details how to use that connection pool from your JAVA app.

Step 1:
Log in to your Glassfish admin console ( http://localhost:4848/) and create the connection pool using the settings below

Step 1

Click “Next” to configure the settings

Step 2

Once you have configured the settings, you can save your connection pool. In order to establish that everything is working, use the “ping” command at the top of the page

Glassfish MySQL connection pool Step3

Once we have the fully-functional container connection-pool, the next step is to declate the JDBC Resource which presents this connection pool to the application code. For this you must use the other Administration option in the JDBC section:

conpool4

dont forget to configure your username and password under “additional properties”
Glassfish MySQL connection pool Step5

This is pretty straight forwards – and the JNDI Name must have the ‘/jdbc’ prefix to show up in the correct context branch for when you locate the resource in your JAVA applet. At this point you have the Glassfish container configured correctly to offer you a jdbc connection pool and resource.

And thats all there is to creating a MySQL Connection pool in Glassfish.

In the next blog post we discuss how to use this connection pool from your JAVA applet.

Posted By: Zayin
Last Edit: 26 Feb 2010 @ 08:12 AM

EmailPermalinkComments (2)
Tags
Tags: ,
Categories: glassfish, mysql
 21 Nov 2009 @ 9:42 AM 

When using activerecord in CodeIgniter to build your queries, it often happens that you want to see what SQL is being generated.

There are 2 ways to do this

1) The application profiler will show the sql used. Just add

$this->output->enable_profiler(TRUE);

2) OR

$str = $this->db->last_query(); 
echo $str;
Posted By: Zayin
Last Edit: 23 Nov 2009 @ 09:47 AM

EmailPermalinkComments (0)
Tags
Tags: ,
Categories: php
 17 Nov 2009 @ 1:37 PM 

I’ve been using the CodeIgniter framework for a few months now, and I am still blow away by its flexibility every day.

CodeIgniter is a MVC (Model/View/Controller) framework that makes your life a breeze when developing PHP applications.

I want to add a form to one of my webpages that allows me to apply a pre-defined pricelist to a customer’s products.

The snippet below generates the form and populates the “select” tag with elements from the database

First, lets load all the pricelists into $query

1
$query = $this->db->get('pricelist');

Then lets put the relevant fields into an array

1
2
3
4
foreach ($query->result() as $row)
{
    $data[$row->pricelist_id] = $row->pricelist_description;
}

Lastly, lets ask CI to build us a form

1
2
3
4
$result = form_open(get_class($this) . '/assign_pricelist_to_customer/' . $this->customer_id . '/' . $this->sub_nav_id) . "\n";
$result = $result . form_dropdown('pricelist_id', $data) . "\n";
$result = $result . form_submit('submit', 'Load this pricelist') . "\n";
$result = $result . form_close() . "\n";

Here’s the full method

1
2
3
4
5
6
7
8
9
10
11
12
    private function setup_pricelist(){
        $query = $this->db->get('pricelist');
        foreach ($query->result() as $row)
        {
            $data[$row->pricelist_id] = $row->pricelist_description;
        }
        $result = form_open(get_class($this) . '/assign_pricelist_to_customer/' . $this->customer_id . '/' . $this->sub_nav_id) . "\n";
        $result = $result . form_dropdown('pricelist_id', $data) . "\n";
        $result = $result . form_submit('submit', 'Load this pricelist') . "\n";
        $result = $result . form_close() . "\n";
        return $result;
    }

So elswhere in my code, all I do is

1
2
3
4
5
6
7
8
9
.
.
.
$data['pricelist_select'] = $this->setup_pricelist();
$data['title']   = $this->title;
$this->load->view('some_view', $data);
.
.
.

in my view

1
2
3
4
5
    <div class="content">
      <?php echo $pricelist_select?>
      <?php echo $content?>
      <div class="line"></div>
  </div>

And hey presto, I have a form with a dynamically populated dropdown

Posted By: Zayin
Last Edit: 17 Nov 2009 @ 01:40 PM

EmailPermalinkComments (0)
Tags
Tags: ,
Categories: php
 16 Nov 2009 @ 9:04 PM 

I have looked this up a number of times because I can never quite remember the exact procedure. I have decided to document this, primarily for myself, but I hope others find it useful as well. They method I have found the most useful for storing money in a MySQL database it using a DECIMAL data type with a length/value of 18,2. I have included a phpMyAdmin screenshot to better demonstrate what I am talking about.

The result of these settings will give you a database value of something like 235.00 instead of 235. It will also properly handle fractions, for example: 235.10 will store as 235.10 as opposed to 235.1. This helps to avoid the problem of MySQL dropping the zeros after the decimal point.

However, you may still want to format your strings for display, but that is up to you.

mysql currency

However, if you are storing costs, you might want to increase your decimal places for accuracy, especially if there are tax implications.

An example would be if you capture a value of 100 including VAT @ 14%, you would need to store the VAT exclusive value of 87.71929824561404

Generally it wouldn’t be necessary to store all 14 digits (6 should suffice), but I would certainly recommend storing more than 2.

Posted By: Zayin
Last Edit: 17 Nov 2009 @ 01:39 PM

EmailPermalinkComments (1)
Tags
Tags: ,
Categories: mysql
 16 Nov 2009 @ 6:04 PM 
class customer_list extends MY_Controller
{
    function some_method($customer_id, $subnav_item)
    {
        $this->sub_nav_id = $subnav_item;
        $this->customer_id = $customer_id;
        $uri_string = get_class($this) . '/some_method/' . $this->customer_id . '/' . $this->sub_nav_id;
     }
}

when calling the class I would do something like this : http://www.mysite.com/customer_list/some_method/1/2

This would call the method “some_method” and pass 2 parameters ($customer_id = 1 and $subnav_item = 2)

Its that simple

Posted By: Zayin
Last Edit: 16 Nov 2009 @ 06:14 PM

EmailPermalinkComments (1)
Tags
Tags: ,
Categories: php
 16 Nov 2009 @ 11:28 AM 

With the latest version of GlassFish Enterprise Server, GlassFish v2.1.1, Sun delivers a scalable, reliable foundation for the telco-grade Sun GlassFish Communications Server, and expands platform support to include AIX 6.1. With more than 10 million downloads in the last year, GlassFish Enterprise Server is one of the leading open source application servers in the industry today. Users of GlassFish Enterprise Server will benefit from enterprise reliability and performance with less complexity, and will be able to deliver new services in less time.

Thats all good and well, but what the heck is an application server?

An application server is a software framework dedicated to the efficient execution of procedures (scripts, routines, programs, …) for supporting the construction of applications. The term was created in the context of web applications. In these, the application server acts as a set of components accessible to the software developer through an API defined by the platform itself. These components are usually performed in the same machine where the web server is running, and their main job is to support the construction of dynamic pages.

This means that you can write JAVA applications and host them on your application server. The application server then handles connection pooling, multiple simultaneous connections, web services you might write and much more.

What this means is that you can focus on writing your application without having to worry about multiple instances and other such problems.

To install GlassFishV2 on linux is fairly straightforward

sudo apt-get install glassfishv2

This will install all the dependancies needed to get glassfish running. To actually start glassfish

cd /usr/share/bin/glassfishv2/bin
./asadmin stop-domain
./asadmin start-domain

then point your browser at http://localhost:4848/ – this is the adminstration module for glassfishv2. Login is admin, password is adminadmin. Make sure you change this!

You are now ready to deploy Java apps against your application server! You can either copy them into the “autodeploy” folder on your server, or you can upload your (ear/war/jar) bundle via the administration interface for deployment

NB: TO INSTALL ON OTHER LINUX VIEW THIS LINK

Posted By: Zayin
Last Edit: 16 Nov 2009 @ 06:12 PM

EmailPermalinkComments (3)
Tags
Tags: ,
Categories: glassfish, linux
 15 Nov 2009 @ 11:23 AM 

If you are looking for an easy to use CRUD (Create, Read, Update, Delete) framework for PHP, then I can *highly* recommend Rapyd.

Although Rapyd is a MVC (Model/View/Controller) framework http://www.rapyd.com/, I am using the version of Rapyd that integrates with CodeIgniter

The only shortcoming is that the documentation is rather lacking, so I had to figure most of it out myself.

While there are some excellent examples on the Rapyd website, I have decided to add some examples of my own.

<?php
class hardware_list extends MY_Controller
{
    function hardware_list()
    {
        parent::MY_Controller();
        $this->load->library('rapyd');
        $this->title = 'Manage hardware';
    }
 
    //put your code here
    function edit_data()
    {
        $hardware_edit = new dataedit_library();
        $hardware_edit->label = $this->title;
        $hardware_edit->back_url = site_url('hardware_list');
 
        $hardware_edit->source('hardware');
        $hardware_edit->field('input','hw_serial','Serial Number');
        $hardware_edit->field('input','hw_desc','Description');
        $hardware_edit->field('radiogroup','hw_status','Status')->options(array("1"=>"Enabled", "2"=>"Disabled"));
        $hardware_edit->field('radiogroup','hw_type','type')->options(array("1"=>"Wintec", "2"=>"Stand Alone PC"));
        $hardware_edit->buttons('modify','save','undo','back','delete');
        $hardware_edit->build();
        $data['head']    = $this->rapyd->head();
        $data['title']   = $this->title;
        $data['content'] = $hardware_edit->output.'<br />';
        $data['current_selected_nav_item'] = 6;
        $this->load->view('terminals/terminals', $data);
    }
 
function index()
    {
        if ($this->rapyd->qs->value('show|delete|modify|create|insert|update'))
        {
            $this->edit_data();
        } else
        {
            $hardware_grid = new datagrid_library();
            $hardware_grid->label = $this->title;
            $hardware_grid->source('hardware');
            $hardware_grid->column('hw_serial','serial', true)
                ->url(site_url('hardware_list/?show={hw_serial}'))
                ->rule('required');
            $hardware_grid->column('hw_status','Status');
            $hardware_grid->column('hw_type','Type');
            $hardware_grid->column('hw_desc','Description');
            $hardware_grid->column('delete', 'delete')->url(site_url('hardware_list/?delete={hw_serial}'));
            $hardware_grid->buttons('add');
 
            $hardware_grid->build();
 
            $data['head']    = $this->rapyd->head();
            $data['title']   = $this->title;
            $data['content'] = $hardware_grid->output.'<br />';
 
            $data['current_selected_nav_item'] = 6;
 
            $this->load->view('terminals/terminals', $data);
       }
    }
}
 
?>

I want to make a note about the “events” and the order that they happen in, as it took me quite a while to figure it out.

create = before insert – show the form with empty fields
insert = after insert – this happens after create and physically inserts the fields into the db
delete = before delete – show confirmation screen
do_delete = after delete is confirmed – this physically deletes the row from the db
show = show all the info for a single row, but edit it just yet
modify = before data is modified – it shows the edit form with all the fields populated
update = save changes entered in the modify screen

Your “source” can also be an active record result set eg

$grid->label = $this->title;
$grid->db->select('user.*,customer.company_name');
$grid->db->from('user');
$grid->db->join('customer', 'user.customer_id = customer.customer_id');
$grid->db->where('user.customer_id = ' . $customer_id);
Posted By: Zayin
Last Edit: 15 Nov 2009 @ 11:40 AM

EmailPermalinkComments (5)
Tags
Tags: , ,
Categories: php, rapyd
 12 Nov 2009 @ 9:15 PM 

In Windows (and if you go a bit further back, DOS), we normally use the “dir” command to show us a list of files in a directory. Linux/Unix uses the “ls” command to do this.

“ls” isnt very pretty and doesnt show us much.

Personally, my preferred “ls” command is

ls --color=auto -al

although this is a huge hassle to type out every time.

But there is a trick.

cd ~
pico .bashrc

go all the way to the bottom and add this

alias ls='ls --color=auto -al'

ctrl-x to exit; “y” to save changes, and restart your terminal session.

Next time you run “ls” it will give you a nicely formatted directory listing show all files (including hidden)

Posted By: Zayin
Last Edit: 15 Nov 2009 @ 11:42 AM

EmailPermalinkComments (0)
Tags
Tags: , ,
Categories: shell

 Last 50 Posts
 Back
Change Theme...
  • Users » 1
  • Posts/Pages » 38
  • Comments » 57
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight

Links



    No Child Pages.

Portfolio



    No Child Pages.