Category Archives: Java

Database Connection Utility Class in Java

You will find this useful when connecting to a database and running queries in you application. will a little modification and you are good to go. Just add your database connection string, username and password!

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Database object to load drivers and perform queries
 * @author Abdulsalam Umar blog.salamtura.com
 */
public class DataService {

    private static Connection con;
    private static final String Driver = "oracle.jdbc.driver.OracleDriver";
    private static final String ConnectionString = "Your database connection string";
    private static final String user = "username";
    private static final String pwd = "password";

    /**
     * create Database object
     */
    public DataService() {
    }

    /**
     * to load the database base driver
     * @return a database connection
     * @throws SQLException throws an exception if an error occurs
     */
    public static Connection loadDriver() throws SQLException {
        try {
            Class.forName(Driver);
        } catch (ClassNotFoundException ex) {
            System.out.println(ex.getMessage());
        }
        con = DriverManager.getConnection(ConnectionString, user, pwd);
        return con;
    }

    /**
     * to get a result set of a query
     * @param query custom query
     * @return a result set of custom query
     * @throws SQLException throws an exception if an error occurs
     */
    public static ResultSet getResultSet(String query) throws SQLException {
        Connection con = loadDriver();
        ResultSet rs;
        PreparedStatement st = con.prepareStatement(query);
        rs = st.executeQuery();

        return rs;
    }

    /**
     * to run an update query such as update, delete
     * @param query custom query
     * @throws SQLException throws an exception if an error occurs
     */
    public static void runQuery(String query) throws SQLException {
        Connection con = loadDriver();
        ResultSet rs;
        PreparedStatement st = con.prepareStatement(query);
        st.executeUpdate();
    }
}

Reading a File into Byte Array

This example implements a method that reads the entire contents of a file into a byte array.

// Returns the contents of the file in a byte array.
public static byte[] getBytesFromFile(File file) throws IOException {
    InputStream is = new FileInputStream(file);

    // Get the size of the file
    long length = file.length();

    // You cannot create an array using a long type.
    // It needs to be an int type.
    // Before converting to an int type, check
    // to ensure that file is not larger than Integer.MAX_VALUE.
    if (length > Integer.MAX_VALUE) {
        // File is too large
    }

    // Create the byte array to hold the data
    byte[] bytes = new byte[(int)length];

    // Read in the bytes
    int offset = 0;
    int numRead = 0;
    while (offset < bytes.length
           && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
        offset += numRead;
    }

    // Ensure all the bytes have been read in
    if (offset < bytes.length) {
        throw new IOException("Could not completely read file "+file.getName());
    }

    // Close the input stream and return bytes
    is.close();
    return bytes;
}

Learning Java – Introduction

As a beginner in programming, the first thing I always do to put one through is to first explain explain the JVM, Source format and the IDE. This gives a basic understanding of what you are getting into and an idea of the structure on how it works.

Java is just another programming language (like c#, c) with more powerful features and more platform independent. Java runs on all the major OSs on PCs, laptops,Palm tops, tablets and mobile devices.

Firstly, you write you code/logic in a file and save it in file with .java extention (g.e Hello.java). This is an important step because this get starters really frustrated, you will really need to understand how to create a source file and how it works. Find a more detailed explanation below;

Source File Layout

Basic syntax of a Java source file:

[<package_declarations>]
[<import_declarations>]
<class_declarations>+

Example, the VehicleCapacityReport.java file

package shipping.reports;
import shipping.domain.*;
import java.util.List;
import java.io.*;

public class VehicleCapacityReport {
			private List vehicles;
			public void generateReport (Writer output) { . . . }
}

The package Statement

Basic syntax of the package statement

package <top_pkg_name> [.sub_pkg_name];

Examples:

package shipping.reports;

  • Specify the package declaration at the beginning of the source file
  • Only one package declaration per source file
  • If no package is declared, then the class “belongs” to the default package
  • Package names must be hierarchical and seperated by dots

The import Statement

Basic syntax of the import statement

import <pkg_name>[.sub_pkg_name>].<class_name>;

Or

import <pkg_name> [.<sub_pkg_name>].*;

Examples:

import shipping.domain.*;

import java.util.List;

import java.io.*;

  • Precedes all class declarations
  • Tells the compiler where to find classes to use
address contact

A Simple Java XML Address Book

This is a simple address book written in java with XML storage. The essence is to demonstrate how to save and query an XML file in java. This program have the following features;

  1. Add a new contact
  2. Delete a contact
  3. Edit a contact
  4. Search contacts

The program uses an XML library called JDOM.

Click here to download source code: XML Address Book (1545)

Feel free to download and modify as you wish. If you have any questions or comment, make sure you drop it in the comment box below.

My first Java program

Class sleeping in style

Am sure i looked like this in my first Java class!

My first encounter with programming wasn’t a good one. My first lesson for my computer science course was systematic programming. I didn’t know what it meant then so i was looking forward to it. I walked in to the computer lab all excited, got my machine up and running waiting for class to start. Little have i known about what i was about to encounter. The lecturer walked in and first instruction was to open NOTE PAD, well it sounded familiar to me but i was wondering why do we need it because it was just basic with no special functions. Next instruction came up to open Command Prompt and  setup JVM class path, wow! it sounded like the lecturer was speaking Alien language because i never knew what command prompt was used for and what the hell is JVM and class path? . At this point i was barely on track,  but managed to cope with the help of my Chinese classmates. I wondered why we had to do all those stuff and i was asking “are we not supposed to be making applications?”. What i could remember next was looking at the lecturer typing some characters and words with some bracket and telling us to run our program. At this point i have had enough, i opened facebook and updated my status to “What the hell is this java?”.

For a few lessons later, all i did in the class was browse facebook. I wasn’t interested in the agenda of the class. Then came an announcement “First lab test next week!” I was in deep trouble and failure wasn’t in my dictionary, That meant i had to learn. Thank God for one week Chinese new year break, i used this opportunity to learn my first java program. Thanks to Ahmed El-Yakub (Babi) and Mohammed Bello(Primes) for helping me during that period to understand my first java program.

Class Hello{

  • public static void main (String args[]){
    String s=”Abdulsalam”;
    System.out.print(“My name is :”+s);
    }

}

This was the first ever java code i wrote that ran successfully. When i look at it today, it gives me a big smile on my face because little had i known at that time what this little piece of code would make me today. At the end of my course, i had gone through a process and become a Sun Certified Java Programmer (SCJP). Today, i have done quite a lot with java with my largest piece of java code being about 19,000 lines of code.

Monopoly game code statistics

Sun Tech day

Me and James Gosling "Father of Java"

Another wonderful experience to share is when I met James Gosling, the man regarded as the father of Java. I went for a Sun technology Conference in Kuala Lumpur Convention Center (KLCC) in march 2007, there and then was a man standing who caught attention of everyone. I dint know him then, one of my mates whispered “I think I’ve seen his picture before, he’s James Gosling”. We all rushed to get his autographs and say hello, he was kind to us and exchanged a few words. At same event i watched the awesome things which Java could do, I saw the “Mission impossible” screen done right in front of me. There and then i became so interested in Java and  it became my passion in programming.

The moral is that one should be open to events in life as they unfold. Do not sit back and imagine what is going to happen, try to have a go at it and make an effort towards it. You never know could become of it, Mark Zuckerberg never new what Facebook was going to be when he started it. Know you passion and keep believing it it!

Thanks,  Salamtura.