Monday, December 17, 2012

Using SQLite with JDBC

I had to implement an application which should utilize a portable database. For better portability the application was implemented in java. As my first choice I selected several flat files for storing data in a hierarchical manner .

At the run time of the application , read operations were much higher than the write operations. It took minutes for traversing and search through each file on a search operation.

Considering all above facts I selected "SQLite" for storing and managing data in my application. Though it was bit slow while feeding data to the application , it was pretty fast when reading data from the database.

Thursday, December 13, 2012

Monitoring JDBC Performance with JDbMonitor

There may be some situations where we need to monitor our JDBC calls. There are few mechanisms available for monitoring JDBC calls. I have tried JDbMonitor in some of my projects because it is easy to use and remove without any code change.

JDbMonitor works as a proxy between our application the JDBC driver. Essentially there may be some performance issue if we use this in a production environment. JDbMonitor provides a GUI application to monitor our JDBC calls.

Tuesday, May 29, 2012

XML Serialization With XStream

XML Serialization is essential in some situations. Most probably we may use XML serialization when we need higher level of portability. XStream is a great library for xml serialization.
Serializing

Monday, April 23, 2012

Ajax with Dojo

It is very safe to use Dojo like java script frameworks for Ajax operations since they ensure browser compatibility. We don't have to change the code based on different browsers. dojo will handle those stuff for us. Any way , If we are using such java script frameworks for Ajax operations  we must carefully choose a proper framework with wide range of browser support.

In this example I have used a very simple Servlet and a simple HTML page to demonstrate the client server model.

Friday, April 20, 2012

Browser Automation With Selenium

Selenium is a browser automation framework. it is available in many flavors such as Java , .net , python . I am interested in Java implementation of Selenium.  Selenium can be successfully used in regression automation. It provides all the necessary functionalists required to automate the browser. Such as navigating, verifying, drag and drop,  clicking , selecting..etc.

Selenium can be downloaded from here
Getting started guide

Tuesday, April 3, 2012

Log4j In Action

Logging is very important for the maintenance of  a deployed application. Just assume a situation that we deploy our application on the client systems and work on another project. After some time client reports a failure of our system. What will happen if we haven't maintained a log file! We may be in a big trouble in such situations. It may be very hard to track where the bug occurred. Because we haven't any IDE's , debuggers on deployed machine.

So it is always recommended to use a logging mechanism for large applications. Logging may be a overhead if we don't use it carefully. We can use logging inside exception handling blocks.

Monday, April 2, 2012

Dependancy Injection (Spring Note 1)

Just assume a situation where we have to develop a module that must generate different types of reports such as PDF reports, Excel reports. One of a worst design for such scenario is design classes for each report separately without any form of polymorphism. Such a design may may result in increasing coupling of the program.
example :
ExcelReport excelReport=new ExcelReport();
PDFReport pdfReport=new PDFReport();

excelReport.initialize();
excelReport.createReport();
excelReport.saveReport();

pdfReport.initialize();
pdfReport.createReport();
pdfReport.saveReport();

Monday, March 26, 2012

JDBC Transactions

Most of the times transactions are important when we deal with JDBC. When we perform database operations if we don't realize the importance of transactions it will end up with a tragedy. I have created a scenario to demonstrate the importance of a transaction.
Scenario :
Lets assume a scenario where a transaction credit 500 rs from user1 and debit that 500 rs to user2 .

initial state of accounts

Thursday, March 22, 2012

Friday, February 10, 2012

How to Implement Threaded Server Socket Application

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace ServerSocketApp

Saturday, February 4, 2012

Arrays in .NET Webservices

Web Service
public class Service1 : System.Web.Services.WebService
{
 [WebMethod]
 public int[] sort(int[] arr)
 {
  Array.Sort(arr);
  return arr;
 }
}
Then run the service.
Copy the URL of the WSDL
ex :  http://localhost:4886/Service1.asmx?WSDL

Reading Text from Files (C#.net)

private void button2_Click(object sender, EventArgs e)
{
try
{
 string buffer;
 StringBuilder stb = new StringBuilder();
 StreamReader strmRdr = File.OpenText("c:\\testfile.txt");
 while ((buffer = strmRdr.ReadLine()) != null)
 {
  stb.Append(buffer);
  stb.Append(Environment.NewLine);

Writing Text to files( C#.net )

private void button1_Click(object sender, EventArgs e)
{
 try
 {
  FileStream fileStrm = File.Open("c:\\testfile.txt", FileMode.OpenOrCreate);
  StreamWriter writer = new StreamWriter(fileStrm);
  writer.WriteLine("First Line");
  for (int i = 2; i < 100; i++)
  {
   writer.WriteLine("This is line {0}", i);

Friday, February 3, 2012

Using DataGridView to Show Data in a table

Selecting multiple files and show their information on a DataGridView
    public partial class Form1 : Form
    {
        private String[] selectedFiles;
        public Form1()
        {
            InitializeComponent();
        }

Using FileOpen Dialog

        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog1.Title = "Open a file to process";
            //selectable file types
            openFileDialog1.Filter = "Portable Document Format (*.pdf)|*.pdf|Text Documents(*.txt)|*.txt";
            openFileDialog1.InitialDirectory = "c:\";
            DialogResult respo= openFileDialog1.ShowDialog();
            if (respo == DialogResult.OK)
            {
                textBox1.Text = openFileDialog1.FileName;
            }
            else
            {
                textBox1.Text = "No selected file!";
            }
        }

Thursday, February 2, 2012

Progressbar Update In C#.net

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace ThreaddedApp
{
    public partial class Form1 : Form
    {
        delegate void progressbarrunnerDelegate();
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Invoke(new progressbarrunnerDelegate(progressbarrunner));
        }

        private void progressbarrunner()
        {
            for (int i = 0; i < 100; i++)
            {
                Thread.Sleep(50);
                this.progressBar1.Value = i;
                Application.DoEvents();
            }
        }
    }
}

Monday, January 23, 2012

Using GET and POST methods in J2ME

Most of the mobile applications are not alone. They frequently communicate with web services or web applications to accomplish their tasks. Lets see how to make GET and POST requests to a server.
We can use HttpConnection class to make requests.
Lets see what are the basic steps.

Saturday, January 21, 2012

Python Note 8 (Python Utilities)

Summary
filenames = os.listdir(dir) -- list of filenames in that directory path (not including . and ..). The filenames are just the names in the directory, not their absolute paths.
import os

dir="c:/"
files=os.listdir(dir)
for path in files:
    print(path)
                 
Output :
addins
AppCompat
AppPatch
assembly
avastSS.scr
bfsvc.exe


Python Note 7 (the pickle module)

In python we can use serialization functionality using pickle module. it can save live instances of objects to files and retrieve object instances from pickled files.
Code:
import pickle

class Transaction : 
 def __init__(self,userName,trnsID,payment):
  self.userName=userName
  self.trnsID=trnsID
  self.payment=payment
 
 def __del__(self):
  print("Destructed!")
 
 def getPaymentValue(self):
  return self.payment
 
 def getUserName(self) :
  return self.userName
#end of the class

Python Summary

[Read All]

Python Note 6(Classes and Objects)

Sample Code  : General class
#define a class
class User :
 def __init__(self,name,user_id,acc_balance):
  self.Name=name
  self.User_id=user_id
  self.Acc_Balance=acc_balance
  
 def recharge(self,amount):
  self.Acc_Balance+=amount
 
 def withdraw(self,amount):
  if amount <= self.Acc_Balance :
   self.Acc_Balance-=amount
  else :
   pass #do nothing
 
 def getBalance(self): #parameter less method
  return self.Acc_Balance
  
 def __del__(self) :
  print("Destructor started!")
#end of the class
 
usr=User("Kanishka",1133,27000.00)
print("User {0} , Balance {1:5.2f}".format(usr.Name,usr.getBalance()))
usr.withdraw(2000.50) #withdrwaw money
print("User {0} , Balance {1:5.2f}".format(usr.Name,usr.getBalance()))

Friday, January 20, 2012

Python Note 5 (File Handling)

File handling is very easy in python, Lets see an example
datafile=open("myfile.dat","w") #open a file for writing
datafile.write("Sri Lanka,India,Pakistan,Bhutan,Australlia,Canada") #write data
datafile.write("\n")
datafile.write("Apple,Orange,Mango")
datafile.close() #release the file

#reading from the file
datafile=open("myfile.dat","r") #open file for reading
record=datafile.readline()#reding a line (here it is the first line)
mylist=record.strip("\n").split(",") #remove newline character and split the string by comma
print(mylist)
print(len(mylist))

Python Note 4( String Formatting)

Code
import math 

for x in range(1,20) :
 print ("{0:2d} {1:3d} {2:5d}".format(x,x*2,x*3))
 
tmplate="My {} is {}"
print(tmplate.format("country","Sri Lanka"))
print(tmplate.format("name","Kanishka"))

tmplate="Hello {name} , your role is {role}"
print(tmplate.format(name="Kanishka",role="Admin"))
print(tmplate.format(name="Sampath",role="User"))

print("The value of 'PI' is approximately {0:0.3f}".format(math.pi))
print("The value of 'e' is approximately {0:0.5f}".format(math.e))

#old formatting
print('The value of PI is approximately %5.3f' % math.pi)
Result

Wednesday, January 18, 2012

Python Note 3 (Functions)

We can define number of functions in same python script.
Code
#function1
def cube(x) :
 return x**3

#function2
def maxVal(x,y) :
 if x > y :
  return x
 else :
  return y

print (cube(3))
print (maxVal(12,22))

Python Note 2 (String manipulations)

Code
mystr="Sri Lanka"
print( len(mystr) )
print( mystr.upper() )
print( mystr.lower() )
print( mystr[1])
print( mystr[-1])

Python Note 1

Python is an interpreted language. Nesting is done using indentation. I have used Python 3.2.2 in this note.


Sample python program demonstrating Python operators.

Monday, January 16, 2012

J2ME with LWUIT (UI Toolkit Widgets) part 3

In this note, I would like to note down how to create a Ticker, Calendar
Any label can be configured as a Ticker.
  • Ticker
            Image ico = Image.createImage("/img/arrow.png");
            Label lblTicker = new Label("Hello! This is a Ticker!");
            lblTicker.setIcon(ico);

            Form frm=new Form();
            frm.addComponent(lblTicker);
            frm.show();
                    
            //finally
            lblTicker.startTicker(100, true);

J2ME with LWUIT (UI Toolkit Widgets) part 2

Lets see how to use Tabbed pane, ComboBox TextArea, TextField

  • TabbedPane
I am going to use Containers with TabbedPanes because it provides an easy way to organize widgets

Sunday, January 15, 2012

J2ME with LWUIT (UI Toolkit Widgets) part 1

There are very important UI widgets available in LWUIT lets demonstrate them.

J2ME with LWUIT (Commands)

Definitely we may need to use commands because users must have a simple way to command our app. Though we can use buttons to get user commands, it may not be the best options. By using commands we can easily place the frequently used commands in our app.

J2ME with LWUIT (Initializing)

LWUIT is a SWING like lightweight widget library for J2ME. It is very useful for software development with J2ME. I could find a very useful guide for LWUIT. It is available here.

LWUIT class hierarchy is useful when we use LWUIT wifgets.

Friday, January 6, 2012

Queries in HIBERNATE

Querying is one of most important part in Hibernate. For this purpose we have to use HQL (Hibernate Query Language). HQL is simpler than SQL and bit differ from SQL. Here in HQL we consider on Classes instead of Tables and we consider on Attributes instead of Columns.
Lets see how to querying from Hibernate.
For this example I have used a College , Student relation which is a one to many association.

Monday, January 2, 2012

Inheritance Mapping

Basically there are 3 types of inheritance mapping. We may use those methods suitably.
  • SINGLE_TABLE (default)
  • JOINED
  • TABLE_PER_CLASS
Model

Sunday, January 1, 2012

Compound Primary Keys in HIBERNATE

Most of the time we need only 1 primary key. But there are some situations we may need compound primary keys.
Here in hibernate it is simple. We can use 2 classes into 1 table strategy.
Account.java
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Account {

 private AccountCompoundKey compoundKey;
 private int accBalance;
 
 @Id
 public AccountCompoundKey getCompoundKey() {
  return compoundKey;
 }
 public void setCompoundKey(AccountCompoundKey compoundKey) {
  this.compoundKey = compoundKey;
 }
 public int getAccBalance() {
  return accBalance;
 }
 public void setAccBalance(int accBalance) {
  this.accBalance = accBalance;
 } 
}

© kani.stack.notez 2012 | Blogger Template by Enny Law - Ngetik Dot Com - Nulis